【问题标题】:Select input filled with SQL from database从数据库中选择用 SQL 填充的输入
【发布时间】:2012-10-02 04:18:29
【问题描述】:

我想用从我的 SQL 数据库中获取的信息填充下拉列表。 我进行了查询,并想使用 while 循环来回显输入字段。

我现在拥有的:

我看到一个下拉菜单选项,其中没有数据。

我想要什么:

选项选择中的信息。

<dt><label for="image">Bild</label></dt>
<select id="image" name="ak_image" value="<?php echo $ak_image; ?>">
<?php 
  $result = mysql_query("SELECT bi_pfad, bi_name FROM tbl_bilder "); 
  $options = ""; 
  while ($row = mysql_fetch_array($result)) {
    $bi_name = $row["bi_name"];
    $bi_pfad = $row["bi_pfad"];
    $options .= "<option value=\"$bi_pfad\">".$bi_name."</option>\n";
  } 
  echo $options; 
  echo "</select>\n";
?>

【问题讨论】:

  • 首先.. 你的 元素没有 value 属性,因此被忽略。因此,您只有一个选择
  • 您是否检查了您要查询的表以确保其中有数据?
  • @Thomas 是的。我在 phpmyadmin 中输入了相同的查询,我得到了所有信息。
  • 您是否正在检查来自mysql_query 的错误?
  • 如果你在浏览器中查看View Source,你会看到选项吗?

标签: php mysql select drop-down-menu option


【解决方案1】:

由于您已经通过 phpmyadmin 验证了有数据,这导致了几个后续问题:

  • 您是否成功地执行了此页面上的任何其他查询?如果不是,那么最可能的罪魁祸首是与数据库的连接不成功。
  • 您是否在此 sn-p 之前运行 mysql_connect()?

您可能还想稍微重构一下,以确保查询函数知道适当的连接并引入一些错误捕获。

<?
    // Somewhere towards the beginning of this page/view.
    $db_connection = mysql_connect( $host, $user, $password );
?>

<dt><label for="image">Bild</label></dt>
<select id="image" name="ak_image" value="<?php echo $ak_image; ?>">
<?php 
  // Affirmatively pass the connection to the query. Also, check for errors.
  $result = mysql_query("SELECT bi_pfad, bi_name FROM tbl_bilder ", $db_connection); 
  if( $result )
  {
      $options = ""; 
      while ($row = mysql_fetch_array($result)) {
        $bi_name = $row["bi_name"];
        $bi_pfad = $row["bi_pfad"];
        $options .= "<option value=\"$bi_pfad\">".$bi_name."</option>\n";
      } 
      echo $options;
  }
  else
  {
        // Perform error trapping here.
  } 
  echo "</select>\n";
?>

另外,如果您的 PHP 版本足够新以支持它们,那么切换库可能是一个好主意。至少我会切换到mysqli 或允许参数化查询设置的东西。

【讨论】:

    猜你喜欢
    • 2021-10-21
    • 2019-05-08
    • 1970-01-01
    • 2018-09-11
    • 2013-07-03
    • 2013-03-04
    • 1970-01-01
    • 1970-01-01
    • 2012-06-07
    相关资源
    最近更新 更多