在 PHP 中使用来自 mysql 的数组数据填充 html<select>


Populate html <select> with array data from mysql in PHP

我可以看到返回结果的查询,但我似乎无法将它们放入 html 下拉框中。此外,下拉框包含的条目数与查询返回的条目数一样多,但它们都是空格。但是,页面源显示正确的选项值,例如

<option value="3 John"></option>
<option value="Jude"></option>
<option value="Revelation"></option>

有人可以帮助我吗?为什么它们实际上没有显示在下拉框中?

<html>
<?php
    //Connect to the database
    $mysqli = new mysqli("localhost", "root", "", "bible");
    //Return an error if we have a connection issue
    if ($mysqli->connect_error) {
        die('Connect Error (' . $mysqli->connect_errno . ') '
                . $mysqli->connect_error);
        }
    //Query the database for the results we want
    $query = $mysqli->query("select distinct bname as Name from kjv limit 1");
    //Create an array  of objects for each returned row
    while($array[] = $query->fetch_object());
    array_pop($array);
    //Print out the array results
    print_r($array);
    ?>
    <h3>Dropdown Demo Starts Here</h3>
    <select name="the_name">
    <?php foreach($array as $option) : ?>
        <option value="<?php echo $option->Name; ?>"></option>
    </select>
        <?php endforeach; ?>

试试这个

<select name="the_name">
<?php foreach($array as $option) : ?>
        <option value="<?php echo $option['Name']; ?>"><?php echo $option['Name']; ?></option>
<?php endforeach; ?>
</select>

执行查询后,使用 while 循环添加要选择

$query = $mysqli->query("select distinct bname as Name from kjv limit 1"); ?>
<select>
    <?php while($option = $query->fetch_object()){ ?>
        <option><?php echo $option->Name; ?></option>
    <?php } ?>
</select>

不确定array_pop在代码中做了什么

正如TIM WAX所说,这就是解决方案

$query = $mysqli->query("select distinct bname as Name from kjv limit 1"); ?>
<select>
    <?php while($option = $query->fetch_object()){ ?>
        <option><?php echo $option->Name; ?></option>
    <?php } ?>
</select>
<select name="the_name">
<?php foreach($array as $option) : ?>
        <option value="<?php echo $option->Name; ?>"></option>
<?php endforeach; ?>
</select>

您结束循环的方式也一次又一次地创建了<select>标记。更改它,然后重试。我对.php了解不多,但在显示下拉框时可能会出现问题。

这是我的..我是初学者,但它对我有用,

    $query = $mysqli->query("SELECT * FROM  `student_type_db`"); //table of student type
    echo "<select>";
    while($row = $query->fetch_array()){
         echo "<option>";
         echo $row['student_type'] . " - " . $row['student_description'];
         echo "</option>"; 
    }
    echo "</select>";
   // student type = 1 | student description = regular
   // output : 1 - regular