7

我在使用 PDO Prepared 语句时遇到问题,如果您需要多次使用相同的绑定变量,查询将无法验证。

例子:

$params = array (
    ':status' => $status,
    ':userid' => $_SESSION['userid']
);

$stmt = $pdo->prepare ('
    INSERT INTO 
        tableName
        ( userId, status )
        VALUES
        ( :userid, ":status" )
        ON DUPLICATE KEY UPDATE
            status = ":status"
');

if ( ! $stmt->execute ( $params ))
{
    print_r( $stmt->errorInfo ());
}

编辑:的值$params是:
Array ( [:status] => PAID [:userid] => 111 )

编辑 2
我注意到插入的是0而不是原始值,而不是用户 ID,并且插入的是空字符串而不是状态。

4

4 回答 4

8

Problem was the quotes around the :status. Removed quotes and all is good.

于 2012-08-20T11:34:39.667 回答
3

您的数组键不需要包含冒号。冒号纯粹是为了让 PDO 知道后面是命名参数。

$params = array (
    ':status' => $status,
    ':userid' => $_SESSION['userid']
);

应该

$params = array (
    'status' => $status,
    'userid' => $_SESSION['userid']
);
于 2012-08-20T10:36:36.013 回答
2

Works fine for me. E.g.

<?php
$pdo = new PDO('mysql:host=localhost;dbname=test;charset=utf8', 'localonly', 'localonly');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
setup($pdo);

echo 'client version: ', $pdo->getAttribute(PDO::ATTR_CLIENT_VERSION), "\n";
echo 'server version: ', $pdo->getAttribute(PDO::ATTR_SERVER_VERSION), "\n";
echo "before:\n";
foreach( $pdo->query('SELECT * FROM tmpTableName', PDO::FETCH_ASSOC) as $row ) {
    echo join(', ', $row), "\n";
}

$status = 1;
$_SESSION['userid'] = 'foo';

$params = array (
    'status' => $status,
    'userid' => $_SESSION['userid'],
);

$stmt = $pdo->prepare ('
    INSERT INTO 
        tmpTableName
        (userId, status)
    VALUES
        (:userid, :status)
    ON DUPLICATE KEY UPDATE
        status = :status
');

if ( ! $stmt->execute ( $params ))
{
    print_r( $stmt->errorInfo ());
}

echo "after:\n";
foreach( $pdo->query('SELECT * FROM tmpTableName', PDO::FETCH_ASSOC) as $row ) {
    echo join(', ', $row), "\n";
}

function setup($pdo) {
    $pdo->exec('
        CREATE TEMPORARY TABLE tmpTableName (
            userId varchar(32),
            status int,
            unique key(userId)
        )
    ');
    $pdo->exec("INSERT INTO tmpTableName (userId,status) VALUES ('foo', 0)");
    $pdo->exec("INSERT INTO tmpTableName (userId,status) VALUES ('bar', 0)");
}

prints

client version: mysqlnd 5.0.10 - 20111026 - $Id: b0b3b15c693b7f6aeb3aa66b646fee339f175e39 $
server version: 5.5.25a
before:
foo, 0
bar, 0
after:
foo, 1
bar, 0

on my machine

于 2012-08-20T11:36:30.153 回答
1

您没有在bindParam任何地方调用该方法,为什么?就在您调用之前execute,请尝试添加

$stmt->bindParam(':userid', $_SESSION['userid'], PDO::PARAM_INT);
$stmt->bindParam(':status', $status, PDO::PARAM_STR);

然后打电话$stmt->execute();看看它对你有用。还要将您的错误消息设置为完整,并在实例化您的 PDO 实例后,添加它$db->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);以确保始终抛出错误。

文档很方便

于 2012-08-20T10:38:16.343 回答