php和mysql中的自动完成表单字段

时间:2014-09-15 04:03:50

标签: javascript php jquery mysql

他每一个我试图从我的sql做自动完成表格这里是index.php的代码

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"

型= “文本/ JavaScript的” &GT;

<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.1/jquery-ui.min.js" type="text/javascript"></script>
<script type="text/javascript">
    $(document).ready(function(){
    var ac_config = {
    source: "database_cities.php",
    select: function(event, ui){
        $("#area").val(ui.item.area);
        $("#city").val(ui.item.city);
        $("#state").val(ui.item.state);
        $("#zip").val(ui.item.zip);
        },
        minLength:1
        };
        $("#area").autocomplete(ac_config);
});

</script>
<form name="form" method="POST">
<p>
<label for="area">area</label>
<br />
<input type="text" name="area" id="area" value=""  />
</p>

<p>
<label for="city">City</label>
<br />
<input type="text" name="city" id="city" value=""/>
</p>
<p>
<label for="state">State</label>
<br />
<input type="text" name="state" id="state" value="" />
</p>
<p>
<label for="zip">Zip</label><br />
<input type="hidden" name="zip" id="zip" value="" />
</p>
<p>
<input type="submit" value="store" />
</p>
</form>

这是database_cities.php

<?php 
// Data could be pulled from a DB or other source
$conn = mysql_connect("localhost", "root", "") or die("Could Not Connect"); 
mysql_select_db("dependency");  

$city_area=$_GET['area'];

$query = "SELECT * FROM cities WHERE city LIKE '$city_area%'";
$data = mysql_query($query);

while ($row = mysql_fetch_array($data,MYSQL_ASSOC)){



$address = array(   
    array('city'=>$row['city'], state=>$row['state'], zip=>$row['postcode']), );
}

// Cleaning up the term
$term = trim(strip_tags($_GET['term']));  
// Rudimentary search
$matches = array(); foreach($address as $city){ if(stripos($city['city'], $term) !== false){
    // Add the necessary "value" and "label" fields and append to result set
    $city['value'] = $city['city']; 
    $city['label'] = "{$city['city']}, {$city['state']} {$city['zip']}";
    $matches[] = $city; } } 
    // Truncate, encode and return the results
    $matches = array_slice($matches, 0, 5);
    print json_encode($matches);

&GT?; 我尝试连接mysql数据库它连接和工作,但问题是我只是得到我的数据库的最后一行我没有得到任何其他字段可以任何一个请告诉我当我输入时我必须得到我的所有数据在第一场 感谢

1 个答案:

答案 0 :(得分:0)

您在每次迭代时都会覆盖$address变量,而不是按预期附加。

$address = array();

while ($row = mysql_fetch_array($data, MYSQL_ASSOC)) {
  $address[] = array(
    'city' => $row['city'],
    'state' => $row['state'],
    'zip' => $row['postcode']
  );
}

[]运算符允许PHP将新值推送到数组的末尾,同时自动递增数字键。

另请注意,我引用了statezip个键。您很可能会收到PHP Notices。