問題描述
我正在使用 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 手冊中的此注釋.
這篇關于在 PDO 準備好的語句中可以參數化哪些令牌?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!