Ryuk
Ryuk

Reputation: 95

Adding seconds to mysql DateTime via php

Im trying to add 12 seconds to a mysql datetime object via php.

My php code generates the following query: "UPDATE Stats SET Usage = 1970-01-01 00:00:12" however the query fails.

My php code is as follows:

public function UpdateTime($diffrence)
{
    $seconds = $diffrence / 1000;

    mysql_connect('localhost','user','pass') or die("Unable to select host");

    mysql_select_db('StatDB') or die("Unable to select database");

    $query  = "SELECT * FROM Stats";

    $result=mysql_query($query);

    $retVal = mysql_result($result,0,"Usage");

    $oldTime = new DateTime($retVal);

    $oldTime->modify('+'. $seconds .' seconds');

    $from = date("Y-m-d H:i:s", strtotime($oldTime->format('Y-m-d H:i:s')));

    $query2  = "UPDATE Stats SET Usage = $from";
    echo $query2;

    $result2=mysql_query($query2);

    mysql_close();
}

Does anyone how I can fix this?

Thanks

Upvotes: 1

Views: 498

Answers (3)

Bojan Dević
Bojan Dević

Reputation: 1875

You can do all of that using one single query:

UPDATE Stats SET Usage = Usage + INTERVAL $seconds SECOND

Upvotes: 0

DiscoInfiltrator
DiscoInfiltrator

Reputation: 2059

Try:

$query2  = "UPDATE `Stats` SET `Usage` = '$from'";

'Usage' is a reserved word in MySQL:

http://dev.mysql.com/doc/refman/5.0/en/reserved-words.html

Upvotes: 1

Aiias
Aiias

Reputation: 4748

This is likely related to missing quotes in your query. Check out the answer to this question.

UPDATE Stats SET Usage = '1970-01-01 00:00:12'

You should surround the date time value passed in single quotes.

Upvotes: 0

Related Questions