php-mysqlHow to insert a date into a MySQL database using PHP?
To insert a date into a MySQL database using PHP, you can use the mysqli_query() function. The following example code will insert a date into the date_column of the table_name table:
$date = date("Y-m-d");
$sql = "INSERT INTO table_name (date_column) VALUES ('$date')";
if (mysqli_query($conn, $sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
Output example
New record created successfully
Code explanation
$date = date("Y-m-d");: This line creates a date string in the format ofYYYY-MM-DDand stores it in the$datevariable.$sql = "INSERT INTO table_name (date_column) VALUES ('$date')";: This line creates an SQL query to insert the date stored in the$datevariable into thedate_columnof thetable_nametable.if (mysqli_query($conn, $sql)) {: This line checks if the query was successful.echo "New record created successfully";: This line prints a success message if the query was successful.echo "Error: " . $sql . "<br>" . mysqli_error($conn);: This line prints an error message if the query was unsuccessful.
Helpful links
More of Php Mysql
- How to check if a record exists in PHP and MySQL?
- How to get the version of MySQL using PHP?
- How to write an update query in MySQL using PHP?
- How to use a MySQL union in PHP?
- How to use a variable in a MySQL query using PHP?
- How to update to null value in MySQL using PHP?
- How to set a timeout for MySQL query in PHP?
- How to join tables with PHP and MySQL?
- How to get a key-value array from a MySQL database using PHP?
- How to change database in MySQL with PHP?
See more codes...