[英]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. 我有一个带有javescript的html doc,在那个html doc中,我想创建一个下拉列表,其值从mysql查询的结果中自动填充。
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. 我猜我需要运行一个php脚本来从数据库中获取信息,但是如何将这些信息输入到下拉列表对我来说是一个谜。
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. 我不能只用PHP编写下拉列表,因为这意味着要远离我拥有其他所有内容的html页面。
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 把PHP放在HTML中
xy.php/html 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 使用Ajax加载数据
EDIT: or Take the approach that Haza suggested 编辑:或采取Haza建议的方法
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 : 如果您正在谈论一些花哨的Javascript下拉菜单列表,则有两部分:
Get the data you need to display to the user, and print them in the html in as known strcture (usually some <ul><li>
...). 获取您需要显示给用户的数据,并在html中以已知的结构打印它们(通常是一些<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. 使用一些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. 所以,首先你需要在你的代码中找到它的一部分是简单列表,使用相同的结构将数据添加到它中,并且它们,你的js脚本将能够转换它。
Welcome to the world of web development. 欢迎来到web开发世界。 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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.