开发者

Table name as parameter using PDO/MySQL prepared statement [duplicate]

This question already has answers here: Can PHP PDO Statements accept the table or column name as parameter? (8 answers) Closed last year.

Is this possible? e.g.

SELECT * FROM :data开发者_如何学Cbase WHERE id = :id

If not, should I just do this:

SELECT * FROM ' . $database . ' WHERE id = :id

Or is there some other trick I need to learn?


Table and Column names cannot be replaced by parameters in PDO. see Can PHP PDO Statements accept the table or column name as parameter?


It is quite dangerous to pass dynamically built table names in a query. But if it is so much needed by your application, you have to sanitize the data. Since PDO cannot help with this, you have to call mysql_real_escape_string on the table name yourself. Also you will have to enclose the table name with backticks as `table_name`. So prepare the query as:

'SELECT * FROM `' . mysql_real_escape_string($database) . '` WHERE id = :id

One note: mysql_real_escape_string needs an already established connection to the DB.

EDIT: But when I think about it, probably is best to match the $database variable against your existing tables.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜