简体   繁体   中英

Cannot update Date field - MySQL PHP

My webpage has a date field which uses javascript calendar. The format of the date field on web page is MM/DD/YYYY. When the user enters all information and hits submit, all fields except the corresponding field of Date gets updated. Here are details:

HTML:

 <tr>
      <td><label><font color="red">*</font>Date:</label></td>
      <td><input name= "Date" value="Select Date" id="popupDatepicker"></td>
 </tr>

PHP Code:

<?php
      $sql = "INSERT INTO MYTABLE (...., USER_DATE, ...) VALUES (...., '$_POST[Date]', ...)"
     ....
?>

MySQL: USER_DATE: DATETIME datatype.

When a new record in inserted, the USER_DATE shows 0000-00-00 00:00:00 as value even when the Date field is populated on the UI side.

Can anyone please guide me as to the issue here.

MM/DD/YYYY is not the datetime format that MySQL uses.

Try this...

date('Y-m-d', strtotime($date));

Example

$date = '02/07/2011';

$sqlDate = date('Y-m-d', strtotime($date));

var_dump($sqlDate); // string(10) "2011-02-07"

CodePad .

When inserting a date to a MySQL datetime field, your must use YYYY-MM-DD format.


As a sidenote : you must escape strings, using mysql_real_escape_string() or mysqli_real_escape_string() , depending on the set of functions you are using, to prevent SQL Injections !

Change the date format after submitting the form.

Mysql accept date in yyyy-mm-dd format

echo date('Y-m-d',strtotime($_POST['date']));

If you don't want to use the standard DATETIME format yyyy-mm-dd hh:mm:ss you can use a TIMESTAMP which is an integer with the number of seconds passed since Jan 01, 1970 or you could also use a VARCHAR where you insert what you want.

My opinion is to go for the TIMESTAMP since afterwards you can format it as you like with php's date functions.

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