dongxi1680 2013-12-05 11:57
浏览 73
已采纳

从PHP MySQL数组填充HTML选择列表

I'm fetching a list of 'actors' from my MySQL database table actors & trying to populate the result into a HTML Select box:

    <?php
$query = "SELECT actor_name FROM actors";
$result = mysql_query($query) or die("<h1>Error - the query could not be executed</h1>
");
$num_rows = mysql_num_rows($result);
$row = mysql_fetch_array($result);

print("<h3>Actors</h3>
");
print($num_rows);
if($num_rows == 0){
    print("<h3>No items are currently recorded in table Actors</h3>
");
}
else{
    print("<select id=\"actors\" name=\"actors\">
");
    for($i = 0; $i < $num_rows; $i++){
        print("<option>$row[$i]</option>");
        $row = mysql_fetch_array($result);
    }
    print("</select>");
}
?>

Error: Notice: Undefined offset: 1 in C:\xampp\htdocs\actors.php on line 16

I'm getting a Undefined offset notice from the second record in the array onwards. When I add an isset check the select box is only populated with the first record. This would indicate that there is something wrong my query? I've checked my table, and there are 113 records.

Any help would be greatly appreciated.

Cheers,

Sam

  • 写回答

2条回答 默认 最新

  • dqwh1209 2013-12-05 11:59
    关注

    I think below code looks better and works well.

    $query = "SELECT actor_name FROM actors";
    $result = mysql_query($query) or die("<h1>Error - the query could not be executed</h1>
    ");
    $num_rows = mysql_num_rows($result);
    
    print("<h3>Actors</h3>
    ");
    print($num_rows);
    
    if($num_rows == 0)
    {
        print("<h3>No items are currently recorded in table Actors</h3>
    ");
    }
    else
    {
        print("<select id=\"actors\" name=\"actors\">
    ");
        while ($row = mysql_fetch_array($result))
        {
                print("<option>$row[0]</option>");
        )
        print("</select>");
        mysql_free_result($result);
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?