Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inserting datetime NOW() in database with prepared statements

Tags:

php

mysql

I'm trying to insert date when user make registration but doesn't work. It didn't insert anything when I add NOW() to the query. If I remove it user is added into database.

This is normal query

$stmt = $pdo->prepare('INSERT INTO users (username,password,email,active) VALUES (:username, :password, :email, :active');
$stmt->execute(array(
    ':username' => $_POST['username'],
    ':password' => $hashedpassword,
    ':email' => $_POST['email'],
    ':active' => $activasion
));

I've read other threads and tried this

$stmt = $pdo->prepare('INSERT INTO users (username,password,email,created,active) VALUES (:username, :password, :email, NOW(), :active');
$stmt->execute(array(
    ':username' => $_POST['username'],
    ':password' => $hashedpassword,
    ':email' => $_POST['email'],
    ':active' => $activasion
));

just added created and NOW() to the query but didn't insert anything.

What can be the problem?

like image 490
S.I. Avatar asked Jun 03 '26 17:06

S.I.


1 Answers

You are missing closing parenthesis on the SQL you are feeding to prepare():

$stmt = $pdo->prepare('INSERT INTO users (username,password,email,created,active) VALUES (:username, :password, :email, NOW(), :active');

It should be

$stmt = $pdo->prepare('INSERT INTO users (username,password,email,created,active) VALUES (:username, :password, :email, NOW(), :active)');

As @VincentDecaux suggests, your error checking should catch this. Use the following to enable exceptions, if that's what you prefer:

$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
like image 90
vhu Avatar answered Jun 05 '26 06:06

vhu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!