我正在运行sql查询,涉及搜索用户在数据库中发布的字符串,如果用户在字符串中有引号,则会收到错误。
function safe($string) {
$string = htmlentities(stripslashes(trim($string)));
$string = trim(trim($string,"'"),'"');
$string = strip_tags($string);
return $string;
}
$searchQ = safe($_REQUEST['q']);
$searchQ ="%$searchQ%";
//$pullsib = $pdo->prepare("SELECT * FROM `categories` WHERE `status`='1' AND (`name` LIKE '%".$searchQ."%' OR `description` LIKE '%".$searchQ."%') ORDER BY rand() ASC LIMIT 50");
$pullsib = $pdo->prepare("SELECT * FROM `categories` WHERE `status`=1 AND (`name` LIKE ? OR `description` LIKE ?) ORDER BY rand() ASC LIMIT 50");
// $RegTool->bindParam(2, $searchQ, PDO::PARAM_STR);
$pullsib->bindParam(1, $searchQ, PDO::PARAM_STR);
$pullsib->bindParam(2, $searchQ, PDO::PARAM_STR);
我得到的错误是因为$ searchQ包含引号,例如; “谁是猫”会引发错误:
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 MariaDB server version for the right syntax to use near 'fgdhj%%' OR `description` LIKE