Inserting integer and datetime from PHP to MySQL 5

2019-07-27 05:32发布

问题:

I have tried to find out what's wrong.

The table is conditions_loop. One column is condition_id, and the other one is a datetime type.

the code is this

$dt = date("Y-m-d H:i:s");

mysql_query("INSERT INTO conditions_loop (condition_id, date) VALUES ($latest_condition, $dt)") or die(mysql_error());  

$latest_condition is a 1 digit integer.

The error says You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '13:12:14)' at line 1

I tried everything, but it's something I don't know. Thanks for reading.

回答1:

You should quote the date value:

mysql_query("INSERT INTO `conditions_loop` (`condition_id`, `date`) 
         VALUES ('$latest_condition', '$dt')") or die(mysql_error());  

And while you're at it, quote the table/field names as well, using backticks (`)