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']; }
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'];
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!