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

标签 php mysql

我尝试从 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][1] 文档,了解可能的返回值以及如何处理它们的建议。

$username = mysql_real_escape_string($_POST['username']);
$password = $_POST['password'];
$result = mysql_query("SELECT * FROM Users WHERE UserName LIKE '$username'");

if($result === FALSE) { 
    trigger_error(mysql_error(), E_USER_ERROR);
}

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

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

相关文章:

php - mysql查询错误

php - MYSQL在PHP中仅询问第一排名时不返回结果

php - 根据数据库字段内容自动(不是悬停)css 覆盖

php - VPS、Apache MySql 和 phpMyadmin 错误

php - 在 PHP 5.3 中使用实例方法的奇怪结果

mysql - 具有两列的子查询

php - 更新查询在我的代码中不起作用

php - 我在编写 MySQL 查询来提交包含文本和复选框的表单内容时陷入困境

php - 我如何比较两个数组并将唯一记录添加到表中

sql - 将用户存储在数据库中