2

I'm building a C application, and for the first time using the MySQL API. I did a little research before I began building my application and stumbled upon this SO question, which talks about not putting user data directly into queries and instead using prepared statements to overcome the possibility of SQL injection - which is just fine and dandy.

I've come round to actually coding my application and I feel like I want to slit my wrists. I haven't used prepared statements before (it's so different to what I'm used to doing normally in my other favourite language, PHP - I'm so used to just writing SQL and escaping data). It so happens that I've also stumbled across the function mysql_real_escape_string. My question is - is it just as safe to escape data in an SQL query (an example below) as it is in a prepared statement?

mysql_real_escape_string(dbc, sBuf, sUserInputData, strlen(sUserInputData));
sprintf(sQuery, "SELECT * FROM `sessions` WHERE `SessionID`='%s';", sBuf);
Community
  • 1
  • 1
Jonathon
  • 778
  • 8
  • 21
  • You should probably use `snprintf` rather than `sprintf`. As is, you have a buffer overflow vulnerability. – icktoofay Oct 29 '11 at 22:30
  • 3
    I think you should instead use prepared statements also in PHP - besides being at least as secure as escaping (if the escape function isn't bugged), it should also be slightly faster (you avoid the escaping and de-escaping costs, just transmitting the raw data separately from the query). – Matteo Italia Oct 29 '11 at 22:32
  • Absolutely prepared statements. Printf can be evil. If you are using c++ use of string stream can be useful too. Better some more security than just 10 nanoseconds less of computation :) – Salvatore Previti Oct 30 '11 at 00:26

0 Answers0