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


Populating an HTML select list from a PHP MySQL array

我正在从MySQL数据库表actors&尝试将结果填充到HTML选择框中:

    <?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:''examplep''htdocs''actors.php中的1

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

如有任何帮助,我们将不胜感激。

我认为下面的代码看起来更好,工作也很好。

$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);
}
 $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>");
    }