問題描述
我正在使用 PDO 并且想做這樣的事情:
$query = $dbh->prepare("SELECT * FROM :table WHERE :column = :value");$query->bindParam(':table', $tableName);$query->bindParam(':column', $columnName);$query->bindParam(':value', $value);
PDO 會允許我像這樣綁定表名和列名嗎?似乎允許它,但即使我使用 PDO::PARAM_INT 或 PDO::PARAM_BOOL 作為數據類型,它也會在我的參數周圍加上引號.
如果這不起作用,我怎樣才能安全地轉義我的變量以便我可以在查詢中插入它們?
很遺憾,您無法通過列名綁定參數.
您可以嘗試動態創建 SQL 命令:
$sql = "SELECT * FROM $tableName WHERE $columnName = :value";$query = $dbh->prepare($sql);$query->bindParam(':value', $value);
只要確保對來自其他地方的參數/變量進行清理,以防止 SQL 注入.在這種情況下,$value
在一定程度上是安全的,但 $tableName
和 $columnName
不是 -- 再次,尤其是如果這些變量的值不是由 you
提供,而是由您的用戶/訪問者/等提供...
另外一件事;請避免使用 *
并命名您的列... 查看原因:
http://www.jasonvolpe.com/topics/sql/>
使用 SELECT * 時的性能問題?
在此處查看其他類似帖子:
為什么 ORDER BY 子句中的綁定參數不對結果進行排序?
如何設置 ORDER BY 參數使用準備好的 PDO 語句?
I am using PDO and want to do something like this:
$query = $dbh->prepare("SELECT * FROM :table WHERE :column = :value");
$query->bindParam(':table', $tableName);
$query->bindParam(':column', $columnName);
$query->bindParam(':value', $value);
Will PDO allow me to bind the table name and the column name like this? It seems to allow it, but it puts quotes around my parameters even if I use PDO::PARAM_INT or PDO::PARAM_BOOL as the data type.
If this won't work, how can I safely escape my variables so that I can interpolate them in the query?
Unfortunately, you can't bind parameters by column names.
What you could try is to dynamically create your SQL command:
$sql = "SELECT * FROM $tableName WHERE $columnName = :value";
$query = $dbh->prepare($sql);
$query->bindParam(':value', $value);
Just make sure to sanitize your parameters/variables if they are coming from elsewhere, to prevent SQL Injection. In this case, $value
is safe to a degree but $tableName
and $columnName
are not -- again, that is most especially if the values for these variables are not provided by you
and instead by your users/vistors/etc...
One other thing; please avoid using *
and name your columns instead... See some reasons why:
http://www.jasonvolpe.com/topics/sql/
Performance issue in using SELECT *?
See other similar posts here:
Why doesn't binding parameter in ORDER BY clause order the results?
How do I set ORDER BY params using prepared PDO statement?
這篇關于如何使用 PDO 動態構建查詢的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!