Home  >  Article  >  Database  >  How to Insert the Current Date and Time into a MySQL Database Using PHP?

How to Insert the Current Date and Time into a MySQL Database Using PHP?

Barbara Streisand
Barbara StreisandOriginal
2024-10-30 11:12:09667browse

How to Insert the Current Date and Time into a MySQL Database Using PHP?

MySQL Insertion of Current Date in Datetime Format

Problem:

Incorrect date insertion into a database when using PHP's date() function and the specified format.

Solution:

Method 1: Using MySQL's NOW() Function

Utilize MySQL's NOW() function to automatically generate and insert the current date and time:

<code class="php">mysql_query("INSERT INTO `table` (`dateposted`) VALUES (now())");</code>

Method 2: Modifying PHP Format

If using PHP's date() function, ensure the correct datetime format is used:

Modified Code:

<code class="php">$date = date('Y-m-d H:i:s');
mysql_query("INSERT INTO `table` (`dateposted`) VALUES ('$date')");</code>

This format aligns with MySQL's datetime data type, resolving the issue of inserting 00:00:00 timestamps.

The above is the detailed content of How to Insert the Current Date and Time into a MySQL Database Using PHP?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn