Home > Database > Mysql Tutorial > How to Correctly Echo a MySQL Time Difference in PHP?

How to Correctly Echo a MySQL Time Difference in PHP?

DDD
Release: 2024-12-17 06:31:24
Original
625 people have browsed it

How to Correctly Echo a MySQL Time Difference in PHP?

Echoing a Time Difference from a MySQL Response in PHP

In PHP, you can use the mysql_query() function to execute SQL queries against a MySQL database. However, when you try to echo() the result of a query that returns a time difference, you may encounter the error message "Resource id #6."

Understanding the Error

The error "Resource id #6" indicates that the echo() statement is attempting to print a resource handle instead of the actual data. A resource handle is a unique identifier assigned to the result set by the MySQL server.

Solution

To display the time difference correctly, you need to use a fetch function to retrieve the actual data from the result set. There are several fetch functions available, including mysql_fetch_row(), mysql_fetch_array(), and mysql_fetch_assoc().

Here's an example that uses the mysql_fetch_assoc() function:

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

Note:

The mysql_* functions are deprecated and should not be used in new projects. Instead, use the PDO_MySQL or mysqli extensions.

Improved Example Using PDO

$pdo = new PDO('mysql:host=localhost;dbname=database_name', 'username', 'password');
$stmt = $pdo->prepare("SELECT TIMEDIFF(NOW(), :fecha) as time_delta");
$stmt->bindParam(':fecha', $row['fecha'], PDO::PARAM_STR);
$stmt->execute();
$data = $stmt->fetch(PDO::FETCH_ASSOC);
echo $data['time_delta'];
Copy after login

The above is the detailed content of How to Correctly Echo a MySQL Time Difference 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