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 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?