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-DD
and stores it in the$date
variable.$sql = "INSERT INTO table_name (date_column) VALUES ('$date')";
: This line creates an SQL query to insert the date stored in the$date
variable into thedate_column
of thetable_name
table.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 use utf8mb4_unicode_ci in MySQL with PHP?
- How to join tables with PHP and MySQL?
- How to get the version of MySQL using PHP?
- How to write an update query in MySQL using PHP?
- How to count the number of resulting rows in a MySQL database using PHP?
- How to use a MySQL union in PHP?
- How to set a timeout for MySQL query in PHP?
- How to create an SSL connection to MySQL using PHP?
- How to get the last insert ID in PHP MySQL?
- How to fetch data from MySQL in PHP?
See more codes...