How to Convert a PHP Date to MySQL \'YYYY-MM-DD\' Format?

Patricia Arquette
Release: 2024-10-26 23:47:30
Original
368 people have browsed it

How to Convert a PHP Date to MySQL

Converting PHP Date to MySQL Format

When working with dates in PHP and MySQL, it's essential to format them correctly for proper insertion into the database.

The question arises: How can we convert a PHP date into the MySQL format of "YYYY-MM-DD"?

Assume we have a date field in PHP set as:

<code class="php">$date = mysql_real_escape_string($_POST['intake_date']);</code>
Copy after login

To convert this PHP date to MySQL format, consider the following:

If the MySQL column is of the DATE type:

<code class="php">$date = date('Y-m-d', strtotime(str_replace('-', '/', $date)));</code>
Copy after login

If the MySQL column is of the DATETIME type:

<code class="php">$date = date('Y-m-d H:i:s', strtotime(str_replace('-', '/', $date)));</code>
Copy after login

It's important to note that strtotime() will not work with hyphen (-) separators. Therefore, it's necessary to replace the hyphens with slashes before using strtotime().

Alternatively, for the date format you provided, which includes time, you can also use this regular expression based approach:

<code class="php">$date = '02/07/2009 00:07:00';
$date = preg_replace('#(\d{2})/(\d{2})/(\d{4})\s(.*)#', '-- ', $date);
echo $date;</code>
Copy after login

This will output the correct MySQL format of "YYYY-MM-DD HH:MM:SS".

The above is the detailed content of How to Convert a PHP Date to MySQL \'YYYY-MM-DD\' Format?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template