Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parameterized SQL Columns?

I have some code which utilizes parameterized queries to prevent against injection, but I also need to be able to dynamically construct the query regardless of the structure of the table. What is the proper way to do this?

Here's an example, say I have a table with columns Name, Address, Telephone. I have a web page where I run Show Columns and populate a select drop-down with them as options.

Next, I have a textbox called Search. This textbox is used as the parameter.

Currently my code looks something like this:

result = pquery('SELECT * FROM contacts WHERE `' + escape(column) + '`=?', search);

I get an icky feeling from it though. The reason I'm using parameterized queries is to avoid using escape. Also, escape is likely not designed for escaping column names.

How can I make sure this works the way I intend?

Edit: The reason I require dynamic queries is that the schema is user-configurable, and I will not be around to fix anything hard-coded.

like image 448
Martin Avatar asked Sep 19 '08 21:09

Martin


People also ask

What is a parameterized SQL query?

A parameterized query is a query in which placeholders are used for parameters and the parameter values are supplied at execution time. The most important reason to use parameterized queries is to avoid SQL injection attacks.

Is parameterized query safe?

Parameterized queries are generally the safest and most efficient way to pass user defined values in a query, however not every database driver supports them.

Are parameterized queries safe from SQL injection?

Use prepared statements and parameterized queries. These are SQL statements that are sent to and parsed by the database server separately from any parameters. This way it is impossible for an attacker to inject malicious SQL.


1 Answers

Instead of passing the column names, just pass an identifier that you code will translate to a column name using a hardcoded table. This means you don't need to worry about malicious data being passed, since all the data is either translated legally, or is known to be invalid. Psudoish code:

@columns = qw/Name Address Telephone/;
if ($columns[$param]) {
  $query = "select * from contacts where $columns[$param] = ?";
} else {
  die "Invalid column!";
}

run_sql($query, $search);
like image 132
zigdon Avatar answered Oct 10 '22 09:10

zigdon