简体   繁体   English

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

[英]How to bind select2 and mysql databse with php

I am trying to bind my select2 input to get results from mysql database, using mysqli connection.I tried several solutions here but have yet to make it work, instead it keeps saying no results found.我正在尝试使用 mysqli 连接绑定我的 select2 输入以从 mysql 数据库获取结果。我在这里尝试了几种解决方案,但尚未使其工作,而是一直说没有找到结果。

The latest I have tried was the javascript code from https://select2.github.io/examples.html .我尝试过的最新版本是https://select2.github.io/examples.html 中的 javascript 代码。 I am not sure if it is my javascript that is failing me or my php file.我不确定是我的 javascript 还是我的 php 文件失败了。

These are my codes, hope someone can point to me where needs to be change.这些是我的代码,希望有人能指出我需要更改的地方。

HTML HTML

<div class="form-group">
   <div class="col-xs-12 col-sm-12 col-md-6 col-lg-6">
      <label class="control-label col-lg-3" for="Customer" id="Customer"><span style="color:red;">*</span>Customer:</label>
      <div class="col-lg-9">
         <input id="cCustomer" name="cCustomer" class="cCustomer form-control" type="hidden" value="" style="width: 100%" />   
      </div><!-- END col-lg-9  -->
   </div><!-- END col-xs-12 col-sm-12 col-md-6 col-lg-6  -->
</div><!-- END .form-group  -->

I did include我确实包括

<link rel="stylesheet" href="//localhost/1System/select2/css/select2.min.css">
<link rel="stylesheet" href="//localhost/1System/select2/css/select2-bootstrap.min.css">
<script type="text/javascript" src="//localhost/1System/select2/js/select2.full.min.js"></script>

in my <head></head>在我的<head></head>

JS JS

$(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
    });
});

Lastly, my PHP最后,我的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);
?>

I am using mysqli to connect to my database.我正在使用 mysqli 连接到我的数据库。 My connection is working for the other php pages.我的连接适用于其他 php 页面。

$conn = mysqli_connect($host, $username, $password);

To be honest I don really know how should the PHP file look like?老实说,我真的不知道 PHP 文件应该是什么样子的? anyone can point me towards a good example or a right direction.任何人都可以为我指出一个很好的例子或正确的方向。

PROBLEM:问题:

When I click on the input on my chrome, it indicated as no results found.![enter image description here][1] [1]: http://i.stack.imgur.com/PDAa5.png当我点击我的 chrome 上的输入时,它表示没有找到结果。![在此处输入图像描述][1] [1]:http://i.stack.imgur.com/PDAa5.png



Thanks in advance.提前致谢。 If my question is duplicated or bad please kindly feedback.如果我的问题重复或不好,请反馈。

Your JS select2 code worked perfectly for me.您的 JS select2 代码非常适合我。

Below is the Doctrine function I used to create the JSON response.下面是我用来创建 JSON 响应的 Doctrine 函数。

You should be able to adapt this to your mysql/php code.您应该能够将其调整为您的 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));

The latest version 4.0 of select2 works on select tags and no longer on input tags (in either type text or type hidden). select2 的最新版本 4.0 适用于选择标签,不再适用于输入标签(文本类型或隐藏类型)。 It seems your using this version so you should enhance your code accordingly.似乎您正在使用此版本,因此您应该相应地增强您的代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM