How can the NOW() function in MySQL be integrated into a PHP script for inserting current dates?
To integrate the NOW() function in MySQL into a PHP script for inserting current dates, you can simply include the NOW() function in your SQL query when inserting data into a datetime field. This way, the current date and time will be automatically inserted into the database whenever the PHP script is executed.
<?php
// Establish a connection to the 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);
}
// Inserting current date and time into a datetime field
$sql = "INSERT INTO table_name (date_column) VALUES (NOW())";
if ($conn->query($sql) === TRUE) {
echo "Record inserted successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
// Close the connection
$conn->close();
?>