在 PHP 程序 使用 PDO 模式 INSERT INTO 数据时,有时候需要会出现”Fatal error: Uncaught PDOException: SQLSTATE[42000]: Syntax error or access violation: 1064 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” 这样的错误,多半是因为待插入的数据中含有未转义的符号
案例:
$domain = "domain is 'vetrue.com'";//变量中含有‘引号 号这样的 的特殊符号 $db->query("INSERT INTO `table` (`id`, `domain`) VALUES (null, '$domain'"); //这样的话就会导致最终执行的 SQL 语句为 INSERT INTO `table` (`id`, `domain`) VALUES (null, 'text is 'vetrue.com'') //PHP 自定义变量中含有单引号未转义自然会在执行 SQL 语句的时候发生错误
解决办法
使用 PHP 自带函数 htmlspecialchars()
$domain = "domain is 'vetrue.com'"; addslashes($domain);//单引号会被转义 $db->query("INSERT INTO `table` (`id`, `domain`) VALUES (null, '$domain'");
再需要输出的时候可以使用 stripslashes()函数把转义的字符串恢复
PHP 还有个两个类似的函数
strip_tags() :去除 HTML 标签
htmlspecialchars() 把 HTML 标签转换为 HTML 实例
htmlspecialchars 和 strip_tags 二者之间的区别是一个是删除掉 HTML 标签,一个是将 html 标签转换为其他字符。