Home >Database >Mysql Tutorial >How Can I Convert PHP Date Formats to MySQL\'s DATE and DATETIME Formats?

How Can I Convert PHP Date Formats to MySQL\'s DATE and DATETIME Formats?

DDD
DDDOriginal
2024-11-29 14:10:12155browse

How Can I Convert PHP Date Formats to MySQL's DATE and DATETIME Formats?

Converting PHP Date Formats to MySQL Compatibility

Inserting date data from PHP into a MySQL database requires adhering to the database's date formats. This article provides a solution for converting a PHP date variable, stored in the variable $date, to the MySQL format 0000-00-00 for database inclusion.

The provided PHP code uses the mysql_real_escape_string() function to secure the $_POST['intake_date'] input before assignment to the $date variable.

Depending on the MySQL column data type:


  • DATE Type:

  • $date = date('Y-m-d', strtotime(str_replace('-', '/', $date)));

  • DATETIME Type:

  • $date = date('Y-m-d H:i:s', strtotime(str_replace('-', '/', $date)));

These conversions involve replacing dash ('-') separators with forward slashes ('/') and applying the strtotime() function. However, if your date is formatted differently, e.g., '02/07/2009 00:07:00', use the following code:

$date = preg_replace('#(d{2})/(d{2})/(d{4})s(.*)#', '$3-$2-$1 $4', $date);

This will produce a date in the format '2009-07-02 00:07:00', compatible with the MySQL DATETIME data type.

The above is the detailed content of How Can I Convert PHP Date Formats to MySQL\'s DATE and DATETIME Formats?. 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