What is the best way to retrieve data from a MySQL database in PHP and display it with different timestamps?
To retrieve data from a MySQL database in PHP and display it with different timestamps, you can use a SQL query to fetch the data along with the timestamps from the database. Then, you can format the timestamps using PHP functions like date() to display them in the desired format.
<?php
// Connect to MySQL database
$connection = mysqli_connect("localhost", "username", "password", "database");
// Check connection
if ($connection === false) {
die("ERROR: Could not connect. " . mysqli_connect_error());
}
// Select data with timestamps from database
$query = "SELECT data, UNIX_TIMESTAMP(timestamp) as timestamp FROM table";
$result = mysqli_query($connection, $query);
// Display data with timestamps
while ($row = mysqli_fetch_assoc($result)) {
echo "Data: " . $row['data'] . " - Timestamp: " . date('Y-m-d H:i:s', $row['timestamp']) . "<br>";
}
// Close connection
mysqli_close($connection);
?>
Keywords
Related Questions
- What strategies can be employed to optimize SQL queries in PHP when dealing with multiple tables and complex data relationships?
- What are the advantages and disadvantages of using mysql_num_rows versus COUNT() in PHP for counting database entries?
- What are some potential pitfalls when trying to dynamically access multiple elements in XML files using PHP?