一尘不染

警告:mysql_fetch_ *期望参数1为资源,布尔值给定错误[重复]

mysql

我正在尝试从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'];
}

阅读 245

收藏
2020-05-17

共1个答案

一尘不染

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

mysql_ *扩展名

注:mysql_功能已被弃用,并在PHP版本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扩展
程序样式

$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。另外,数据库错误消息不应显示给非管理员用户,因为它会显示过多信息

2020-05-17