使用PHP从MYSQL填充动态html / javascript下拉列表 [英] Dynamic html/javascript drop down list populated from MYSQL using PHP
问题描述
我有一个带有javescript的html文档,并且在那个html中doc,我想创建一个下拉列表,其值由mysql查询的结果自动填充。
我猜我需要运行一个php脚本从数据库中获取信息,但是如何将这些信息放入下拉菜单对我来说是一个谜。
请允许有人指出我在莱特方向 - 也许是例如,某人已经这样做了。我不能只在PHP中写下下拉菜单,因为这意味着要离开我拥有其他所有内容的html页面。
非常感谢,
Rob。
这是一个非常广泛的问题,所以我可以给你一个广泛的答案。简单的指导原则。
您可以选择:
< select name =fos>
<?php
// php代码从mysql获取数据
// foreach / while遍历元素
echo'< option value =''。$ key '>' $值 '< /选项>'。;
//结束foreach / while
?>
< / select>
使用Ajax载入资料
$ b
编辑:或采取
无论您选择哪种方式,我都会向您提供搜索关键字或提出进一步问题
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 everything 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
这篇关于使用PHP从MYSQL填充动态html / javascript下拉列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!