drop-down menus and mysql

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
Lisa.W
Forum Newbie
Posts: 2
Joined: Mon Jan 20, 2003 2:40 pm

drop-down menus and mysql

Post by Lisa.W »

Hi!

I’d be grateful, if you could help me solving a problem with php and mysql.
I have got a mysql database. There is a table in this database, called “categories”. I want to create a html (or php)-Page with a drop-down menu. And in this menu, I want to insert the values in the table categories. The user can choose a category, and is directed to another html-Page, depending on his choice.
Could you help me getting the categories from the mysql-table into the drop-down menu on my php-Page?

Thanks for your help.

Best regards,
Lisa W.
User avatar
daven
Forum Contributor
Posts: 332
Joined: Tue Dec 17, 2002 1:29 pm
Location: Gaithersburg, MD
Contact:

Post by daven »

two options come to mind. One involves creating an array, and the other does not. Technically, it would be better to use the array, but either method will work. The code surmizes that you have table "categories" with column "category_name".
1. with array

Code: Select all

<?php
$query="SELECT * FROM categories";
$result=mysql_query($query,$db_conn);
for($i=0;$i<mysql_num_rows($result);$i++){
    $category_array[$i]=$row[category_name];
}
?>

Code: Select all

&lt;HTML&gt;
&lt;select name="category"&gt;
    &lt;?for($i=0;$i&lt;count($category_array);$i++)&#123;
        print "&lt;option&gt;".$category_array&#1111;$i];
    &#125;?&gt;
&lt;/select&gt;
&lt;/HTML&gt;
2. without arrays

Code: Select all

<?php
$query="SELECT * FROM categories";
$result=mysql_query($query,$db_conn);
?>

Code: Select all

&lt;HTML&gt;
&lt;select name="category"&gt;
    &lt;?while($row=mysql_fetch_assoc($result))&#123;
        print "&lt;option&gt;".$row&#1111;category_name];
    &#125;?&gt;
&lt;/select&gt;
&lt;/HTML&gt;
Then do whatever form/javascript processing you have in mind.
Lisa.W
Forum Newbie
Posts: 2
Joined: Mon Jan 20, 2003 2:40 pm

Post by Lisa.W »

Thank you very much for the prompt answer!

I will try your code straight away.

Best wishes,
Lisa.W
User avatar
Skywalker
Forum Contributor
Posts: 117
Joined: Thu Aug 29, 2002 3:33 am
Location: The Netherlands

Post by Skywalker »

<?while($row=mysql_fetch_assoc($result)){
print "<option>".$row[category_name];
}?>

you write <? to open php try [<?php] insted of [<?]

?>
Post Reply