How to INSERT string with single quote ' symbol [duplicate]

五迷三道 提交于 2021-02-11 13:23:13

问题


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)


回答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




回答2:


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!



来源:https://stackoverflow.com/questions/36967233/how-to-insert-string-with-single-quote-symbol

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!