使用预准备语句在数据库中插入datetime NOW()

时间:2015-10-05 09:39:21

标签: php mysql

我尝试在用户进行注册时插入日期但不起作用。当我向查询添加begin if :old.comments is not null then APEX_ERROR.ADD_ERROR ( p_message => 'Warning: ' || :new.comments || ' will replace ' || :old.comments', p_additional_info => SQLERRM, p_display_location => apex_error.c_inline_in_notification); end if; end; 时,它没有插入任何内容。如果我将其删除,则会将用户添加到数据库中。

这是正常查询

NOW()

我已经阅读了其他帖子并尝试了这个

$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
));

刚刚在查询中添加了$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 )); created,但没有插入任何内容。

可能是什么问题?

3 个答案:

答案 0 :(得分:1)

首先尝试捕捉您的错误:

try {
    $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
    ));
}
catch(Exception $e) {
    echo 'Exception -> ';
    var_dump($e->getMessage());
}

然后,您可以这样使用:

$stmt->execute(array(
    ':username' => $_POST['username'],
    ':password' => $hashedpassword,
    ':created' => date('Y-m-d H:i:s'),
    ':email'   => $_POST['email'],
    ':active'  => $activasion
));

答案 1 :(得分:1)

尝试

$created = date("Y:m:d h:i:s");
$stmt = $pdo->prepare('INSERT INTO users (username,password,email,created,active) VALUES (:username, :password, :email, :created, :active');
$stmt->execute(array(
    ':username' => $_POST['username'],
    ':password' => $hashedpassword,
    ':email' => $_POST['email'],
    ':active' => $activasion,
    ':created' => $created
));

答案 2 :(得分:1)

您缺少关于正在向prepare()提供的SQL的右括号:

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

应该是

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

正如@VincentDecaux建议的那样,你的错误检查应该抓住这个。如果您愿意,请使用以下内容启用例外:

$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);