Skip to content
Advertisement

Escape a pdo query, is that necessary?

My question of to day is. Do i need to escape PDO in my script?

$columns = implode(", ",$column);
$query = ''.$query.' '.$columns.' FROM '.$table.'';
$dbh_query = $dbh->prepare($query);
$dbh_query->execute();
$dbh_querys = $dbh_query->fetchAll();

return $dbh_querys;

The whole script can be found at. https://github.com/joshuahiwat/crud/blob/master/control/query_connector.class.php

Can someone explain why do i need a escape at this time or why not.

I like to hear from you, thanks a lot!

Advertisement

Answer

The parts of your query that are dynamic are the table name and column names. You can’t use bind functions for these parts of the query. Bind functions can be used only for the parts of the query that would otherwise be a simple value in an SQL query. Like a numeric constant, or a quoted string or quoted date literal.

To avoid SQL injection from dynamic table names or column names, you have the following choices:

  • Use values that are predefined in your class, or otherwise certain to be safe. Don’t use external content from users or any other source.
  • Use escaping. Note that the function PDO::quote() doesn’t do the kind of escaping you need for table names or column names.
  • Create a “allowlist” of known table names and the column names for the respective table, and compare the dynamic input to the allowlist. If it doesn’t match the allowlist, raise an error.
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement