Home >Database >Mysql Tutorial >How to Fix the 'Resource id #' Error When Echoing MySQL Query Results in PHP?

How to Fix the 'Resource id #' Error When Echoing MySQL Query Results in PHP?

Linda Hamilton
Linda HamiltonOriginal
2025-01-01 14:56:12638browse

How to Fix the

Echoing MySQL Query Results in PHP: Overcoming "Resource id #" Error

When working with MySQL databases in PHP, you may encounter the "Resource id #" error while attempting to echo the result of a query. This error message indicates that you're trying to directly echo a MySQL resource handle instead of the actual query result.

To resolve this issue and retrieve the intended result, you need to employ a fetch function. The following approach illustrates how to use the mysql_fetch_assoc() function to fetch and print the query result:

$result = mysql_query(sprintf("SELECT TIMEDIFF(NOW(), '%s') as time_delta", $row['fecha']));
if ($result) {
  $data = mysql_fetch_assoc($result);
  echo $data['time_delta'];
}

In this code:

  • The first line executes the query and receives a resource handle as a result.
  • The second line checks if the query was successful.
  • The mysql_fetch_assoc() function (third line) fetches the next row from the result resource as an associative array ($data).
  • The desired result can then be accessed using the array key ('time_delta' in this case).

Caution:

While the mysql functions are still available, their use in new projects is strongly discouraged. Consider utilizing the PDO extension with the PDO_mysql PDO driver or the mysqli extension for improved security and maintainability.

The above is the detailed content of How to Fix the 'Resource id #' Error When Echoing MySQL Query Results in PHP?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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