[英]Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[42000]: Syntax error or access violation: 1064
I am making a shop and using an input to get results, now I have the AJAX that calls the PHP script and it calls it fine, but I get an error: 我正在开一家商店,并使用输入来获取结果,现在我有了调用PHP脚本的AJAX,它也很好用,但是出现错误:
Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[42000]: Syntax error or access violation: 1064
致命错误:消息为“ SQLSTATE [42000]”的未捕获异常“ PDOException”:语法错误或访问冲突:1064
NOTE : The error line is the $query->execute(array(':input'=>$input))
line 注意 :错误行是
$query->execute(array(':input'=>$input))
行
here's the AJAX script ( + HTML calling the function ) 这是AJAX脚本(+调用该函数的HTML)
<input type="text" name="search_item" onkeyup="showItems(this.value)" id="search_item">
<script>
function showItems(str) {
if (str.length == 0) {
} else {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("items").innerHTML = this.responseText;
}
};
xmlhttp.open("GET", "searchScript.php?iName=" + str, true);
xmlhttp.send();
}
}
</script>
and here's the called PHP: 这就是所谓的PHP:
$input = $_REQUEST["iName"];
$input = "%".$input."%";
$dsn = 'mysql:host=xxx.com;dbname=dbNameHidden;charset=utf8mb4';
$username = 'hidden';
$password = 'hidden';
try{
// connect to mysql
$con = new PDO($dsn,$username,$password);
$con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (Exception $ex) {
echo 'Not Connected '.$ex->getMessage();
}
$query = $con->prepare("SELECT * FROM store AS s INNER JOIN product_pictures AS pp ON s.product_id = pp.id INNER JOIN product_name AS pn ON s.product_id = pn.id WHERE product_name LIKE %:input% LIMIT 9 ");
$query->execute(array(':input' => $input));
$items = $query->fetchAll();
Add the wildcards to the parameter: 将通配符添加到参数:
$query = $con->prepare("SELECT ... WHERE product_name LIKE :input LIMIT 9 ");
$query->execute(array(':input' => '%' . $input. '%'));
That way the wildcards are contained in the value, essentially making the query like this: 这样,通配符就包含在值中,从本质上讲,查询是这样的:
SELECT .... WHERE product_name LIKE '%name%'
Your query results in LIKE %'something'%
which is not correct. 您的查询导致
LIKE %'something'%
错误。 Add %
to the variable not the query. 将
%
添加到变量而不是查询中。 You want something like: 您想要类似的东西:
$input = "%$input%";
$query = $con->prepare("SELECT * FROM store AS s
INNER JOIN product_pictures AS pp ON s.product_id = pp.id
INNER JOIN product_name AS pn ON s.product_id = pn.id
WHERE product_name LIKE :input LIMIT 9 ");
$query->execute(array(':input' => $input));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.