2013-11-28 111 views
0

我在我的数据库中有两个innoDB表,名为客户船只。我也有2个选择框一个具有列形式:COMPANY_NAME表客户作为选项,而另一种列:船只名称表的船只根据第一个选项填充第二个选择框的选项。这两个都是PHP阵列

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

最后请注意,我是一个JavaScript和jQuery的完全新手,这就是为什么我在这里问我如何实现上述结果。

形式:

<?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(); 

} 

?> 

UPDATE:下面是我想实现上述结果的一个PHP页面

<!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 

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> 

FINAL-UP DATE

test.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> 

test.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> 

回答

1

这不是我第一次看到这样问,但我会潜水

警告:这个答案有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> 

好了,现在一些点ERS

  • 你应该小心与PHP脚本我离开那里,有做什么我预期的其他方式,其更干净,更容易维护
  • 的JavaScript是不是最好的,也有更好的解决方案了有所以一定要检查这些出以及
  • 如果你不明白的任何脚本的部分不要犹豫,问
  • 谨防任何空白,不允许在PHP脚本之前任何输出,这非常重要。所有输出应该留给模板

我希望这一直是有帮助

+0

我的PHP脚本的修改版本打算直接与上述表单在同一页让我们说steve.php?原因如果它不起作用:( –

+0

我的测试表明它还没有完成。我仍然需要编辑php文件,对不起,它需要一分钟左右的时间... – hanzo2001

+0

它现在应该工作...改变'url ='http:...''到你的目标'steve.php(?)',并且不要忘记在进入查询之前转换'company_name',这是一个安全的预防措施。一个特殊的'ajax.php'脚本,可以处理请求 – hanzo2001

0

这个使用Ajax,通过你的公司ID来javascript

<script> 
function showCustomer(str) 
{ 
if (window.XMLHttpRequest) 
    {// code for IE7+, Firefox, Chrome, Opera, Safari 
    xmlhttp=new XMLHttpRequest(); 
    } 
else 
    {// code for IE6, IE5 
    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); 
    } 
xmlhttp.onreadystatechange=function() 
    { 
    if (xmlhttp.readyState==4 && xmlhttp.status==200) 
    { 
    document.getElementById("myresult").innerHTML=xmlhttp.responseText; 
    } 
    } 
xmlhttp.open("GET","test.php?q="+str,true); // Pass value to another page Here->test 
xmlhttp.send(); 
} 
</script> 

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

<div id="myresult"> 


</div> 

,立即test.php的简单期权价值&放的选择框,

<?php 
$q = $_GET['q']; 

// Here fetch values for particular q(company name) 

// put select box 
+0

忘了提职方法,我用我的表单POST已编辑。 –

+0

请随意提及上面所需的任何更改,如果这可以通过任何更简单的JavaScript方式不使用ajax来完成。 –

相关问题