在 PDO 准备好的语句中可以参数化哪些令牌?

2021-12-26 00:00:00 php pdo prepared-statement

我正在使用 PHP/PDO 中的准备好的语句.基本查询工作正常,将值传递给 WHERE 子句:

I'm playing around with prepared statements in PHP/PDO. The basic queries work fine, passing a value to the WHERE clause:

$stmt = $db->prepare( 'SELECT title FROM episode WHERE id=:id' );
$stmt->bindParam( ':id', $id, PDO::PARAM_INT );
$id = 5;
$stmt->execute();

但是我有一种情况,我需要为字段名称传递变量.此查询(具有适当的绑定)工作正常:

However I have a situation where I need to pass variables for the field names. This query (with appropriate binding) works fine:

SELECT :field FROM episode WHERE id=:id

这个给出了一个错误:

SELECT title FROM :field WHERE id=:id

这个没有给出错误,但不返回任何行:

This one doesn't give an error, but returns no rows:

SELECT title FROM episode WHERE :field=:id

那么,什么东西应该在准备好的语句中起作用?我可以参数化"字段名、表名等吗?

So, what things should work in prepared statements? Can I 'parameterize' field names, table names and so on?

推荐答案

您不能参数化表名、列名或 IN 子句中的任何内容(感谢 c0r0ner for 指出IN 子句限制).

You cannot parameterize table names, column names, or anything in an IN clause (thanks to c0r0ner for pointing out the IN clause restriction).

参见这个问题,以及随后PHP 手册中的此注释.

相关文章