简体   繁体   English

使用php和mysqli填充下拉框

[英]Populating a drop down box using php and mysqli

We have been given the task where we have to populate a drop down box with data from a database using PHP and MySQL etc. This is the code I have so far. 我们已经获得了必须使用PHP和MySQL等从数据库中填充数据的下拉框的任务。这是我到目前为止的代码。 So far since I have tested it, it is showing the drop down box but other than that there is nothing in the drop down menu populating it. 到目前为止,由于我已经对其进行了测试,因此它显示了下拉框,但除此之外,下拉菜单中没有任何内容。

<?php

$hostname = 'host';
$username = 'username';
$password = 'password';
$databaseName = 'dbname';

$connect = mysqli_connect($hostname, $username, $password, $databaseName);

$query = 'SELECT * FROM `User`';

$result1 = mysqli_query($connect, $query);
$result2 = mysqli_query($connect, $query);

$options = '';
while ($row2 = mysqli_fetch_array($result2)) {
    $options = $options . "<option>$row2[1]</option>";
}

?>
<!DOCTYPE html>
<html>
<head>
    <title> PHP SELECT OPTIONS FROM DATABASE </title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<select>
    <?php while ($row1 = mysqli_fetch_array($result1)):; ?>
        <option value="<?php echo $row1[0]; ?>"><?php echo $row1[1]; ?>        </option>
    <?php endwhile; ?>
</select>
<select>
    <?php echo $options; ?>
</select>
</body>
</html>

Try 尝试

  While($row = mysqli_fetch_assoc($result)){

 $therow = row['column_name'];

  echo '
  <option value='.$therow.'>'.$therow.'</option>
  ';
  }

Hope this give you a clue Cos in your code above, you had two results and it's really hard to tell which is which and what does what. 希望上面的代码为您提供了一条线索,因为您有两个结果,而且很难分辨出哪个是做什么的。

Also, using the associative array makes it easier or simple to work with the columns in the table so one doesn't get confused... 而且,使用关联数组可以更轻松或简单地处理表中的列,因此不会混淆...

Alternatively, if you need the options as a variable to use outside the while loop. 或者,如果您需要将选项作为变量使用在while循环之外。

Do

  $option .= '<option value='.$therow.'>'.$therow.'</option>';

Inside the loop 循环内

Then in your html 然后在你的HTML

   <select>

      <?php echo $option; ?>

    </select>

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

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