2017-03-03 116 views
0

我正在創建一個商店並使用輸入來獲取結果,現在我有了調用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

我仍然得到一個錯誤 –

回答

1

添加通配符參數:

$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://stackoverflow.com/help/accepted-answer)。有關更多信息,請參閱[我應該怎麼做當有人回答我的問題?](http://stackoverflow.com/help/someone-answers) –

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)); 
相關問題