简体   繁体   English

如何将日期保存到数据库?

[英]How to save date to database?

I have a database column called "worked", it is set to DATETIME type.我有一个名为“worked”的数据库列,它被设置为 DATETIME 类型。 I want this to hold the time that is inserted into it.我希望它能够保存插入其中的时间。

I get the date like this我得到这样的日期

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

I then echo it to check it like this然后我 echo 它像这样检查它

echo $date,"</br>";

Which displays哪个显示

2014-10-21 21:35:12

So that works, but I now want to save that $date into the "worked" column, like this这样就可以了,但我现在想将该 $date 保存到“已工作”列中,就像这样

$ins2 = mysqli_query($con,"UPDATE stats SET stats.worked = $date WHERE stats.id=$id2");

id2 is the ID of the user logged in and it is correct. id2是登录用户的ID,是正确的。

The problem is that it doesn't do anything!问题是它什么都不做!

Nothing happens, the field stays as "0000-00-00 00:00:00"没有任何反应,该字段保持为“0000-00-00 00:00:00”

It didn't work for you, because you didn't enclose the date in quotes.它对您不起作用,因为您没有将日期括在引号中。 Dates are string literals and every string literal in SQL must be enclosed in quotes.日期是字符串文字,SQL 中的每个字符串文字都必须用引号括起来。

This is not the right way to pass the data to SQL though.但是,这不是将数据传递给 SQL 的正确方法。 You should pass the data via parameters.您应该通过参数传递数据。

Using mysqli it would look like this:使用 mysqli 它看起来像这样:

$ins2 = $con->prepare('UPDATE stats SET stats.worked = ? WHERE stats.id=?');
$ins2->bind_param('ss', $date, $id2);
$ins2->execute();

However, I strongly recommend to use PDO instead of mysqli.但是,我强烈建议使用 PDO 而不是 mysqli。 It is much simpler.这要简单得多。 The same code in PDO is one line only. PDO 中的相同代码只有一行。

$pdo->prepare('UPDATE stats SET stats.worked = ? WHERE stats.id=?')->execute([$date, $id2]);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM