Danny3man
Danny3man

Reputation: 3

HTML Select Not Showing All Options

I have a form with a dynamic select option inside which is taking its options from a database through PHP. The main problem is that although it is working, it is not showing the first record from database. This is the code:

<select name="elevi" >
    <?
    $sql="Select * from elevi";
    $query=mysql_query($sql)or die(mysql_error());
    $result=mysql_fetch_array($query);
    while($result=mysql_fetch_array($query)){
        echo'<option value="'.$result['id_elev'].'">'.$result['nume']."".$result['prenume'].'</option>';
    }
    ?>
</select>

Upvotes: 0

Views: 1234

Answers (4)

Amrinder Singh
Amrinder Singh

Reputation: 5492

you are using $result=mysql_fetch_array($query); twice, it should be used once, for example,

<select name="elevi" >
<?php
    $sql="Select * from elevi";
    $query=mysql_query($sql)or die(mysql_error());
 while($result=mysql_fetch_row($query)){
 echo'<option value="'.$result['id_elev'].'">'.$result['nume']." ".$result['prenume'].'</option>';}?>
</select>

Upvotes: 0

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476659

You need to fetch one row at a time

<select name="elevi" >
    <?php
        $sql="Select * from elevi";
        $query=mysql_query($sql)or die(mysql_error());
     while($result=mysql_fetch_row($query)){
     echo'<option value="'.$result['id_elev'].'">'.$result['nume']." ".$result['prenume'].'</option>';}?>
    </select>

Or in case of bulk data, fetch the array and then loop through the array (the results are however fetched with one call making the code more efficient)

Upvotes: 1

Philip
Philip

Reputation: 46

mysql_fetch_array() moves its internal data pointer forward by one each time it is called, until there are no more options and it returns false. This is why you can use the while loop.

So if you remove you first $result=mysql_fetch_array($query) call, you'll be fine.

Upvotes: 1

Fabien Warniez
Fabien Warniez

Reputation: 2741

Remove the first $result=mysql_fetch_array($query);

This line basically throws away the first record.

In the while loop, you do 2 things, assign $result with the result of mysql_fetch_array(), and check if that result is null or not.

Upvotes: 4

Related Questions