簡體   English   中英

使用 HTML+PHP+MySQL 鏈接下拉列表

[英]Link Dropdown List with HTML+PHP+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>

我需要做的是制作三個下拉列表(上面顯示了其中的兩個)讓用戶首先選擇國家,然后第二個下拉列表根據用戶選擇顯示州/地區,最后根據所選州選擇城市。請向我展示執行此操作的解決方案。

我去年某個時候為此編寫了代碼,您需要的是使用 ajax,有 on 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>

位置.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 用戶能幫助我錯過一些東西。

你可以通過多種方式實現你想要的,但你必須對你的代碼進行很多改進。

例如。 你可以只在你的腳本之上建立連接而不是多次(無論你需要什么)。 您也可以像這樣從腳本頂部的數據庫表中獲取數據。

<?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 並使用准備好的語句來過濾區域。

在這種情況下,您應該使用 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 返回要顯示的數據。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM