huong
huong

Reputation: 4564

Trouble saving date and time to MySQL using PHP

I'm writing a website and I'm having a problem with saving date and time to MySQL database using PHP but all I got for the date is 0000-00-00 00:00:00. I'm not sure what's the problem with my code so I hope you guys can help me point it out.

Below is the INSERT function I store in an external php file for convenience

 <?php
    class FITQuery {    
        public static function insert($table, $fields, $values, $condition = null) {

        $query = "INSERT INTO ".$table;

        $query .= '(';

        for ($i = 0; $i < count($fields) - 1; $i++) {
            $query .= $fields[$i].',';
        }

        $query .= $fields[count($fields) - 1];

        $query .= ') VALUES (';

        for ($i = 0; $i < count($values) - 1; $i++) {
            $query .= "'".$values[$i]."',";
        }

        $query .= "'".$values[count($values) - 1]."'";

        $query .= ') ';     

        if (mysql_query($query)) return true;
        else die("INSERT:".mysql_error());
    } 

} ?>

And here is the code where I use the INSERT:

<?php
if (!empty($_POST)) {
    // POST PROCESS
    $title = $_POST['title'];
    $short_desc  = $_POST['short_desc'];
    $content = $_POST['content'];   
    // FILE UPLOAD
    if (isset($_FILES['avatar'])) {      
        $avatar = FITUtils::uploadFile($_FILES['avatar']['name'], $_FILES['avatar']['tmp_name'], "../uploads");
    }
    else $avatar = null;

    // Insert
    FITQuery::insert('news', array('title','short_desc','content','avatar','created_date'), 
        array($title, $short_desc, $content, $avatar, FITUtils::getDate()));

    FITUtils::redirect('index.php?page=news');
}
else {

}
?>

I'm pretty sure it's not the INSERT function's problem because I already tried the "traditional" way but still got the same result. Anyone has some suggestions for me? I'm a newbie in PHP so I hope that you guys can help me with this. Thanks!

Upvotes: 0

Views: 320

Answers (2)

Zahid Khan
Zahid Khan

Reputation: 1260

Use variable to store date and time, your database field must have field type Date. and do it like this:

$date_time= SYSDATE;

Then use this variable to insert into database using query.

Hope it works good as I've used this one...

Upvotes: 0

J. Bruni
J. Bruni

Reputation: 20490

Try changing FITUtils::getDate() to

date('Y-m-d H:i:s', strtotime(FITUtils::getDate()))

The date format expected by MySQL is like 2011-12-17 04:20:00 which corresponds to the "format" parameter Y-m-d H:i:s passed to the date function in the suggestion above.

I don't know the date format returned by FITUtils::getDate(). If it is a string, then strftime will transform it into a timestamp, so we can use it as the second parameter for the date function. If it already returns a timestamp, then you may try the following code instead:

date('Y-m-d H:i:s', FITUtils::getDate())

Upvotes: 3

Related Questions