简体   繁体   中英

Insert PHP date into MySQL database

I need to insert a date field from a form into a mysql database. If the user does not input a date, the current date should be used. My code is :

if ($_POST[date]==0)
    {$ref_date=date('Y-d-m');}
    else {$ref_date=$_POST[date];}

$L="insert into referral (ID,patient, Doctor,Date) values (default,$pat,$doc,'$ref_date')";
        mysql_query($L) or die(mysql_error());

It works fine when I submit a date in the form, but when I leave that field blank it inputs 0000-00-00.

MySQL expects dates to be in YYYY-MM-DD format. You have YYYY-DD-MM . Change:

$ref_date=date('Y-d-m');

to:

$ref_date=date('Y-m-d');

You should pay attention, though, that Apache's (or whatever php server you're using) may have a different time/timezone compared to your MySQL server.

Let's say Apache's server is 2h ahead of MySQL. If it's 1 am of January 22 (in Apache), then using date('Ỹ-m-d') would return 2015-01-22, and CURDATE() (MySQL current date's function) would return 2015-01-21.

So, there are 2 possible solutions. One is John Conde's solution:

$ref_date = date('Y-d-m');

The other would be insert CURDATE():

$ref_date = 'CURDATE()';

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM