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

时间:2013-12-05 11:57:48

标签: php mysql sql

我正在提取一个“演员”列表'来自我的MySQL数据库表演员&尝试将结果填充到HTML Select框中:

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

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

错误: 注意:未定义的偏移量:第16行的C:\ xampp \ htdocs \ actors.php中的1

我从数组中的第二条记录开始收到未定义的偏移通知。当我添加一个isset检查时,选择框仅填充第一个记录。这表明我的查询有问题吗?我检查过我的桌子,共有113条记录。

非常感谢任何帮助。

干杯,

萨姆

2 个答案:

答案 0 :(得分:1)

我认为下面的代码看起来更好,效果很好。

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

print("<h3>Actors</h3>\n");
print($num_rows);

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

答案 1 :(得分:1)

 $query = "SELECT actor_name FROM actors";
    $result = mysql_query($query) or die("<h1>Error -
    the query could not be    executed</h1>\n");
    $num_rows = mysql_num_rows($result);
    $row = mysql_fetch_array($result);
-`--------^^^^^^ //**you are already fetching the array once`**

您正在使用$row = mysql_fetch_array($result);两次

for($i = 0; $i < $num_rows; $i++){
        print("<option>$row[$i]</option>");
        $row = mysql_fetch_array($result);
----------------^^^^//**remove this**

    }

正确的循环将是:

for($i = 0; $i < $num_rows; $i++){
        print("<option>$row[$i]</option>");

    }