如何用php绑定select2和mysql数据库

如何用php绑定select2和mysql数据库,php,json,ajax,jquery-select2,Php,Json,Ajax,Jquery Select2,我正在尝试使用mysqli连接绑定我的select2输入以从mysql数据库获得结果。我在这里尝试了几种解决方案,但尚未成功,相反,它一直说没有找到结果 我最近尝试的是来自的javascript代码。我不确定是我的javascript还是我的php文件让我失望 这些是我的代码,希望有人能告诉我哪里需要更改 HTML 最后,我的PHP <?php include($_SERVER['DOCUMENT_ROOT']."/1System/php/connect.php"

我正在尝试使用mysqli连接绑定我的select2输入以从mysql数据库获得结果。我在这里尝试了几种解决方案,但尚未成功,相反,它一直说没有找到结果

我最近尝试的是来自的javascript代码。我不确定是我的javascript还是我的php文件让我失望

这些是我的代码,希望有人能告诉我哪里需要更改

HTML

最后,我的PHP

<?php
   include($_SERVER['DOCUMENT_ROOT']."/1System/php/connect.php");//calling connection file

   $conn=dbConnect();
   if (!$conn)
      die("Couldn't connect to MySQL"); /*when server is down, the statement will be showed*/
   $query = "SELECT c.customerID, c.name AS cname FROM customer c WHERE c.name LIKE '%".mysql_real_escape_string(strtoupper($_GET['q']))."%' or '%".mysql_real_escape_string($_GET['q']))."%'";
   $result = mysqli_query($conn, $query);
   $numCustomer = mysqli_num_rows($result);

   if($numCustomer != 0) {
      while(row = mysqli_fetch_array($result)) {
         $answer[] = array("id"=>$row['customerID'], "text"=>$row['cname']);
      }
   }else {
      $answer[] = array("id"=>"0", "text"=>"No Results Found...");    
   }
   echo json_encode($answer);
?>

你的JS select2代码对我来说非常适合

下面是我用来创建JSON响应的函数

您应该能够使其适应您的mysql/php代码

$q = strtolower($q);
$stmt = $this->getEntityManager()
        ->getConnection()
        ->prepare("SELECT s.id, s.suburb, s.state, s.postcode "
            . "FROM suburbs s "
            . "WHERE LOWER(s.suburb) LIKE '%" . $q . "%' "
            . "OR LOWER(s.state) LIKE '%" . $q . "%' "
            . "OR LOWER(s.postcode) LIKE '%" . $q . "%' "
            . "ORDER BY s.suburb, s.state"
        );
$stmt->execute();
$result = $stmt->fetchAll();

$suburbs = array();
if (is_array($result)) {
    foreach ($result as $row) {
        $id = $row['id'];
        $text = $row['suburb'] . ", " . $row['state'] . " " . $row['postcode'];
        $suburbs[] = array('id' => $id, 'text' => $text);
    }
}
return json_encode(array('items' => $suburbs));

select2的最新版本4.0适用于select标记,而不再适用于输入标记(输入文本或隐藏类型)。
您似乎正在使用此版本,因此您应该相应地增强代码。

1。检查firebug(或其他浏览器的类似扩展)所说的内容。2.在JS代码
url
中,参数应该是url,而不是相对路径。3.您的PHP代码应该返回
数组('items'=>$answer)
@dragoste如何检查PHP代码的返回结果?我读到人们能够看到他们的json结果,但我不太知道如何做到这一点。感谢Firebug->Console和Network选项卡,您可以查看所有ajax请求。
$(document).ready(function() {
    $("#cCustomer").select2({
        ajax: {
            url: "../../autoComplete/autoAddQuotation1.php",
            dataType: 'json',
            delay: 250,
            data: function (params) {
                return {
                    q: params.term, // search term
                    page: params.page
                };
            },
            processResults: function (data, page) {
                // parse the results into the format expected by Select2.
                // since we are using custom formatting functions we do not need to
                // alter the remote JSON data
                return {
                    results: data.items
                };
            },
            cache: true
        },
        escapeMarkup: function (markup) { return markup; }, // let our custom formatter work
        minimumInputLength: 1,
        //templateResult: formatRepo, // omitted for brevity, see the source of this page
        //templateSelection: formatRepoSelection // omitted for brevity, see the source of this page
    });
});
<?php
   include($_SERVER['DOCUMENT_ROOT']."/1System/php/connect.php");//calling connection file

   $conn=dbConnect();
   if (!$conn)
      die("Couldn't connect to MySQL"); /*when server is down, the statement will be showed*/
   $query = "SELECT c.customerID, c.name AS cname FROM customer c WHERE c.name LIKE '%".mysql_real_escape_string(strtoupper($_GET['q']))."%' or '%".mysql_real_escape_string($_GET['q']))."%'";
   $result = mysqli_query($conn, $query);
   $numCustomer = mysqli_num_rows($result);

   if($numCustomer != 0) {
      while(row = mysqli_fetch_array($result)) {
         $answer[] = array("id"=>$row['customerID'], "text"=>$row['cname']);
      }
   }else {
      $answer[] = array("id"=>"0", "text"=>"No Results Found...");    
   }
   echo json_encode($answer);
?>
$q = strtolower($q);
$stmt = $this->getEntityManager()
        ->getConnection()
        ->prepare("SELECT s.id, s.suburb, s.state, s.postcode "
            . "FROM suburbs s "
            . "WHERE LOWER(s.suburb) LIKE '%" . $q . "%' "
            . "OR LOWER(s.state) LIKE '%" . $q . "%' "
            . "OR LOWER(s.postcode) LIKE '%" . $q . "%' "
            . "ORDER BY s.suburb, s.state"
        );
$stmt->execute();
$result = $stmt->fetchAll();

$suburbs = array();
if (is_array($result)) {
    foreach ($result as $row) {
        $id = $row['id'];
        $text = $row['suburb'] . ", " . $row['state'] . " " . $row['postcode'];
        $suburbs[] = array('id' => $id, 'text' => $text);
    }
}
return json_encode(array('items' => $suburbs));