使用PDO出现了一个问题,当字符的最后一个为\的时候插入数据库失败,很是费解,参数绑定怎么会出现如此的问题?
error_reporting(E_ALL);
header("content-type:text/html;charset=utf8");
$params = array();
$params[PDO::MYSQL_ATTR_INIT_COMMAND] = 'SET NAMES UTF8';
$dsn = "mysql:host=localhost;dbname=test;port=3306;";
$dbh = new PDO($dsn, 'root', '123456', $params);
$sql = 'INSERT INTO `fav_ls_1` (`uid`,`fid`,`type`,`title_md5`,`title`,`url`,`order`,`addtime`) VALUES (:uid,:fid,:type,:title_md5,:title,:url,:order,:addtime)';
$bind = array(
':uid' => 5919639,
':fid' => 0,
':type' => 1,
':title_md5' => "0886c9605d1424e656c85736b4730e7f",
':title' => '\\敌\\',
':url' => "http://www.2345.com/?ie",
':order' => 0,
':addtime' => 1449156098,
);
$sth = $dbh->prepare($sql);
if(false===$sth->execute($bind))
{
print_r( $sth->errorInfo () );
}
else
{
echo $dbh->lastInsertId();
}
错误代码如下:
Array ( [0] => 42000 [1] => 1064 [2] => You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'http://www.2345.com/?ie','0','1449156098')' at line 1 )
补充一下:
这个设置了$dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);就可以运行了,但是在其他sql上也会出现莫名其妙的错误。
感谢king同学的答案:
我的问题是PHP环境是大于5.3.6的,需要在dsn中设置charset=utf8,低于PHP5.3.6版本的使用SET NAMES UTF8
修改代码如下解决: