php - 使第二个选择框的选项根据第一个选择框进行填充。两者都是 PHP 数组

标签 php mysql

我的数据库中有两个 innoDB 表,分别名为 customersvessels。我还有一个带有 2 个选择框的表单,其中一个具有表:客户 的列:company_name 作为选项,另一个具有列:vessel_name> 表:船只

我想要做的是根据第一个选择框中选择的客户公司名称填充第二个选择框的选项。

最后请考虑到我是 Javascript 和 jQuery 的新手,这就是为什么我在这里问如何才能实现上述结果。

形式:

<!DOCTYPE html>
<html>
<head>
    <title></title>
</head>
<body>

        <form name="ypo" method="post">

        <select name="company_name">
        <?php
        foreach($pelates as $pelend) {
            ?>
            <option value="<?php echo $pelend->company_name; ?>"><?php echo $pelend->company_name; ?></option>
        <?php
        }
            ?>
        </select>


        <select name="vessel">
        <?php
        foreach($ploia as $end) {
            ?>
            <option value="<?php echo $end->vessel_name; ?>"><?php echo $end->vessel_name; ?></option>
        <?php
        }
            ?>
        </select>

    </form>

    </body>
    </html>

使上述表单工作的 php :

    <?php

// For customers
$sqlpelates = "SELECT * FROM customers ORDER BY company_name";

if($pelat = $db->query($sqlpelates)) {

$pelates = array();

    while($pelate = $pelat->fetch_object()) {
        $pelates[] = $pelate;
    }

$pelat->free();

}

// For vessels
$sqlploia = "SELECT * FROM vessels ORDER BY vessel_name";

if($plo = $db->query($sqlploia)) {

$ploia = array();

    while($ploi = $plo->fetch_object()) {
        $ploia[] = $ploi;
    }

$plo->free();

}

?>

更新:下面是我试图实现上述结果的单个 .php 页面:

<?php

require 'db/connect.php';
//check if this is an ajax call
$ajax = isset($_POST['ajax']) ? $_POST['ajax'] : false;
if (!$ajax) {
  // if not then this is a fresh page that needs everything
  $sqlpelates = "SELECT * FROM customers ORDER BY company_name";
  if ($pelat=$db->query($sqlpelates)) {
    $pelates = array();
    while($pelate=$pelat->fetch_object()) $pelates[] = $pelate;
    $pelat->free();
  }
}
// modify the query to filter out only what your ajax request wants
$where = $ajax ? ' WHERE company_name="'.$_POST['companyName'].'"' : '';
// you need to make sure to escape the incoming variable $_POST['company_name']
$sqlploia = 'SELECT * FROM vessels'.$where.' ORDER BY vessel_name';
if ($plo=$db->query($sqlploia)) {
  $ploia = array();
  while($ploi=$plo->fetch_object()) $ploia[] = $ploi;
  $plo->free();
}
// the secret sauce... and some very bad programming, this should be done some other way
if ($ajax) {
  // set the type, so the client knows what the server returns
  header('Content-Type: application/json');
  // output what the client asked for: an array of vessels in JSON format
  echo json_encode($ploia);
  // kill the script, this is all the client wants to know
  exit;
}



?>  

<!DOCTYPE html>
<html>
<head>
    <title></title>
</head>
<body>
<script src="jquery.js">

// Your code goes here.
// jQuery must be loaded already
$(function(){
  var
    // put the target php script
    url = 'http://prinseapals-marine.com/filing/drop_down.php',
    form=$('form[name="ypo"]'), company, vessels;
  company = {
    // I prefer using native DomElements sometimes
    selectBox : $(form).find('select[name="company_name"]')[0],
    onSelect : function () {
      var
        idx = company.selectBox.selectedIndex,
        data;
      // if user selected an empty option, clear and return
      if (idx === -1) {vessels.clearBox();return;}
      // setup the data 
      data = {"ajax":1,"company_name":company.selectBox[idx].value};
      // your script now has $_GET['ajax'], $_GET['company_name']
      $.post(url,data,vessels.fillBox,'json');
      // vessels.fillbox will be executed when your php script returns
    }
  };
  vessels = {
    // I prefer using native DomElements sometimes
    selectBox : $(form).find('select[name="vessel"]')[0],
    // a handy method for clearing options
    clearBox : function () {$(this.selectBox).empty()},
    // called upon completion of the ajax request
    fillBox : function (arrayOfVessels) {
      // clear current contents
      $(this.selectBox).empty();
      // for each element in the array append a new option to the vessel selector
      arrayOfVessels.forEach(function(v){
        $(vessels.selectBox).append('<option value="'+v+'">'+v+'</option>');
      });
    }
  };
  // add a listener to the company selector
  $(company.selectBox).change(company.onSelect);
});
</script>


        <form name="ypo" method="post">

        <select name="company_name">
        <?php
        foreach($pelates as $pelend) {
            ?>
            <option value="<?php echo $pelend->company_name; ?>"><?php echo $pelend->company_name; ?></option>
        <?php
        }
            ?>
        </select>


        <select name="vessel">
        <?php
        foreach($ploia as $end) {
            ?>
            <option value="<?php echo $end->vessel_name; ?>"><?php echo $end->vessel_name; ?></option>
        <?php
        }
            ?>
        </select>

    </form>

    </body>

最终更新:

测试.php:

<?php

require 'db/connect.php';
$cus = array();
if($cterm = $db->query("SELECT * FROM `customers`")) {
    while($cterm2 = $cterm->fetch_object()) {
        $cus[] = $cterm2;
    }
}

?>

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <script type="text/javascript" src="test.js"></script>
</head>
<body>

<form id="form1" name="myform"> 
    <select name="selection" onchange="load('bdiv', 'test2.php');">
    <?php
    foreach($cus as $c) {
    ?>
    <option value="<? echo $c->company_name ?>"><? echo $c->company_name ?></option>
    <?php
    }
    ?>
    </select>

    <div id="bdiv"></div>
</form>

</body>
</html>

测试.js:

function load (thediv, thefile) {
    // body...
    if(window.XMLHttpRequest) {
        xmlhttp = new XMLHttpRequest();
    } else {
        xmlhttp = new ActiveXObject('Microsoft.XMLHTTP');
    }

    xmlhttp.onreadystatechange = function() {
        if (xmlhttp.readyState==4 && xmlhttp.status==200) {
            document.getElementById(thediv).innerHTML = xmlhttp.responseText;
        }
    }

    xmlhttp.open('GET', thefile+'?selection='+document.myform.selection.value, true);
    xmlhttp.send();


}

test2.php:

<?php

require 'db/connect.php';

if (isset($_GET['selection'])) {
    # code...
    $selection = $_GET['selection'];
}

$ves = array();
    if ($vterm = $db->query(
        "SELECT `vessel_name` FROM `vessels` WHERE `company_name` = '$selection'")) {
        while ($vterm2 = $vterm->fetch_object()) {
            $ves[] = $vterm2;
        }

    } else {
    echo 'Please type a customer name.';
    }
?>

<select>
    <?php
    foreach($ves as $v) {
    ?>
    <option value="<?php echo $v->vessel_name ?>" ><?php echo $v->vessel_name ?></option>
    <?php
    }
    ?>
</select>

最佳答案

这不是我第一次看到这个问题,但我会深入研究

警告:这个答案有 javascript 和 jQuery。之后我还将附加一个 php 文件并进行一些更改,以允许为 ajax 请求调用相同的脚本

// jQuery must be loaded already
$(function(){
  var
    // put the target php script
    url = 'http://localhost/test/stackoverflow.php',
    form=$('form[name="ypo"]'), company, vessels;
  company = {
    // I prefer using native DomElements sometimes
    selectBox : $(form).find('select[name="company_name"]')[0],
    onSelect : function () {
      var
        idx = company.selectBox.selectedIndex,
        data;
      // if user selected an empty option, clear and return
      if (idx === -1) {vessels.clearBox();return;}
      // setup the data 
      data = {"ajax":1,"company_name":company.selectBox[idx].value};
      // your script now has $_GET['ajax'], $_GET['company_name']
      $.post(url,data,vessels.fillBox,'json');
      // vessels.fillbox will be executed when your php script returns
    }
  };
  vessels = {
    // I prefer using native DomElements sometimes
    selectBox : $(form).find('select[name="vessel"]')[0],
    // a handy method for clearing options
    clearBox : function () {$(this.selectBox).empty()},
    // called upon completion of the ajax request
    fillBox : function (arrayOfVessels) {
      // clear current contents
      $(this.selectBox).empty();
      // for each element in the array append a new option to the vessel selector
      arrayOfVessels.forEach(function(v){
        $(vessels.selectBox).append('<option value="'+v+'">'+v+'</option>');
      });
    }
  };
  // add a listener to the company selector
  $(company.selectBox).change(company.onSelect);
});

js代码背后的逻辑是允许用户交互。当用户做出选择时,将向服务器发出请求,并在客户端中处理响应并填充您的第二个 <select>

现在,您的 PHP 脚本的修改版本(警告:这适用于我接下来附加的模板)

<?php
// your model, check for whitespaces outside php tags, do not allow output yet
require 'db/connect.php';
// check if this is an ajax call
$ajax = isset($_POST['ajax']) ? $_POST['ajax'] : false;
if (!$ajax) {
  // required for the template
  $pelates = array();
  // if not then this is a fresh page that needs everything
  $sqlpelates = "SELECT * FROM customers ORDER BY company_name";
  if ($pelat=$db->query($sqlpelates)) {
    while($pelate=$pelat->fetch_object()) $pelates[] = $pelate;
    $pelat->free();
  }
} else {
  // modify the query to filter out only what your ajax request wants
  $where = ' WHERE company_name="'.$_POST['companyName'].'"';
  // required for the ajax request
  $ploia = array();
  // you need to make sure to escape the incoming variable $_POST['company_name']
  $sqlploia = 'SELECT * FROM vessels'.$where.' ORDER BY vessel_name';
  if ($plo=$db->query($sqlploia)) {
    while($ploi=$plo->fetch_object()) $ploia[] = $ploi;
    $plo->free();
  }
  // the secret sauce... and some very bad programming, this should be done some other way
  // set the type, so the client knows what the server returns
  header('Content-Type: application/json');
  // output what the client asked for: an array of vessels in JSON format
  echo json_encode($ploia);
  // kill the script, this is all the client want's to know
  exit;
}
?>

接下来是 html 模板的修改版本

<!DOCTYPE html>
<html>
  <head>
    <title>Your title</title>
  </head>
  <body>
    <form name="ypo" method="post">
      <select name="company_name"><?php
        foreach($pelates as $p) echo '<option value="'.$p->company_name.'">'.$p->company_name.'</option>';
      ?></select>
      <!-- leave empty, we will populate it when the user selects a company -->
      <select name="vessel"></select>
    </form>
    <!-- add jQuery lib here, either your own or from a CDN; this is google's version 2.0.3 -->
    <script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
    <!-- The code should be in a seperate file, load here if you want (but after jQuery lib) -->
    <script src="your/javascript/file.js"></script>
  </body>
</html>

好的,现在有一些提示

  • 你应该小心我留在那里的 php 脚本,还有其他方法可以实现我的意图,这些方法更干净且更易于维护
  • JavaScript 不是最好的,还有更好的解决方案,所以一定要检查一下
  • 如果您不理解任何脚本的部分内容,请随时询问
  • 注意任何空格,在php脚本之前不允许有任何输出,这一点非常重要。所有输出都应留给模板

希望这对您有所帮助

关于php - 使第二个选择框的选项根据第一个选择框进行填充。两者都是 PHP 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20266758/

相关文章:

php - 如何确保在检查时该值仅保存到表中一次?

php - laravel View 中的 e() 方法是做什么用的?

php - fancybox:打开外部子页面加载其后面的父页面

PHP/MySQL/??? - 组织文章和任意深度的子文章,其中可以检索任何文章,以及所有 parent 和 child

mysql count with right join返回一些错误的值

MySQL 排序 DESC 和 ASC

php - 从 PHP 中的数组中获取连续输赢

php登录系统插入麻烦

php - 如何使用数组更新列

MYSQL:将行连接为列