Greeso
Greeso

Reputation: 8269

Inserting DATETIME into MySQL

I am having a problem inserting DATETIME into MySQL using PHP.

First, I am fetching a date from the news table:

$statement = $db->query("SELECT utcPublishedDate FROM News WHERE idNews = $newsID");
$row = $statement->fetch(PDO::FETCH_ASSOC);
$utcPublishedDate = $row["utcPublishedDate"];

Then I am doing some date manipulation on that date due to some code requirements, eventually this date is changing to something else.

Now, I have to update the table, so:

$statement = $db->query("UPDATE News SET utcPublishedDate = $utcPublishedDate WHERE idNews = $newsID");

This is causing an error. If I do this:

$statement = $db->query("UPDATE News SET utcPublishedDate = NOW() WHERE idNews = $newsID");

The statement will execute without a problem.

Now, how do I solve the error I am getting? Obviously It is something to do with the fact there are spaces in my DATETIME field. Suggestions please? Thanks.

Upvotes: 0

Views: 1415

Answers (2)

Jeffrey Carandang
Jeffrey Carandang

Reputation: 408

Convert the DATETIME via php first so that it will be Mysql valid datetime. Use this:

$utcPublishedDate = date('Y-m-d H:i:s', strtotime($utcPublishedDate));   $statement = $db->query("UPDATE News SET utcPublishedDate = '$utcPublishedDate' WHERE idNews = $newsID");

Cheers

Upvotes: 0

Dawson Loudon
Dawson Loudon

Reputation: 6029

try changing:

$statement = $db->query("UPDATE News SET utcPublishedDate = $utcPublishedDate WHERE idNews = $newsID");

to:

$statement = $db->query("UPDATE News SET utcPublishedDate = '$utcPublishedDate' WHERE idNews = $newsID");

Upvotes: 2

Related Questions