簡體   English   中英

致命錯誤:消息為“ SQLSTATE [42000]”的未捕獲異常“ PDOException”:語法錯誤或訪問沖突:1064

[英]Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[42000]: Syntax error or access violation: 1064

我正在開一家商店,並使用輸入來獲取結果,現在我有了調用PHP腳本的AJAX,它也很好用,但是出現錯誤:

致命錯誤:消息為“ SQLSTATE [42000]”的未捕獲異常“ PDOException”:語法錯誤或訪問沖突: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();

將通配符添加到參數:

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

這樣,通配符就包含在值中,從本質上講,查詢是這樣的:

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

您的查詢導致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));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM