Home >Database >Mysql Tutorial >How Can I Convert PHP Date Formats to MySQL\'s DATE and DATETIME Formats?
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 = date('Y-m-d', strtotime(str_replace('-', '/', $date)));
$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!