0

I just found out because someone had a ' in their last name and it caused the script to not update anything after that. What's the best way to make their last name safe of any potental damaging characters?

Strawberry
  • 66,024
  • 56
  • 149
  • 197
  • 3
    See http://stackoverflow.com/questions/60174/best-way-to-stop-sql-injection-in-php. While you can sanitize your SQL, as SoosGjr mentions below, parameterization is considered better practice, for reasons discussed in that link. – Michael Petrotta Apr 05 '10 at 00:50
  • You should answer the question instead of adding comment, I can give you a vote up and possibly select as best answer :) – Strawberry Apr 05 '10 at 01:10
  • I don't like writing duplicate answers; I can't really add anything to the linked answer. – Michael Petrotta Apr 05 '10 at 02:01

2 Answers2

2

You should probably be using prepared statements if you're embedding the SQL to insert records into the DB in your logic. Among other things they will properly escape data values for you (as long as you use them consistently.)

Tagore Smith
  • 1,554
  • 10
  • 9
  • What kind of prepared statements are you talking about? – Strawberry Apr 05 '10 at 01:08
  • Prepared statements are what M. Petrotta is referring to in his comment above. Here's a link to the documentation for them if you use the PDO abstraction layer for PHP: http://php.net/manual/en/pdo.prepared-statements.php In addition to escaping your data values prepared statements can be more efficient if you find yourself executing the same query repeatedly. If you're going to embed SQL directly in your code it's usually a good idea to use them. – Tagore Smith Apr 05 '10 at 01:18
  • @Doug The ones that don't allow SQL injection (or "break" when ' is inserted) –  Apr 05 '10 at 02:48
0

You should use

print htmlentities("O'Brian",ENT_QUOTES);

before inserting into database, it will convert string to

O'Brian

so it is safe to store to database. Keep in mind that this function also escapes double quotes.

More info on escaping string.