動態下拉式選單(結合資料庫)

  • 45944
  • 0

摘要:動態下拉式選單(結合資料庫)

首先要感謝這一篇介紹:

http://neural.cs.nthu.edu.tw/jang/books/javascript/dynamicSelect.asp?title=7-3+%B0%CA%BAA%A4U%A9%D4%A6%A1%BF%EF%B3%E6

 

然後因為希望做到從資料庫抓資料做成下拉式選單,因此已經有個假選單(空的),

接著就是要把它增加選項。

html的部分是這樣:

 

 <select id="shopList">
    <option></option>
    </select>    
 
重點就是要有id。
接著php要加在</body>與</html>之間,否則在那之前他是不認得id的。

</body>
<?php
$mysqlhost="localhost";
$mysqluser="你的帳號";
$mysqlpasswd="你的密碼";

// 建立資料庫連線
$link =
	@mysql_connect($mysqlhost, $mysqluser, $mysqlpasswd);
if ($link == FALSE) {
	echo "不幸地,現在無法連上資料庫。請查詢資料庫連結是否有誤,請稍後再試。\n".mysql_error();
	exit();
}
		
mysql_query("set names utf8");
$mysqldbname="資料庫名";
mysql_select_db($mysqldbname);

$shops = mysql_query("select * from 資料庫的table;");
if(!$shops){
   	echo "Execute SQL failed : ". mysql_error();
	exit;
}
$shopCodeArr=array();     //用來存哪些選項的陣列
$shopCount=0;
while($rows=mysql_fetch_array($shops))
{
	$shopCodeArr[$shopCount]=$rows[shopCode];
	$shopCount++;
}
for($i=0;$i<count($shopCodeArr);$i++)
{
	echo "<script type=\"text/javascript\">";
	echo "document.getElementById(\"shopList\").options[$i]=new Option(\"$shopCodeArr[$i]\",\"$shopCodeArr[$i]\")";
	echo "</script>";
}
?>
</html>

 

所以大概就是這樣:


<html>
<head>
<title>下拉式選單測試</title>
</head>
<body>
    <select id="shopList">
    	<option></option>
    </select>  
</body>
<?php
$mysqlhost="localhost";
$mysqluser="你的帳號";
$mysqlpasswd="你的密碼";

// 建立資料庫連線
$link =
	@mysql_connect($mysqlhost, $mysqluser, $mysqlpasswd);
if ($link == FALSE) {
	echo "不幸地,現在無法連上資料庫。請查詢資料庫連結是否有誤,請稍後再試。\n".mysql_error();
	exit();
}
		
mysql_query("set names utf8");
$mysqldbname="資料庫名";
mysql_select_db($mysqldbname);

$shops = mysql_query("select * from 資料庫的table;");
if(!$shops){
   	echo "Execute SQL failed : ". mysql_error();
	exit;
}
$shopCodeArr=array();     //用來存哪些選項的陣列
$shopCount=0;
while($rows=mysql_fetch_array($shops))
{
	$shopCodeArr[$shopCount]=$rows[想要的資料表內容];
	$shopCount++;
}
for($i=0;$i<count($shopCodeArr);$i++)
{
	echo "<script type=\"text/javascript\">";
	echo "document.getElementById(\"shopList\").options[$i]=new Option(\"$shopCodeArr[$i]\",\"$shopCodeArr[$i]\");";
	echo "</script>";
}
?>
</html>

 

在javascript最重要的就是這一行:
document.getElementById("shopList").options[索引]=new Option(資料的文字,資料的值);

 

然後祝大家開工愉快:)