Home > Database > Mysql Tutorial > How Can I Handle Query Failures When Using PHP's MySQL Extensions?

How Can I Handle Query Failures When Using PHP's MySQL Extensions?

Patricia Arquette
Release: 2024-12-29 12:50:15
Original
711 people have browsed it

How Can I Handle Query Failures When Using PHP's MySQL Extensions?

Handling Query Failures in PHP MySQL Extensions

When attempting to extract data from a MySQL table, occasionally, errors such as "mysql_fetch_array() expects parameter 1 to be resource, boolean given" may arise. This error indicates that the query function failed, resulting in a boolean value ("false") instead of the expected resource handle.

In the provided PHP code:

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

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

The error occurs because the query function (mysql_query) can return either true upon successful execution or false in case of failure. It should be noted that the provided SQL statement may fail due to various reasons, such as invalid syntax or non-existent table.

To resolve this, you should check the result of the query function before trying to fetch rows using mysql_fetch_array. If $result evaluates to false, it signifies that the query failed, and you should handle the error appropriately.

For the Deprecated MySQL Extension:

  • Use mysql_error to retrieve the error message associated with the query failure.
  • You may choose to output a user-friendly error message or log the error for debugging.
if($result === FALSE) {
    trigger_error(mysql_error(), E_USER_ERROR);
}
Copy after login

For the MySQLi Extension:

  • Check the mysqli_errno property of the mysqli object to get the error code.
  • Use mysqli_error to retrieve the error message.
  • Handle the error as appropriate.
if($result->errno) {
    // Log or output the error message
}
Copy after login

The above is the detailed content of How Can I Handle Query Failures When Using PHP's MySQL Extensions?. 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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template