Table name as parameter using prepared PDO / MySQL statement

Is it possible? eg.

SELECT * FROM :database 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?

+2
source share
2 answers

Table and column names cannot be replaced with parameters in the PDO. see Can PHP PDO expressions accept a table or column name as a parameter?

+3
source

It is very dangerous to pass dynamically constructed table names in a query. But if it is so necessary for your application, you must misinform the data. Since PDO cannot handle this, you must call mysql_real_escape_string on the table name yourself. You will also have to wrap the table name with reverse records as `table_name`. Therefore, prepare the request as:

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

One note: mysql_real_escape_string requires an already established database connection.

EDIT: But when I think about it, it's probably best to map the $database variable to your existing tables.

+3
source

All Articles