Sam H
Sam H

Reputation: 7

Populating an HTML select list from a PHP MySQL array

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

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.

Upvotes: 0

Views: 991

Answers (2)

R R
R R

Reputation: 2956

 $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`**

you are using $row = mysql_fetch_array($result); twice

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

    }

the correct loop will be:

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

    }

Upvotes: 1

Jason Heo
Jason Heo

Reputation: 10246

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>\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);
}

Upvotes: 1

Related Questions