Working with quotes added by PDO :: prepare ()

According to PHP Documentation PDO :: prepare () appends quotes to all of your parameters, so you don't need to worry about this:

"Parameters for prepared statements do not have to be specified, the driver automatically processes this. If the application uses exclusively prepared statements, the developer can be sure that SQL injection will not happen (however, if other parts of the query are built with unrelated input, SQL injection will still possible). "

The problem with this for me is how I build my queries and database structure. Typically, the FROM part of an SQL statement need not be parameterized because the table is likely to be determined by direct user input. However, with my code, which takes place in some places, and thus, I feel more comfortable with the parameterized version.

SELECT * FROM ? WHERE ?=? 

unlike SELECT * FROM tablename WHERE? =?

So my question is, is it possible to prevent my PDO from adding quotes around the FROM parameter so that I don't get SQL errors thrown into my face? Or should I do it differently.

+7
source share
2 answers

Placeholders in prepared statements apply only to values. The only way to insert dynamic table names is to do it yourself

 "SELECT FROM `".$table."` WHERE `".$column."` = ?" 
+4
source

@KingCrunch is basically true in his answer. You must really avoid the string yourself. Something like this should protect against most injections:

 //make sure $table and $column only contain alphanumeric chars $table = preg_replace("/[^A-Za-z0-9]/", '', $table); $column = preg_replace("/[^A-Za-z0-9]/", '', $column); $query = "SELECT FROM `{$table}` WHERE `{$column}` = ?" 
+2
source

All Articles