如何从数据库中获取数据并将其显示在html中的组合框中

时间:2017-09-11 02:06:28

标签: php html sql

<tr>
    <td>Subject:</td>
    <td>
        <select name="Subject">
            <option value="<?php echo $Subject;?>"></option>
        </select>
    </td>
</tr>
<?php
 $connection = mysqli_connect("localhost", "root", "", "phobiamming") or die (mysqli_error());
 $sql = "SELECT * FROM section";
 $result = mysqli_query($connection, $sql);

 while ($row= mysqli_fetch_array($result)) {
    echo $row['Subject'];
 }

 $connection->close();
 ?>

我无法将数据从DB显示到组合框。我不知道我的代码是否正确。

    <tr>
    <td>Subject:</td>
    <td><select name="Subject">
        <option value="Subject"><?php $connection = mysqli_connect("localhost", "root", "", "phobiamming") or die (mysqli_error());

  // SQL query
  $strSQL = "SELECT * FROM  sections";

  // Execute the query (the recordset $rs contains the result)
  $rs = mysqli_query($connection, $strSQL);

  // Loop the recordset $rs
  // Each row will be made into an array ($row) using mysql_fetch_array
  while($row = mysqli_fetch_array($rs)) {

     // Write the value of the column FirstName (which is now in the array $row)
    echo $row['Subject']. "<br>";



    }

  // Close the database connection
  $connection->close(); ?></option>
    </select></td>
   </tr>

这是我的更新代码,我已经可以显示来自数据库的数据,但另一个问题是数据库中将显示的行,它不能创建换行符

1 个答案:

答案 0 :(得分:0)

将选项值放入while循环

<tr>
    <td>Subject:</td>
    <td>
    <select name="Subject">
<?php
$connection = mysqli_connect("localhost", "root", "", "phobiamming") or die 
(mysqli_error());
$sql = "SELECT * FROM section";
$result = mysqli_query($connection, $sql);

while ($row= mysqli_fetch_array($result)) { ?>
        <option value="<?php echo $row['$Subject']; ?>"><?php echo $row['$Subject']; ?></option>
<?php
}
$connection->close();
?>
    </select>
    </td>
</tr>