Reputation: 3
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
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
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
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
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