根据第一个下拉框从数据库检索第二个下拉框的选项 [英] Retrieve options for the second drop down box from DB based on first Drop down box
本文介绍了根据第一个下拉框从数据库检索第二个下拉框的选项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我目前正在研究一个小项目。我必须从数据库(MySQL)中检索一些数据并将其作为选择(下拉框)插入到网页中。我用PHP编写的代码是:
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). The code I have written in PHP is:
<?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.
?>
当我在MySQL控制台中执行查询时,它会返回正确的输出。 [这是一个包含五个名字的列表]。
When I execute the query in MySQL console, it returns the correct output. [It is a list of five names].
你能帮我找到这个错误吗?
Can you help me find the error?
推荐答案
使用此方法:
Use this:
if ($r = @mysqli_query ($dbc, $q))
{
echo 'select ....
由于 $ r
不同于 true on
SELECT
查询。
As $r
is different to true
on SELECT
queries.
编辑
您正在关闭 select
标记在的每次迭代中,而
。试试这样:
You are closing the select
tag on every iteration of the while
. 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
}
这篇关于根据第一个下拉框从数据库检索第二个下拉框的选项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文