php pdo update语句

ct3nt3jp  于 2021-06-24  发布在  Mysql
关注(0)|答案(1)|浏览(544)

我尝试使用pdo创建一个查询,其中查询包含一个子查询。代码不起作用。使用workbench,我可以执行查询,它确实可以执行。
我觉得在使用pdo时,在派生表时有细微差别。

$turn = 1;
    $phase = -1;
    $status = "waiting";
    $gameid = 1;

        $stmt = $this->connection->prepare("
            UPDATE playerstatus 
            SET 
                turn = :turn,
                phase = :phase,
                status = :status,
                value = value + (SELECT reinforce FROM games where id = :gameid)
            WHERE
                gameid = :gameid                
        ");

        $stmt->bindParam(":turn", $turn);
        $stmt->bindParam(":phase", $phase);
        $stmt->bindParam(":status", $status);
        $stmt->bindParam(":gameid", $gameid);

        $stmt->execute();

我尝试了大量的调整,但在执行时失败了。
编辑错误:
致命错误:未捕获的pdoexception:sqlstate[hy093]:无效的参数号

ntjbwcob

ntjbwcob1#

pdo命名的platchholders有一个已知的(但没有很好的文档记录)限制:同一个bind占位符不能在一个语句中使用多次。解决方法是使用不同的绑定占位符名称。
(pdo中的这一限制可能已在更高版本(?)中解决。我认为根本原因是“幕后”,pdo正在用位置符号问号替换命名占位符。这个问题不仅仅局限于update语句,同样的问题困扰着所有使用命名占位符的pdosql语句。)
另外,与问题无关,我建议使用 bindValue 代替 bindParam .
将绑定占位符名称更改为独特/唯一。此处显示,更改 :gameid:gameid2 ```
value = value + (SELECT reinforce FROM games where id = :gameid)
WHERE
gameid = :gameid2
^

我们需要为每个绑定占位符提供一个值。这意味着我们需要再加一行。与 `bindValue` ,我们可以引用相同的变量,而不需要复制它。

$stmt->bindValue(":gameid", $gameid);
$stmt->bindValue(":gameid2", $gameid);
^

相关问题