Home > Backend Development > PHP Tutorial > Why Do MySQL Fetch Functions Return 'expects parameter 1 to be resource'?

Why Do MySQL Fetch Functions Return 'expects parameter 1 to be resource'?

Mary-Kate Olsen
Release: 2024-12-23 03:02:35
Original
109 people have browsed it

Why Do MySQL Fetch Functions Return

Understanding the "mysql_fetch_..." Expecting Resource Error

When using MySQL functions such as mysql_fetch_array(), mysql_fetch_assoc(), mysql_fetch_row(), and mysql_num_rows, you may encounter the error: "mysql_fetch_array()/mysql_fetch_assoc()/mysql_fetch_row()/mysql_num_rows etc... expects parameter 1 to be resource."

The error indicates that the first parameter to the function is not a valid database resource. A database resource is typically obtained from a successful call to mysql_query(). If mysql_query() fails to execute the query, it returns false.

Addressing the Issue

To resolve this error, you need to ensure that the query is successfully executed before passing the result resource to the fetch functions. This involves checking the return value of mysql_query() and handling the error condition accordingly.

Example for mysql_extension

<?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

In this example, mysql_real_escape_string() prepares the username string for the query to prevent SQL injections. We check the return value of mysql_query() and trigger a user error if the query fails. If the query is successful, we can safely use the result resource in the mysql_fetch_array() function.

The above is the detailed content of Why Do MySQL Fetch Functions Return 'expects parameter 1 to be resource'?. 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