2

I am trying to create some SQL insert statements and a few variables have names like the following:

  • "Aamma's Pastries"

I want to escape the quote (') as I am adding the value into the MySQL database. How do I do that with PHP?

random
  • 9,774
  • 10
  • 66
  • 83
Harsha M V
  • 54,075
  • 125
  • 354
  • 529

4 Answers4

4

You've already accepted an answer, but I'd like to suggest a better approach to you. Using an approach like mysql_real_escape_string requires you to consistently remember to apply it every single time in every single query; it's tedious and error prone.

A more simple approach, which also ensures consistency is to use parameterised statements. This ensures that everything is correctly escaped, and also avoids you having to embed variables in your queries.

In PHP, this can be used with the newer PDO or MySQLi libraries. Of these, I prefer PDO for the flexibility it provides (e.g. I'm currently stuck with MySQL, but I don't intend to keep my app running that way forever, and with PDO the migration will be massively simplified), but there are plenty of questions here on SO that cover the pros and cons of each.

El Yobo
  • 14,823
  • 5
  • 60
  • 78
2

Have a look at mysql_real_escape_string

Adriaan Stander
  • 162,879
  • 31
  • 289
  • 284
  • 1
    Please don't encourage people to try to escape strings themselves, point them to the correct way to do it, paramaterized queries w/PDO or MySQLi. – El Yobo Nov 30 '10 at 05:38
1

Please use prepare statements and let mysql handle escaping itself and you doing at code level

shashuec
  • 684
  • 8
  • 20
-2

There is this function that you can use that escapes all characters that you need, here is a code example in php

<?php
$str = "Is your name O'reilly?";

// Outputs: Is your name O\'reilly?
echo addslashes($str);
?>
mariana soffer
  • 1,853
  • 12
  • 17