致命错误:带有消息'SQLSTATE [42000]的未捕获异常'PDOException':语法错误或访问冲突:1064

问题描述:

我正在创建一个商店并使用输入来获取结果,现在我有了调用PHP脚本的AJAX和它调用它很好,但我得到一个错误:致命错误:带有消息'SQLSTATE [42000]的未捕获异常'PDOException':语法错误或访问冲突:1064

Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[42000]: Syntax error or access violation: 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

'LIKE%''%'的结果不正确。将'%'添加到变量而不是查询中。 – AbraCadaver

+0

您不能将通配符放在绑定的外部。在你输入之前把它放在你的输入中。 – aynber

+0

我仍然得到一个错误 –

添加通配符参数:

$query = $con->prepare("SELECT ... WHERE product_name LIKE :input LIMIT 9 "); 
$query->execute(array(':input' => '%' . $input. '%')); 

这样的通配符包含在价值,从根本上让这样的查询:

SELECT .... WHERE product_name LIKE '%name%' 
+0

ohh there,好吧我试着 –

+0

它的工作原理!谢谢! –

+0

太棒了 - 如果您认为这是最佳解决方案,请[接受答案](http://*.com/help/accepted-answer)。有关更多信息,请参阅[我应该怎么做当有人回答我的问题?](http://*.com/help/someone-answers) –

你的查询结果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));