无法使用pdo预处理语句插入UTC_TIMESTAMP()

时间:2014-05-23 23:50:29

标签: pdo prepared-statement sql-insert

如何将UTC_TIMESTAMP()与此准备好的插入语句一起使用?它不喜欢格式/绑定和错误。

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

2 个答案:

答案 0 :(得分:2)

在语句本身中指定UTC_TIMESTAMP()而不是参数。

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

如果你这样做:

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

然后UTC_TIMESTAMP()变成一个字符串(因为它不是PHP函数),SQL语句最终变成了:

    INSERT INTO accounts (
        account_username,
        account_password,
        account_email,
        fname,
        lname,
        dtCreated
    ) VALUES (
        'jblow',
        'password',
        'jblow@gmail.com',
        'Joe',
        'Blow',
        'UTC_TIMESTAMP()'
    );

如果您注意到,UTC_TIMESTAMP()被指定为不起作用的字符串。

答案 1 :(得分:0)

你可以使用我想的 NOW() MySQL函数来做到这一点。