进入mySQL数据库的PHP日期无法按计划运行

进入mySQL数据库的PHP日期无法按计划运行

问题描述:

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.

所以我一直试图独自解决这个问题几个小时,这让我发疯了。 / p>

我只想在mySQL数据库中输入日期,代码如下: p>

  $ timeStarted = date(“  Ymd H:i:s“,time()); 
 $ sqlquery =”INSERT INTO deviceStats(currTime,...)VALUES($ timeStarted,...)“; 
mysql_query($ sqlquery); 
echo $  timeStarted; 
  code>  pre> 
 
 

我的ajax返回告诉我$ timeStarted属于propper格式,它给出了正确的时间,但如果我在查询中有这个变量 ,它不会运行。 DB中的currTime字段设置为datetime,因此它应该可以工作。 p> div>

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;

Why not just use NOW()?

$sqlquery = "INSERT INTO deviceStats (currTime, ...) VALUES (NOW(), ...);