Home > Database > Mysql Tutorial > Why Am I Getting the 'mysql_fetch_array() expects parameter 1 to be resource, boolean given' Error in PHP?

Why Am I Getting the 'mysql_fetch_array() expects parameter 1 to be resource, boolean given' Error in PHP?

DDD
Release: 2024-12-22 06:05:09
Original
591 people have browsed it

Why Am I Getting the

Error Message: "mysql_fetch_array()/mysql_fetch_assoc()/mysql_fetch_row()/mysql_num_rows etc... expects parameter 1 to be resource, boolean given"

This error occurs when calling a function that expects a resource as the first parameter, but a boolean value is passed instead. In this specific case, it indicates that the query failed, resulting in a false value being returned.

Solution:

To resolve this issue, check the result of the MySQL query before passing it to the data retrieval functions. In PHP's mysql_ extension, use mysql_query() and test its return value. If the query fails, you can handle the error accordingly or issue a trigger.

Here's an example with improved error handling:

<?php
$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'];
}
?>
Copy after login

By using mysql_real_escape_string() to sanitize user input, you can also prevent SQL injection attacks, which can be a cause of query failure.

The above is the detailed content of Why Am I Getting the 'mysql_fetch_array() expects parameter 1 to be resource, boolean given' Error in PHP?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template