Let’s say you want to have a simple HTML <select> form as a drop down for rows in a Mysql table. This could be for things like categories, pages, games, anything you want to have in a drop down to navigate to another page or submit a form. What ever the case is, I’m going to make a simple layout for displaying rows returned from a mysql query as <option>’s in a HTML <select> or drop down.
Before we can grab anything from a mysql database we have to connect to it. Find how to connect to a mysql database here.
Let’s make our mysql query first:
// index.php
// Connect to mysql database here!
$sql = mysql_query("SELECT * FROM table1 ORDER BY id DESC") or die(mysql_error());
?>
This will grab all the rows in “table1″ ordered by the value of “id” descending. You can make this query whatever you want whether you want it ordered differently or with other requirements, etc. Now we will just make a <select> inside of a HTML form that holds each of these values as a option.
Here is where we will insert our PHP code to call the returned rows of our Mysql query and display them as HTML <option> tags inside of the <select> tag.
// Display mysql rows
if(mysql_num_rows($sql) > 0){
// We have some results!
while($row = mysql_fetch_array($sql)){
echo "<option value=\"".$row["id"]."\">".$row["title"]."</option>";
}
}
else {
echo "<option value=\"0\">No categories found.</option>";
}
?>
Now we close up our HTML and see the finished result!
If you have rows returned in you mysql query you will have a HTML drop down that looks like this:
This HTML form is being submitted to “index.php?do=nav.” Of course you can point this where ever you want to do whatever you want with it, but let’s say we want to have it direct you to a category with PHP. So we are going to run a function on index.php?do=nav that will redirect the viewer to the category.
Someone on July 24, 2010
This thing is pretty awesome, I was doing something similar once and it ended up well… just like this!
Thanks for sharing your tips
registry cleaner review on July 27, 2010
Great information here! I have been looking for this everywhere, and I’m happy I finally found it! Keep up the great work.
Lieselotte Grabill on July 28, 2010
I’ll be back again, thanks for the info.
SEO hosting on July 31, 2010
A very interesting read and a great post alltogether. Would you mind if I posted the same article on my blog (with a reference to your website)?
Mitchel Grambo on August 9, 2010
Hi, I just tried to email you regarding this post but cannot get in touch with you. Please email me if get a moment. Thank you.
Denny Huberman on August 17, 2010
I really like your blog. Very good content. Please keep posting such great cotent.