Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mysql select distinct query in PHP

$sql = "SELECT DISTINCT Branch FROM student_main";
    $result = mysql_query($sql);
    $row_num = mysql_num_rows($result);
    $rows = mysql_fetch_array($result);
    echo "<select name='Branch'>";
    for($i=0;$i<=$row_num-1;$i++){
        echo "<option value='".$rows[$i]."'>".$rows[$i]."</option>";

    }
    echo "</select>";
    echo "<input type='submit' Value='submit' />";
    echo "</form>";

I am trying to create a dropdown using the above code for my form. But its not working. There are 3 distinct values in the Branch column but in the dropdown, it shows only one value(the first one) and the next two as blank values.

However when in echo $row_num, its shows 3.
Thats means its fetching the three rows, but then why its not showing in the dropdown list.

If I run the same query in phpmyadmin it shows the correct answer i.r it returns 3 distinct Branch values.

like image 994
hsinxh Avatar asked Nov 28 '22 22:11

hsinxh


2 Answers

You should do something like this:

$sql = "SELECT DISTINCT Branch FROM student_main";
$result = mysql_query($sql);

echo "<select name='Branch'>";
while ($row = mysql_fetch_array($result)) {
    echo "<option value='".$row[0]."'>".$row[0]."</option>";
}
echo "</select>";

echo "<input type='submit' Value='submit' />";
echo "</form>";
like image 72
aorcsik Avatar answered Dec 04 '22 09:12

aorcsik


you need to mysql_fetch_array() for each row. That function returns an associative array for one row only. just include it inside your for loop just above your echo statement.

edit: mysql_fetch_array() actually returns an array (by default) that has associative indices and numbered indices. You can continue using it the same way, though.

like image 44
Scott M. Avatar answered Dec 04 '22 09:12

Scott M.