如何使用MYSQL数据库进行自动完成?

时间:2015-03-20 09:46:03

标签: php jquery

抱歉我的愚蠢问题,但我的jquery技能并不好。如何使用此FIDLE示例将MYSQL数据库用作源?谢谢!

PHP连接部分

$link = mysqli_connect("localhost", "***", "***", "mydb");

// Check connection
if($link === false){
die("error " .mysqli_connect_error());
}
 $va1= "770032PK";
//perform lookup
$query = "SELECT * FROM table1 WHERE mycol='$va1'";
$result=mysqli_query($link, $query) or die(mysqli_error());

 //print out results
 $row = mysqli_fetch_array($result);
   echo $row['golqmcm'].",".$row['malakcm'];

一些JS代码

$(function() {
  $( "#choice" ).autocomplete({
    source: [ { label: "Choice1", value: "value1" }, { label: "Choice2", value: "value2" }, { label: "Choice3", value: "value3" }],
    minLength: 2,
    select: function( event, ui ) {
        event.preventDefault();
        $('#choice').val(ui.item.label);
        this.value = ui.item.label;
        $('#prid').val(ui.item.value);
    }
  });
});

和HTML部分:

 <span class="input-group-addon">choices ...</span>
<input type="text" class="form-control" placeholder="choice" name="choice" id="choice">
 </div>
<div class="input-group">
<span class="input-group-addon">value of choices ...</span>
<input type="text" class="form-control" placeholder="" name="prid" id="prid">
 <input type="text" class="form-control" placeholder="" name="prid2" id="prid2">
</div>

1 个答案:

答案 0 :(得分:1)

这可以帮助你

在你的js代码之前你可以使用fallowing代码来添加选择和值

$rs = mysql_query("SELECT label, value from table ");
$result  = mysql_fetch_array($rs);

现在在你的js

$(function() {
  $( "#choice" ).autocomplete({
  source: [ <?php echo json_encode($result); ?>],
  minLength: 2,
  select: function( event, ui ) {
     event.preventDefault();
     $('#choice').val(ui.item.label);
     this.value = ui.item.label;
    $('#prid').val(ui.item.value);
  }
 });
});