我目前正在开展一个小项目。我必须从数据库(MySQL)中检索一些数据并将其作为选择(下拉框)插入到网页中。我用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.
?>
当我在MySQL控制台中执行查询时,它会返回正确的输出。 [这是五个名字的清单]。
你能帮我找到错误吗?
答案 0 :(得分:0)
使用此:
if ($r = @mysqli_query ($dbc, $q))
{
echo 'select ....
由于$r
与true
查询SELECT
不同。
修改强>
您正在select
的每次迭代中关闭while
标记。试试这样:
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
}
答案 1 :(得分:0)
回声你的结束选择退出循环。
while ($row = mysqli_fetch_array($r))
{
echo '<option value="'.$row['employee_name'] . '>"'.$row['employee_name'] .'</option>';
}
echo "</select>";