How to convert date to textbox to MySQL DATETIME format

I am new to php and was reading Larry Ullman's book for developing a basic db site. I used the YUI Calendar pop up date picker to add a date to a text box called "date". The date format it comes in is for example Thursday, May 7, 2009.

I have tried many different ways to try to enter a date in mysql db but it stays at 00 00 00 00 00 00 This is the code related to the date field I have,

    // Check for a Date.
if (eregi ("^([0-9]{2})/([0-9]{2})/([0-9]{4})$", $_POST['date'],)) {
    $p = escape_data($_POST['date'],);
} else {
    $p = FALSE;
    echo '<p><font color="red">Please enter a valid Date!</font></p>';
}

    // Add the URL to the urls table.
    $query = "INSERT INTO urls (url, title, description, date) VALUES ('$u', '$t', '$d', '$p')";        
    $result = @mysql_query ($query); // Run the query.
    $uid = @mysql_insert_id(); // Get the url ID.

    if ($uid > 0) { // New URL has been added.

      

I think I have provided all the relevant information, but again I apologize if this does not help and I will do my best to provide you with any other information you may need. Thanks - Sean

0


a source to share


3 answers


If the format your choice of date takes is "Thursday, May 7, 2009" then strtotime () and the date () function should work to give you a valid date to go to MySQL:

$p = date("Y-m-d H:i:s",strtotime('Thursday, 7 May 2009'));

      



If the database field is DATE, you probably only need the "Ymd" part. If it's DATETIME, you will also need "H: i: s".

0


a source


You probably need to format the date so that mysql expects it for that data type, otherwise it won't be able to recognize it. You can use a regular expression or similar method to extract the components and format it according to the MySQL DATETIME type format.



EDIT: See http://dev.mysql.com/doc/refman/5.0/en/datetime.html for the specified format. Also, you might be better off storing the date / time as a unix timestamp, as it is usually easier to maintain.

0


a source


date format in mysql is YYYY-MM-DD, so change your way of receiving data to php

if (eregi ("^ ([0-9] {2}) / ([0-9] {2}) / ([0-9] {4}) $", $ _POST ['date'],) ) {$ p = escape_data ($ _ POST ['date'],); } else {$ p = FALSE; echo '

Please enter a valid date!

';

Should be

if (eregi ("^ ([0-9] {4} / ([0-9] {2}) / ([0-9] {2})) $", $ _POST ['date'],) ) {$ p = escape_data ($ _ POST ['date'],); } else {$ p = FALSE; echo '

Please enter a valid date!

';
0


a source







All Articles