0

I want to do an INSERT into a MySQL database using:

$sql = "INSERT INTO table (title1) VALUES ('$myVar')";

but the problem is $myVar can contain the single quotes (' symbols, e.g. in "idiot's"). Can somebody tell me how to handle any single quotes in the variable as a letter and not as a piece of code?

(I know there are posts about this in the forum already, but I do not really understand their solutions, so sorry for double posting)

jotik
  • 17,044
  • 13
  • 58
  • 123
Sariel
  • 3
  • 1
  • 2
  • 4
    Either "escape" the value of `$myVar`; or (better yet) switch to using prepared statements with bind variables, when the binding will escape it for you – Mark Baker May 01 '16 at 13:35

2 Answers2

1

You might be temped to replace each single quote with two of them.

like so

    $myvar =  "idiot\'s";

But resist the urge and escape it instead:

<?php $var = "Hello !! idiot's";

 mysql_real_escape_string($var);?>

Or even better, use PDO

Johan
  • 74,508
  • 24
  • 191
  • 319
Naresh Kumar
  • 561
  • 2
  • 15
  • good idea but i cant escape them by hand. and the `mysql_real_escape_string($var);` does not work for me :( – Sariel May 01 '16 at 14:03
  • 1
    it depends what you are using if you use PDO Statement, then no need to work it will do automatically. If you are using mysql or mysqli then you will have to use escape functions – Naresh Kumar May 01 '16 at 14:10
  • 1
    @NareshKumar - PDO won't do it for you automatically.... if you use bind variables, it will be done automatically for you, and you can use bind variables with either PDO or MySQLi – Mark Baker May 01 '16 at 14:31
  • 1
    @MarkBaker thank you for the correction, i forgot to mention that if we use bind variables it will do :) :) =) – Naresh Kumar May 01 '16 at 14:35
0

Use mysqli_real_escape_string like this:

$myVar= mysqli_real_escape_string($link,$myVar);

and then your query.

It is advisable to use PDO too!

Thamilhan
  • 13,040
  • 5
  • 37
  • 59