所以我想得到一个帖子的id,其中title =“$ someTitle”
$dbh= new PDO("mysql:host=localhost;dbname=NAME",'USER','PASS',
array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"
));
$someTitle = '\"If you\'re absent during my struggle, don\'t expect to be present during my success.\" - Will Smith';
$statement = $dbh->prepare("select id from posts where title = :title");
$statement->execute(array(':title' => $someTitle));
$row = $statement->fetch();
echo $row[id];
这个例子有效,但如果我将$ someTitle更改为$ someTitle ='new test';
每件事都没问题
任何提示?
答案 0 :(得分:3)
不要自己逃跑。这就是为什么有准备好的语句,它会为你解决SQL注入问题。你在文本中有了自己的转义,你告诉数据库要在DB中搜索包含那些转义的文本 - 这很可能不存在。
相反,有:
$someTitle = '"If you\'re absent during my struggle, don\'t expect to be present during my success." - Will Smith';
^---no escape, and ditto for at the end of the line.
请注意,我只撤消了"
个字符。由于您对字符串本身使用单引号,因此必须对任何'
DO进行转义,以使其成为有效的PHP字符串赋值。但是,数据库不会看到\'
,只会看到原始'
。