user756659
user756659

Reputation: 3512

Cannot insert UTC_TIMESTAMP() with pdo prepared statement

How can I use UTC_TIMESTAMP() with this prepared insert statement? It is not liking the format/binding and errors out.

// prepare the statement
$stmt = $db->prepare("INSERT INTO accounts (
        account_username,
        account_password,
        account_email,
        fname,
        lname,
        dtCreated
    ) VALUES (
        :account_username,
        :account_password,
        :account_email,
        :fname,
        :lname,
        :dtCreated
    )
");

//set bindings
$binding = array(
    'account_username' => $_POST['username'],
    'account_password' => $newhash,
    'account_email' => $_POST['email'],
    'fname' => $_POST['fname'],
    'lname' => $_POST['lname'],
    'dtCreated' => UTC_TIMESTAMP()
    );

// execute the insert
$stmt->execute($binding);

Upvotes: 0

Views: 471

Answers (2)

SameOldNick
SameOldNick

Reputation: 2457

Specify the UTC_TIMESTAMP() in the statement itself and not as a parameter.

$stmt = $db->prepare("INSERT INTO accounts (
        account_username,
        account_password,
        account_email,
        fname,
        lname,
        dtCreated
    ) VALUES (
        :account_username,
        :account_password,
        :account_email,
        :fname,
        :lname,
        UTC_TIMESTAMP()
    )
");

//set bindings
$binding = array(
    'account_username' => $_POST['username'],
    'account_password' => $newhash,
    'account_email' => $_POST['email'],
    'fname' => $_POST['fname'],
    'lname' => $_POST['lname']
);

// execute the insert
$stmt->execute($binding);

If you do this:

$stmt = $db->prepare("INSERT INTO accounts (
        account_username,
        account_password,
        account_email,
        fname,
        lname,
        dtCreated
    ) VALUES (
        :account_username,
        :account_password,
        :account_email,
        :fname,
        :lname,
        :dtCreated
    )
");

//set bindings
$binding = array(
    'account_username' => $_POST['username'],
    'account_password' => $newhash,
    'account_email' => $_POST['email'],
    'fname' => $_POST['fname'],
    'lname' => $_POST['lname'],
    'dtCreated' => UTC_TIMESTAMP()
);

// execute the insert
$stmt->execute($binding);

Then UTC_TIMESTAMP() gets turned into a string (because its not a PHP function) and the SQL statement ends up being turned into:

    INSERT INTO accounts (
        account_username,
        account_password,
        account_email,
        fname,
        lname,
        dtCreated
    ) VALUES (
        'jblow',
        'password',
        '[email protected]',
        'Joe',
        'Blow',
        'UTC_TIMESTAMP()'
    );

And if you notice, UTC_TIMESTAMP() is specified as a string which will not work.

Upvotes: 2

Knoweldges
Knoweldges

Reputation: 72

You can do that using the NOW() MySQL function I guess.

Upvotes: 0

Related Questions