8

I am very used to using MySQL and mysql_real_escape_string(), but I have been given a new PHP project that uses ODBC.

What is the correct way to escape user input in a SQL string?

Is addslashes() sufficient?

I would like to get this right now rather than later!

psx
  • 4,040
  • 6
  • 30
  • 59

1 Answers1

7

Instead of string escaping the PHP ODBC driver uses prepared statements. Use odbc_prepare to prepare an SQL statement and odbc_execute to pass in the parameters and execute the statements. (This is similar to what you can do with PDO).

halfdan
  • 33,545
  • 8
  • 78
  • 87
  • Looks exactly like what I want. However, I'm completely new to prepared statements too. By using prepared statements, can I pass in special characters without worrying about escaping? e.g. to pass **O'Brien** in as a parameter, I just pass it in using odbc_exec into a prepared statement? – psx Apr 19 '11 at 09:08
  • 3
    Yes, that's what prepared statements are for. They prevent SQL Injections as the DBMS handles the parameters for you. – halfdan Apr 19 '11 at 14:23
  • Prepared statements are the most sensible approach. In practice, though, not all ODBC drivers support them. – Álvaro González Nov 13 '13 at 15:13
  • @ÁlvaroG.Vicario What would be the alternative to drivers which do not support those? – Ray Feb 28 '14 at 09:13
  • @PacMani - I've [had that problem myself](http://stackoverflow.com/questions/3996275/escape-input-data-in-sql-queries-when-using-odbc-access) and didn't find a satisfactory answer. As far as I know your only chance is reading technical docs to find out the DBMS mechanism and writing your own escape function. – Álvaro González Feb 28 '14 at 10:06
  • @ÁlvaroG.Vicario Okay, I just helped myself by simply replacing ' with '' in my case... not very secure, but the code is only used internally anyways... – Ray Feb 28 '14 at 18:00
  • Prepared statements are great until you run into a bug such as: a parameter marker in a LIKE clause will cause a "String data, right truncation" if the bound value is too long (which is bogus; LIKE isn't supposed to generate that kind of error) (with PHP ODBC and SQL Server native driver on Windows, that is) – Brian A. Henning Oct 10 '16 at 14:53