链接下拉列表与HTML + PHP + MySQL

时间:2017-01-26 10:20:27

标签: php html mysql

我想知道如何将三个下拉列表链接在一起。我想让用户选择国家,然后选择州,然后选择城市。实际上我尝试了多种方法,但我所做的就是如下:

<div class="row">
  <div class="col-sm-4"><div class="form-group">
  <label for="countries">Country</label>
  <select class="form-control" id="countries">
<?php
$servername = "localhost";
$username = "root";
$password = "123";
$dbname = "countries";


$conn = new mysqli($servername, $username, $password, $dbname);    
$sql = "SELECT * FROM countries";
$result = $conn->query($sql);

//echo "<select id='countries'>";
while ($row = $result->fetch_assoc()) {
    echo "<option value='" . $row['name'] . "'>" . $row['name'] . "</option>";
}
//echo "</select>";

$conn->close();?>
  </select>
</div></div>
  <div class="col-sm-4"><div class="form-group">
  <label for="countries">State</label>
  <select class="form-control" id="states">
<?php
$servername = "localhost";
$username = "root";
$password = "123";
$dbname = "countries";


// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
if($_POST['submit'] && $_POST['submit'] != 0)
{
   $countries=$_POST['countries'];
}
//echo "Connected successfully";
$sql = "SELECT * FROM regions where  country_id = $countries";
$result = $conn->query($sql);

//echo "<select id='states'>";
while ($row = $result->fetch_assoc()) {
    echo "<option value='" . $row['name'] . "'>" . $row['name'] . "</option>";
}
//echo "</select>";

$conn->close();?>
  </select>
</div></div>
</div>

我需要做的是制作三个下拉列表(其中2个显示在上面)让用户先选择国家/地区,然后第二个下拉列表根据用户选择显示州/地区,最后根据选择选择城市state.Please向我展示这样做的解决方案。

3 个答案:

答案 0 :(得分:2)

我去年的某个时候编写了代码,你需要的是使用ajax,有change event

  

请不要我用PDO编写我的解决方案我知道你的解决方案需要mysqli,但是我没有太多时间重写整个   对mysqli的事情

但是我希望你能看到如何做到这一点的逻辑,并希望你能够自己将它转换成mysqli,而不是喧嚣。

我的索引文件

<script src="jquery.min.js"></script>
<?php require 'db_config.php';?>

 <script type="text/javascript">
  $('#country').on('change', function() {
            var countryID = $(this).val();
            if (countryID) {
                $.ajax({
                    type: 'POST',
                    url: 'locations.php',
                    data: 'country_id=' + countryID,
                    success: function(html) {
                        $('#state').html(html);
                        $('#city').html('<option value="">Select state first</option>');
                    }
                });
            } else {
                $('#state').html('<option value="">Select country first</option>');
                $('#city').html('<option value="">Select state first</option>');
            }

            $(this).remove('has-errors');
        });

        $('#state').on('change', function() {
            var stateID = $(this).val();
            if (stateID) {
                $.ajax({
                    type: 'POST',
                    url: 'locations.php',
                    data: 'state=' + stateID,
                    success: function(html) {
                        $('#city').html(html);
                    }
                });
            } else {
                $('#city').html('<option value="">Select city first</option>');
            }
        });
</script>
<form method="POST" action="" id="reg_form">
 <select name="country" id="country" class="input">
        <option value="0">Select country</option>
        <?php

            $stmt= $dbh->Prepare("SELECT countryID, countryName FROM countries ORDER BY countryName ASC");

            $stmt->execute();

            $results= $stmt->Fetchall(PDO::FETCH_ASSOC);

            if(count($results) > 0){
               foreach($results as $row){
                    echo '<option value="'.$row['countryID'].'">'.$row['countryName'].'</option>';
                }
            }else{
                echo '<option value="">country not available</option>';
            }
            ?>
    </select>
    <select name="state" id="state" class="input">
        <option value="">Select country first</option>
    </select>
    <select name="city" id="city" class="input">
        <option value="">Select state first</option>
    </select>
</form>

<强> locations.php

<?php
/**
 * Created by PhpStorm.
 * User: Masivuye
 * Date: 2016/12/19
 * Time: 11:27 AM
 */
require 'db_config.php';


if(isset($_POST["country_id"]) && !empty($_POST["country_id"])){


  $sql=$dbh->prepare("SELECT DISTINCT states.stateID,states.stateName from states INNER JOIN countries ON states.countryID  = ? ");
  $sql->bindValue(1,$_POST['country_id']);
  $sql->execute();

  $results =$sql->fetchall(PDO::FETCH_ASSOC);

  if(count($results) > 0){

        echo '<option value="0">Select state</option>';
        foreach($results as $row){ 
            echo '<option value="'.$row['stateID'].'">'.$row['stateName'].'</option>';
    }

  }else{
        echo '<option value="">state not available</option>';
    }


}

if(isset($_POST["state"]) && !empty($_POST["state"])){


   $sql=$dbh->prepare("SELECT DISTINCT cities.cityID,cities.cityName,cities.stateID from cities INNER JOIN states ON cities.stateID= ? ");
 $sql->bindValue(1,$_POST['state']);
 $sql->execute();

 $results =$sql->fetchall(PDO::FETCH_ASSOC);

 if(count($results) > 0){

        echo '<option value="0">Select City</option>';
        foreach($results as $row){ 
            echo '<option value="'.$row['cityID'].'">'.$row['cityName'].'</option>';
    }

 }else{
        echo '<option value="">city not available</option>';
    }
}
?>

<强> db_config.php

<?php


    $servername  = "localhost";
    $username    = "hidden";
    $password    = "hidden";
    $dbname      = "mytestDB";


    try {

        $dbh= new PDO("mysql:host=$servername;dbname=$dbname",$username,$password);
        $dbh->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);


    } catch (PDOException $e) {

        echo "Could not connect".$e->getMessage();
        error_log($e);

    }

?>

我的表格

CREATE TABLE IF NOT EXISTS `states` (
  `stateID` int(6) NOT NULL AUTO_INCREMENT,
  `stateName` varchar(255) NOT NULL,
  `countryID` int(6) NOT NULL,
  PRIMARY KEY (`stateID`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1;

--
-- Dumping data for table `states`
--

INSERT INTO `states` (`stateID`, `stateName`, `countryID`) VALUES
(3, 'Western Cape', 2),
(4, 'Eastern Cape', 1),
(5, 'North West', 2),
(6, 'Northen Cape', 2);


--
-- Table structure for table `cities`
--

CREATE TABLE IF NOT EXISTS `cities` (
  `cityID` int(6) NOT NULL AUTO_INCREMENT,
  `cityName` varchar(255) NOT NULL,
  `stateID` int(6) NOT NULL,
  PRIMARY KEY (`cityID`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1;

--
-- Dumping data for table `cities`
--

INSERT INTO `cities` (`cityID`, `cityName`, `stateID`) VALUES
(1, 'Cape Town', 3),
(2, 'East London', 4);



-- --------------------------------------------------------

--
-- Table structure for table `countries`
--

CREATE TABLE IF NOT EXISTS `countries` (
  `countryID` int(6) NOT NULL AUTO_INCREMENT,
  `countryName` varchar(255) NOT NULL,
  PRIMARY KEY (`countryID`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 ;

--
-- Dumping data for table `countries`
--

INSERT INTO `countries` (`countryID`, `countryName`) VALUES
(1, 'South Africa'),
(2, 'Zambia'),
(3, 'Zimbabwe '),
(4, 'Uganda'),
(5, 'USA'),
(6, 'Brazil'),
(7, 'India'),
(8, 'Austrilia'),
(9, 'Ghana');

-- --------------------------------------------------------
  

注意:在表格上使用你自己的字符集,你可以使用utf-8

希望这会指向正确的方向,希望其他SO用户也会帮助我错过的地方。

答案 1 :(得分:0)

您可以通过多种方式实现您想要的功能,但您必须对代码进行许多改进。

例如。您可以在脚本之上进行连接,而不是多次(无论何时需要)。您也可以在脚本之上从数据库表中获取数据。

<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "test";

$conn = new mysqli($servername, $username, $password, $dbname);    

$sql = "SELECT * FROM countries";
$result = $conn->query($sql);
$countries = $result->fetch_all(MYSQLI_ASSOC);

$sql = "SELECT * FROM regions";
$result = $conn->query($sql);

$regions = $result->fetch_all(MYSQLI_ASSOC);
?>

然后在下面添加您的HTML代码。

<div class="row">
  <div class="col-sm-4">
      <div class="form-group">
          <label for="countries">Country</label>
          <select class="form-control" id="countries" onchange="refreshPage(this)">
                <option value=""> Select Country</option>
            <?php foreach($countries as $country): ?>
                <option value="<?= $country['id'] ?>" ><?= $country['name'] ?></option>
            <?php endforeach; ?>
          </select>
        </div>

        <div class="form-group">
          <label for="regions">Region</label>
          <select class="form-control" id="regions">
            <option value=""> Select Region</option>
            <?php foreach($regions as $region): ?>
                <option value="<?= $region['id'] ?>"><?= $region['name'] ?></option>
            <?php endforeach; ?>
          </select>
        </div>
    </div>
</div>

您希望相关的国家和地区,您可以使用javascript甚至jQuery(如果需要)分别获取区域。或者只是在选择国家/地区时刷新页面,例如。 (请注意上面国家选择框中的 refreshPage()方法。)

<script>
    function refreshPage(object)
    {
        var country_id = object.options[object.selectedIndex].value;

        if (country_id != '') {
            window.location.href = '?country_id='+country_id;           
        }
    }
</script>

现在您只需从$ _GET中获取 country_id 值即可过滤区域。完整的代码看起来像这样。

<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "test";

$conn = new mysqli($servername, $username, $password, $dbname);    

$sql = "SELECT * FROM countries";
$result = $conn->query($sql);
$countries = $result->fetch_all(MYSQLI_ASSOC);

$where = "";

if (isset($_GET['country_id']) && $_GET['country_id'] != '') {
    $where = " WHERE country_id = '{$_GET['country_id']}'";
}

$sql = "SELECT * FROM regions {$where}";
$result = $conn->query($sql);

$regions = $result->fetch_all(MYSQLI_ASSOC);
?>

<div class="row">
  <div class="col-sm-4">
      <div class="form-group">
          <label for="countries">Country</label>
          <select class="form-control" id="countries" onchange="refreshPage(this)">
                <option value=""> Select Country</option>
            <?php foreach($countries as $country): ?>
                <option value="<?= $country['id'] ?>" <?php echo isset($_GET['country_id']) && $_GET['country_id'] == $country['id'] ? 'selected' : ''; ?> ><?= $country['name'] ?></option>
            <?php endforeach; ?>
          </select>
        </div>

        <div class="form-group">
          <label for="regions">Region</label>
          <select class="form-control" id="regions">
            <option value=""> Select Region</option>
            <?php foreach($regions as $region): ?>
                <option value="<?= $region['id'] ?>"><?= $region['name'] ?></option>
            <?php endforeach; ?>
          </select>
        </div>
    </div>
</div>

<script>
    function refreshPage(object)
    {
        var country_id = object.options[object.selectedIndex].value;

        if (country_id != '') {
            window.location.href = '?country_id='+country_id;           
        }
    }
</script>

此代码的主要问题是,它不会阻止任何SQL注入,并且在很多方面都容易受到攻击。您必须使用PDO而不是mysqli并使用预准备语句来过滤区域。

答案 2 :(得分:-1)

在这种情况下,您应该使用AJAX。 Onchange(select)你可以将xmlhttprequest(JS)发送到一个单独的php文件,它返回你需要的数据(例如作为JSON),然后用JS将它插入你的网站。

示例:

  <script type="text/javascript">
  function filtern()
  {
    region = document.getElementById("feld1").value;

    xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function()
    {
      if(xhr.readyState==4 && xhr.status==200)
      {
        filtered_region = JSON.parse(xhr.responseText);
        document.getElementById("select1").innerHTML = "";
        for(i=0;i<filtered_region.length;i++)
        {
          document.getElementById("select1").innerHTML += "<option>"+filtered_region[i]+"</option>";
        }
      }
    }
    xhr.open("GET","get_your_data.php?region="+region,true);
    xhr.send();
  }
  </script>

  <form>
    <p>Feld1: <input type="text" name="feld1" id="feld1" onchange="filtern()" /></p>
    <select name="select1" id="select1"></select>
  </form>

get_your_data.php返回您要显示的数据。