1

So I've been trying to solve this one on my own for a few hours and it's driving me crazy.

I'm just trying to put a date into a mySQL database, the code looks like this:

$timeStarted = date("Y-m-d H:i:s", time());
$sqlquery = "INSERT INTO deviceStats (currTime, ...) VALUES ($timeStarted, ...)";
mysql_query($sqlquery);
echo $timeStarted;

My ajax return is telling me that $timeStarted is in the propper format, it's giving the right time, but if I have this one variable in my query, it won't run. the currTime field in the DB is set to datetime, so it should work.

2
  • why on earth did my question get downranked? Commented Jun 6, 2011 at 2:48
  • There are some idiots around, don't worry. I upvoted it. Commented Jun 6, 2011 at 4:23

2 Answers 2

3

Why not just use NOW()?

$sqlquery = "INSERT INTO deviceStats (currTime, ...) VALUES (NOW(), ...);
Sign up to request clarification or add additional context in comments.

5 Comments

I need to echo that NOW(), so I need something saved to a php variable. If I can echo NOW() then that's golden!
Run this query select NOW() (but running this after your first query will make the value slightly off). Or you can go mysql_last_insert_id(); and re-select the record to get the value of now.
can you output what the sql looks like exactly so that we can see what the complete statement looks like?
try wrapping the variable in a single quote. $sqlquery = "INSERT INTO deviceStats (currTime, ...) VALUES ('$timeStarted', ...)";
you called it, single quotes. I owe you a beer.
2

Your problem is that date strings in MySQL are exactly that, strings and as such must either be quoted (single quotes) or preferably, passed as parameters.

Using PDO, this would be quite simple

$stmt = $pdo->prepare('INSERT INTO `deviceStats` (`currTime`, ...) VALUES (?, ...)');
$ts = date('Y-m-d H:i:s');
$stmt->bindParam(1, $ts);
$stmt->execute();
echo $ts;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.