简体   繁体   English

根据第一个下拉框从数据库检索第二个下拉框的选项

[英]Retrieve options for the second drop down box from DB based on first Drop down box

I am currently working on a small project. 我目前正在做一个小项目。 I have to retrieve some data from a DB (MySQL) and insert it into a webpage as a select (Drop Down box). 我必须从数据库(MySQL)中检索一些数据,然后将其插入到网页中作为选择(“下拉”框)。 The code I have written in PHP is: 我用PHP编写的代码是:

<?php
// Connect to the db.
require ('mysqli_connect.php');

// Make the query:
$q = "SELECT employee_name from employee where dept_id=3 ORDER BY employee_id ASC"; 

// Run the query.
$r = mysqli_query ($dbc, $q);

if ($r) // If it ran OK, display the records. 
{ 
     echo '<select name="employee_name">';

     // Fetch and print all the records:
     while ($row = mysqli_fetch_array($r)) 
     {
          echo '<option value="'.$row['employee_name'] . '>"'.$row['employee_name'] .'</option>';

     }
         echo "</select>";    

}

mysqli_free_result ($r); // Free up the resources.
mysqli_close($dbc); // Close the database connection.
?>

When I execute the query in MySQL console, it returns the correct output. 当我在MySQL控制台中执行查询时,它返回正确的输出。 [It is a list of five names]. [这是五个名字的清单]。

Can you help me find the error? 您能帮我找到错误吗?

Use this: 用这个:

if ($r = @mysqli_query ($dbc, $q))
{
    echo 'select ....

As $r is different to true on SELECT queries. 因为$rSELECT查询中的true不同。

EDIT 编辑

You are closing the select tag on every iteration of the while . 您将在while每次迭代中关闭select标记。 Try it like this: 像这样尝试:

if ($r = @mysqli_query ($dbc, $q))
{ 
     echo '<select name="employee_name">';
     // Fetch and print all the records:
     while ($row = mysqli_fetch_array($r)) 
     {
          echo '<option value="'.$row['employee_name'] . '>"'.$row['employee_name'] .'</option>';
     }
     echo "</select>";                         
//   ^
//   |__  Now the </select> is out of the loop
}

Echo your end select out of the loop. 回声结束选择。

 while ($row = mysqli_fetch_array($r)) 
 {
      echo '<option value="'.$row['employee_name'] . '>"'.$row['employee_name'] .'</option>';

 }
 echo "</select>";

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM