Reputation: 97
I have this php script that's supposed to fill a drop down list; I actually embedded it into the <select>
element but it didn't work.
Here's my script to clearly explain my problem :
<select name="cats">
<?php
require_once("connection.php");
$rs = mysql_query("select cat_name from category");
$count = 0;
while($array = mysql_fetch_array($rs)){
echo "<option>".$array[$count]."</option>";
}
mysql_close($con);
?>
</select>
Can help me to define the error and if this is the wrong way to do it? What is the better approach?
Upvotes: 0
Views: 912
Reputation: 6736
i think there is not any issues with your code , check your database connection again and try.because i try your code in my localhost and fetch cat_name in dropdown list.
Upvotes: 0
Reputation: 100205
change:
while($array = mysql_fetch_array($rs)){
echo "<option>".$array[$count]."</option>";
}
to
while($array = mysql_fetch_array($rs)){
echo "<option value='".$array["cat_id"]."'>".$array["cat_name"]."</option>";
}
where cat_id
is id of your category table
Upvotes: 1
Reputation: 3932
In general terms this is the right way to do it. I assume the problem is here:
echo "<option>".$array[$count]."</option>";
Your $count
is necessarily 0, so you will always be outputting $array[0]
, which is the first field that's being selected (usually some kind of ID, but it depends on the table structure). This may or may not be the right field in the table.
What I recommend is first to specify the exact fields you're selecting. For example:
select `id`, `text` from `category`
And then use the associative array $array
to get what you want, for example: $array['id']
Upvotes: 0