Dynamic html/javascript drop down list populated from MYSQL using PHP
I think I must be missing something very simple here (and apologies if I am).
I have a html doc with javescript in it, and in that html doc, I want to create a dropdown list whose values are automtically populated from the result of a mysql query.
I'm guessing that I need to run a php script to get the info from the database, but then how to get that info into the dropdown is a mystery to me.
Please could someone point me in the wright direction - perhaps an example where someone has already done this.
I can't just write the dropdown in PHP as it would mean going away from the html page that I have ever开发者_如何学JAVAything else on.
Many thanks,
Rob.
This a very broad question, so I can give you a broad answer. Simple guidelines.
You have some options:
Put PHP in the HTML
- rename your .html to .php or change your webserver settings (through .htaccess probably if you use Apache) to let php process .html files
- put something like this into the HTML code at the appropriate place:
xy.php/html
<select name="fos">
<?php
//php code to get data from mysql
//foreach/while to iterate through elements
echo '<option value="'.$key.'">'.$value.'</option>';
//end of foreach/while
?>
</select>
Use Ajax to load data
- leave the HTML as it is now
- write a PHP script to output the dropdown
- write Javascript to get the output of the PHP script with Ajax, then insert it to the DOM in the appropriate place
- the downside is that people without JS won't see the dropdown
EDIT: or Take the approach that Haza suggested
Whichever you choose, I've given you the keywords to search for or ask further questions on
If you are talking about some fancy Javascript dropdown menu list, there is two part :
Get the data you need to display to the user, and print them in the html in as known strcture (usually some
<ul><li>
...). This will just create a list, wich is what a menu should generally be.Transform this simple list into you dropdown menu using some javascript.
So, first you need to find in your code wich part of it is the simple list, add your data into it using the same structure, and them, your js script will be able to transform it.
Welcome to the world of web development. My dear first try to do some search. Here is some code through which you can accomplish your task
<select name='myselect'>
<?php
$q="select * from $table";
$rs=mysql_query($q);
if($rs && mysql_num_rows($rs))
{
while($rd=mysql_fetch_object($rs))
{
echo("<option value='$rd->id'>$rd->name</option>");
}
}
?>
</select>
精彩评论