What is the correct way to insert the current date and time into a MySQL database using PHP?
To insert the current date and time into a MySQL database using PHP, you can use the NOW() function in your SQL query. This function retrieves the current date and time from the system. You can simply include the NOW() function in your INSERT query to automatically insert the current date and time into a datetime field in your database.
<?php
// Connect to MySQL database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Insert current date and time into database
$sql = "INSERT INTO table_name (date_time_column) VALUES (NOW())";
if ($conn->query($sql) === TRUE) {
echo "Record inserted successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
// Close connection
$conn->close();
?>
Related Questions
- Are there specific PHP functions or methods that are recommended for handling user login status in a forum setting?
- What are the best practices for setting the character encoding (UTF-8) in PHP files included via include statements?
- What role does the use of SESSION variables play in maintaining order number consistency in PHP when dealing with customer orders?