我正在开店并使用输入来获得结果,现在我有调用PHP脚本的AJAX并且它调用它很好,但是我收到错误:
致命错误:未捕获的异常' PDOException' with message' SQLSTATE [42000]:语法错误或访问冲突:1064
注意:错误行是$query->execute(array(':input'=>$input))
行
这里是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>
这里叫做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();
答案 0 :(得分:1)
将通配符添加到参数:
$query = $con->prepare("SELECT ... WHERE product_name LIKE :input LIMIT 9 ");
$query->execute(array(':input' => '%' . $input. '%'));
通过这种方式,通配符包含在值中,实际上是这样的查询:
SELECT .... WHERE product_name LIKE '%name%'
答案 1 :(得分:0)
您的查询导致LIKE %'something'%
不正确。将%
添加到变量而不是查询。你想要这样的东西:
$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));