How can PHP be used to automatically insert the current date and time into a MySQL database when adding new entries?
To automatically insert the current date and time into a MySQL database when adding new entries, you can use the NOW() function in MySQL combined with PHP. In your PHP code, you can construct the SQL query and include NOW() in the appropriate column to insert the current date and time.
<?php
// Connect to MySQL database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database_name";
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Prepare SQL query to insert new entry with current date and time
$sql = "INSERT INTO table_name (column1, column2, date_time_column) VALUES ('value1', 'value2', NOW())";
// Execute SQL query
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
// Close database connection
$conn->close();
?>
Keywords
Related Questions
- What are the best practices for creating a custom IP ban system in PHP to protect against malicious bots and users?
- What are the disadvantages of using the @ symbol in PHP code for error suppression?
- What are the potential pitfalls of using a one-dimensional array for implementing tree structures in PHP?