1

是否可以为表名做一个绑定值?如果我删除 :table 并添加表名,我的似乎基本上没有捡起它,第二个 2 绑定工作正常,但我想将它用于同一表单中的多个表。

表单上的表字段是根据上一个查询的结果定义的,因此表名称以 $table 的值出现在表单上,​​该值正确显示,因此这应该将 $table 的值发布到表绑定???

try {
    $sql = 'UPDATE :table SET
                archive = :archive
                WHERE id = :id';
    $s = $pdo->prepare($sql);
    $s->bindvalue('table', $_POST['table']);
    $s->bindvalue('archive', $_POST['archive']);
    $s->bindvalue('id', $_POST['id']);
    $s->execute();
}
4

1 回答 1

0

Since prepared statements are a "bit" more than sprintf, it doesn't make sense to set the table by variable.

A prepared statement is passed to the DB before the actual values are set. So the DB may look for a way how to answer the query. After this preparation the actual values searched for are set. The query is answered, when execute() is called.

So, to prepare "a way how to answer the query" (as I called it), the table name is a significant information. That is why it does not make sense to pass it as a variable. That is also why it doesn't work.

So, you have to string concatenate the table name:

$sql = 'UPDATE '. $table .' SET
            archive = :archive
            WHERE id = :id';

As @zerkms suggest, you should whitelist the possible table names.

于 2013-08-11T06:54:09.930 回答