简体   繁体   中英

Fill drop down list via mysql select query

I have this php script that's supposed to fill a drop down list ; I actually embedded it into the 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>

If you can help me to define the error and if this is the wrong way to do it ; what the best way is. I'd be grateful for implementations . thanks in advance :)

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

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']

我认为您的代码没有任何问题,请再次检查您的数据库连接,然后尝试一下。因为我在本地主机中尝试了您的代码,并在下拉列表中获取了cat_name。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM