What are some common mistakes to avoid when querying a database for time-sensitive data in PHP?
When querying a database for time-sensitive data in PHP, a common mistake to avoid is not properly handling time zones. It's important to ensure that the time zone settings are consistent between the PHP application and the database to accurately retrieve and display time-sensitive data.
// Set the default time zone for PHP
date_default_timezone_set('America/New_York');
// Connect to the database and set the time zone
$pdo = new PDO('mysql:host=localhost;dbname=mydatabase', 'username', 'password');
$pdo->exec("SET time_zone = 'America/New_York'");
// Query the database for time-sensitive data
$stmt = $pdo->prepare("SELECT * FROM mytable WHERE created_at > :time");
$stmt->bindValue(':time', date('Y-m-d H:i:s', strtotime('-1 day')));
$stmt->execute();
// Fetch and display the results
while ($row = $stmt->fetch()) {
echo $row['created_at'] . ' - ' . $row['data'] . '<br>';
}