简体   繁体   中英

How to use Now() with PDO

I'm just interesting, should I use Now() inside query or I should make an array for that? This is my code and it's working, but not sure about this..

$STH = $DBH->prepare('INSERT INTO users SET username = :username, password = :password, email = :email, joined = NOW(), usergroup = :usergroup, favourite_genre = :genre');
$STH->execute(array(
    ':username' => $username,
    ':password' => $password,
    ':email' => $email,
    ':usergroup' => 0,
    ':genre' => $_POST['genre']
));

A timestamp is a timestamp, without further context it makes little difference what generates the timestamp. Currently you're generating that value on the database, what you propose is to generate that value in the PHP application.

Both methods will successfully generate a timestamp.

If the database is being used by other applications, potentially accessed from other systems, then depending on the use cases you may want to rely on the database for generating the timestamps so that the values will be internally consistent. Though even then there would need to be a high degree of precision for it to matter.

Now, if multiple systems with different location/culture settings are accessing the database, then it would definitely be a good idea to centralize the timestamp creation on the database itself.

Shouldn't the query be in this form?

$data = array(
        "email"    => $email,
        "password" => $password,
        "salt"     => $salt,
        "ingame"   => $ingame,
        "kiosk"    => $kiosk,
);
$dbh->query("INSERT INTO ?n SET reg = NOW(), ?u","users", $data);

Datetime fields do not accept defaults values they are not than timestamp fields.

So I do this:

<?php

$STH = $DBH->prepare('INSERT INTO users SET username = :username, password = :password, email = :email, joined = :joined, usergroup = :usergroup, favourite_genre = :genre');
$STH->execute(array(
    ':username' => $username,
    ':password' => $password,
    ':email' => $email,
    ':joined' => date ("Y-m-d H:i:s", time());
    ':usergroup' => 0,
    ':genre' => $_POST['genre']
));

?>

See you my friend!

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