小编典典

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

all

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

mysql_fetch_array() 期望参数 1 是资源,给定的布尔值

这是我的代码:

$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'];
}

阅读 90

收藏
2022-02-28

共1个答案

小编典典

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

mysql_* 扩展名

注意 mysql_函数已被弃用,并已在 php 版本 7 中删除。

在传递$resultmysql_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 扩展
程序风格

$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 ) {
      ...

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

2022-02-28