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 join tables with PHP and MySQL?
- How to get the version of MySQL using PHP?
- How to create an SSL connection to MySQL using PHP?
- How to use utf8mb4_unicode_ci in MySQL with PHP?
- How to get the error message for a MySQL query using PHP?
- How to run multiple queries in PHP and MySQL?
- How to escape JSON in PHP and MySQL?
- How to get the last insert ID in PHP MySQL?
- How to get a single value from query in PHP MySQL?
- How to get the number of affected rows in a MySQL using PHP?
See more codes...