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

标签 php mysql sql

我正在从 MySQL 数据库表 actor 中获取“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>");
}
?>

错误:

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

我从数组中的第二条记录开始收到 undefined offset 通知。当我添加 Assets 时,请检查选择框仅填充第一条记录。这是否表明我的查询有问题?我检查了我的表,有 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);
}

关于php - 从 PHP MySQL 数组填充 HTML 选择列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20399405/

相关文章:

php - tinyMCE 和 wordpress 给出奇怪的字符...尝试了解决方案的组合

MySQL 选择一行,将多行连接到其中

c# - 管理内存

mysql - 如何编写查询来获取基于月份的数据?

sql - 如何选择适合我的目的的数据库?我想存储文件元数据。

php - 移动检测高流量站点

php - 如何在 hacklang/hhvm 中使用 Mysql PDO 驱动程序

php - 如何将我的 PHP 5.3.3 更新到 PHP 5.3.8 Linux Centos

php - 如何查看以下系统中的反向关系

python - 进行迁移后,Django 新属性未显示在管理仪表板中