Home >Backend Development >PHP Tutorial >How Do I Access MySQL Response Values in PHP?

How Do I Access MySQL Response Values in PHP?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-02 14:35:02651browse

How Do I Access MySQL Response Values in PHP?

Accessing MySQL Response Values in PHP

In PHP, when querying a MySQL database, the result is stored in a resource handle. This can lead to confusion when attempting to print or use the response data.

Problem:

Consider the following code:

<code class="php">$datos1 = mysql_query("SELECT TIMEDIFF(NOW(), '" . $row['fecha'] . "');");
echo($datos1);</code>

This code returns "Resource id #6" instead of the expected value.

Solution:

To access the actual response data, you need to use a fetch function. Here's an updated example:

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

In this code:

  • mysql_fetch_assoc() retrieves the first row from the result set and converts it into an associative array.
  • echo $data['time_delta'] prints the value of the "time_delta" column from the first row.

Caution:

The mysql functions are deprecated and it is recommended to use the PDO or mysqli extensions instead for database handling.

The above is the detailed content of How Do I Access MySQL Response Values 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