简体   繁体   中英

How to save date to database?

I have a database column called "worked", it is set to DATETIME type. 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 $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

$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.

The problem is that it doesn't do anything!

Nothing happens, the field stays as "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.

This is not the right way to pass the data to SQL though. You should pass the data via parameters.

Using mysqli it would look like this:

$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. It is much simpler. The same code in PDO is one line only.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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