如何使用选择输入表单中的PDO和PHP从MySql表中获取数据

时间:2013-09-29 17:23:53

标签: php jquery pdo

我正在尝试创建一个表单,当用户首次选择一个国家/地区时,应该会显示所选县的所有城市的列表。请参阅以下代码:

<select name="country" id="countryS">
<option value="">Select Country</option>
<option value="1">USA</option>
<option value="2">RUSSIA</option>
<option value="3">United Kingdom</option>
</select>


<select name="city" id="citiesS">
<option value="">Select City</option>
</select>

然后使用JQuery我使用以下代码:

    $('#countryS').on('change', function (e) {
    var optionSelected = $("option:selected", this);
    var valueSelected = this.value;

    $.post('Showcountries.php', { valueSelected: valueSelected}, function(results){

      });    

我的问题是如何使用上面的jQuery代码,以便能够在以下html代码中显示相应的城市?

<select name="city" id="citiesS">
<option value="">Select City</option>
</select>

showCountries.php中,我存储了以下代码:

<?php
require_once('../class.myclass.php');

if(isset($_POST['valueSelected'])){
  $selectedVal = $_POST['valueSelected'];
  if(!empty($selectedVal)){
                        $locations = new location();
                        $cities = $locations->TheCities($selectedVal);
                        return $cities;
                        }
}

?>

最后在class.myclass.php我有下面的代码返回所有适当的城市。

<?php
class location
{
private $host = "xxxxxxxx";   
private $user = "xxxxxxxx";   
private $password = "xxxxxxxx";   
private $name = "xxxxxx"; 

public function TheCities($country)  
{
    $db = new PDO('mysql:host=' . $this->host . ';dbname=' . $this->name, $this->user, $this->password);
    $sql = "SELECT * FROM CITIES WHERE COUNTRY = :country";
    $sth = $db->prepare($sql, array(PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY));
    $sth->execute(array(':country' => $country));

    $results = $sth->fetchAll();

    return $results;

}


}
?>

1 个答案:

答案 0 :(得分:-1)

首先,您需要更改服务器端代码以返回json。循环遍历您获得的城市,并将它们添加到数组中,索引为城市的id,值为城市名称。然后,回显json_encode($ cityArray)而不是返回$ cities。

然后,在jQuery中,您需要构建如下所示的元素:

 $.post('Showcountries.php', { valueSelected: valueSelected}, function(results){
       var resultsObj = jQuery.parseJSON(results);
       var optionsHTML = '';
       $(resultsObj).each(function() {
           optionsHTML += '<option value="'+ this.cityId +'">'+ this.cityName +'</option>';
       });
       $('#citiesS').html(optionsHTML);
  });