【问题标题】:How to Populate Dropdown List's text and value from MySQL?如何从 MySQL 填充下拉列表文本和值?
【发布时间】:2011-09-12 17:46:17
【问题描述】:

我正在使用 mysqli 查询数据库表以获取下拉列表的值。但是,我还想检索相应的描述并将其加载到选项文本中。我的查询如下:

<?php 
$query=('SELECT restaurantid,location from restaurant');
$result = mysqli_query($mysqli,$query);
echo '<select name="ddlStore">';
while($row=$mysqli->fetch_array($result))
{
    echo '<option value="' . htmlspecialchars($row['restaurantid']) . '">';
    '</option>';
}
echo '</select>';
?>

如何修改上述内容,以便在下拉列表的选项文本中填充位置字段?

更新代码:

<?php 
$query=('SELECT restaurantid,location from restaurant');
$result = mysqli_query($mysqli,$query);
echo '<select name="ddlStore">';
while($row=$mysqli->fetch_array($result))
{
    echo '<option value="' . htmlspecialchars($row['restaurantid']) . '">' .
     htmlspecialchars($row['location']) . 
    '</option>';
}
echo '</select>';
?>

上面仍然没有将位置显示为下拉列表选项文本值。

更新 #2: 查看页面时,下拉列表不显示数据库表中的值。使用 IE Developer Tools,我在 while 语句中看到一个脚本错误:

Call to undefined method mysqli::fetch_array()

是否有更优化的方式来构造 mysqli_fetch_array 语句?

【问题讨论】:

  • @65Fbef05:只是履行我的公民义务。 :)

标签: php mysqli


【解决方案1】:

更改为...

echo '<option value="' . htmlspecialchars($row['restaurantid']) . '">' . htmlspecialchars($row['location']) . '</option>';

【讨论】:

  • 你的意思是&lt;/option&gt;最后吗?
  • 最后,我将在我的 while 语句中关闭
  • @Herbert, @SidC - 很抱歉 - 我的意思是关闭 option 标签而不是 select 标签。我的错。 :P
【解决方案2】:
echo '<option value="' . htmlspecialchars($row['restaurantid']) . '">' . htmlspecialchars($row['location']) . '</option>';

但是到目前为止你尝试过什么?

【讨论】:

    【解决方案3】:

    试试这个方法 (more info here)

    $result = $mysqli->query($query)
    
    while($row = $result->fetch_assoc()) {
    
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-10-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-09-21
      相关资源
      最近更新 更多