gpt4 book ai didi

php - mysql_fetch_array()/mysql_fetch_assoc()/mysql_fetch_row()/mysql_num_rows 等...期望参数1是资源

转载 作者:行者123 更新时间:2023-11-29 23:57:01 25 4
gpt4 key购买 nike

我正在尝试从 MySQL 表中选择数据,但收到以下错误消息之一:

mysql_fetch_array() expects parameter 1 to be resource, boolean given



这是我的代码:
$username = $_POST['username'];
$password = $_POST['password'];

$result = mysql_query('SELECT * FROM Users WHERE UserName LIKE $username');

while($row = mysql_fetch_array($result)) {
echo $row['FirstName'];
}

最佳答案

查询可能由于各种原因而失败,在这种情况下 mysql_* 和 mysqli 扩展都将返回 false从他们各自的查询功能/方法。您需要测试该错误情况并相应地处理它。

mysql_* extension :

NOTE The mysql_ functions are deprecated and have been removed in php version 7.



查看 $result在传递给 mysql_fetch_array 之前.你会发现它是 false因为查询失败。见 mysql_query 可能返回值的文档以及如何处理它们的建议。
$username = mysql_real_escape_string($_POST['username']);
$password = $_POST['password'];
$result = mysql_query("SELECT * FROM Users WHERE UserName LIKE '$username'");

if($result === FALSE) {
die(mysql_error()); // TODO: better error handling
}

while($row = mysql_fetch_array($result))
{
echo $row['FirstName'];
}

mysqli extension
程序风格:
$username = mysqli_real_escape_string($mysqli, $_POST['username']);
$result = mysqli_query($mysqli, "SELECT * FROM Users WHERE UserName LIKE '$username'");

// mysqli_query returns false if something went wrong with the query
if($result === FALSE) {
yourErrorHandler(mysqli_error($mysqli));
}
else {
// as of php 5.4 mysqli_result implements Traversable, so you can use it with foreach
foreach( $result as $row ) {
...

oo 风格:
$username = $mysqli->escape_string($_POST['username']);
$result = $mysqli->query("SELECT * FROM Users WHERE UserName LIKE '$username'");

if($result === FALSE) {
yourErrorHandler($mysqli->error); // or $mysqli->error_list
}
else {
// as of php 5.4 mysqli_result implements Traversable, so you can use it with foreach
foreach( $result as $row ) {
...

使用准备好的语句:
$stmt = $mysqli->prepare('SELECT * FROM Users WHERE UserName LIKE ?');
if ( !$stmt ) {
yourErrorHandler($mysqli->error); // or $mysqli->error_list
}
else if ( !$stmt->bind_param('s', $_POST['username']) ) {
yourErrorHandler($stmt->error); // or $stmt->error_list
}
else if ( !$stmt->execute() ) {
yourErrorHandler($stmt->error); // or $stmt->error_list
}
else {
$result = $stmt->get_result();
// as of php 5.4 mysqli_result implements Traversable, so you can use it with foreach
foreach( $result as $row ) {
...

这些示例仅说明应该做什么(错误处理),而不是如何去做。生产代码不应使用 or die 输出 HTML 时,否则它将(至少)生成无效的 HTML。此外,不应向非管理员用户显示数据库错误消息,因为它 discloses too much information .

关于php - mysql_fetch_array()/mysql_fetch_assoc()/mysql_fetch_row()/mysql_num_rows 等...期望参数1是资源,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25274157/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com