0

My string $name = "Ali'Shan"; I want store it into database but the ' I use htmlentities/ htmlspecialchars and str_replace but insert I still get syntax error ' .

$name = "Ali'Shan";
str_replace("'", "", $name);
echo $name;

echo htmlentities($name);

My output is still Ali'Shan

user236501
  • 8,538
  • 24
  • 85
  • 119
  • 1
    ' is not an entity for HTML purposes. It's a legitimate character. For putting into the database you use mysql_real_escape_string() or the appropriate equivalent for your DB. – virmaior Dec 28 '13 at 11:27
  • addslashes() or mysql_real_escape_string() – Sibiraj PR Dec 28 '13 at 11:28
  • Thanks mysql_real_escape_string() solved the problem. – user236501 Dec 28 '13 at 11:32
  • Don't use `mysql_real_escape_string`, it forces you to use the `mysql_` library, which is deprecated and will be removed from PHP. There are better alternatives. – Quentin Dec 28 '13 at 11:33
  • You can use [mysqli::real_escape_string](http://www.php.net/manual/en/mysqli.real-escape-string.php) it's an alternative like Quentin meant. – demonking Dec 28 '13 at 12:07

4 Answers4

1

Use addslashes() or mysql_real_escape_string()

Sibiraj PR
  • 1,481
  • 1
  • 10
  • 25
  • 2
    Don't use `addslahes`, it is simply unsuitable. Don't use `mysql_real_escape_string`, it forces you to use the `mysql_` library, which is deprecated and will be removed from PHP. There are better alternatives. – Quentin Dec 28 '13 at 11:35
1

Use htmlentities and htmlspecialchars when you want to insert text into an HTML document.

A database is not an HTML document. You need to use the appropriate mechanisms for adding text to an SQL query.

For the most part, those mechanisms are prepared statements with bound variables.

Community
  • 1
  • 1
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
0

what about

str_replace("'", "\'", $name);
Null
  • 154
  • 1
  • 14
0

Use mysql_real_escape_string($str) while inserting in database.

Amit
  • 3,251
  • 3
  • 20
  • 31
  • 1
    Don't use `mysql_real_escape_string`, it forces you to use the `mysql_` library, which is deprecated and will be removed from PHP. There are better alternatives. – Quentin Dec 28 '13 at 11:34