Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

Can escaping functions (e.g. mysql_real_esacpe_string ) be moved down to the database layer where we would loop through all parameters passed for all queries and escape all strings. Would that be a good design?

share|improve this question
up vote 4 down vote accepted

In most other languages you would use "prepared statements" for this where you separate the SQL from the values.

Doesn't PHP provide the same facility?

share|improve this answer
I think it does but never tried it? Is it really the professional way? – Imran Omar Bukhsh Apr 17 '11 at 8:21
Prepared statements are much more robust than generated SQL. – user1249 Apr 17 '11 at 8:47
Not using prepared statements with user supplied data is inviting an SQL injection attack. Not using them in this case would be less professional than using them. – BillThor Apr 17 '11 at 17:50
@BillThor, careful escaping of user supplied data should be enough but this is what the OP wants to avoid. Personally I just find the dynamically generated SQL brittle and hard to test. – user1249 Apr 17 '11 at 17:53
Use prepared statements to store data. period. It's the only way to make sure you avoid SQL injection attacks where people can modify the price of products, drop your users table, or even the whole database if they are crafty. I don't think there is a language that uses databases that doesn't support prepared statements. They work. – Berin Loritsch Apr 18 '11 at 12:27

PHP does provide a good emulation of prepared statements through the built-in PDO library. Use this for SQL if you can. The mysql_* functions are quick, dirty and legacy.

share|improve this answer

It would not be good design.

Use one of the common escaping libraries to escape the parameters.

Rolling out your own is error prone, especially in the database (where it might be subverted by a cleverly written parameter).

Additionally, SQL is fairly poor at string manipulation, so also a bad choice on this point.

share|improve this answer
what library would you suggest? – Imran Omar Bukhsh Apr 17 '11 at 8:21
@Imran Omar Bukhsh - – Oded Apr 17 '11 at 8:23

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.