开发者

Populating combo-box dynamically with mysql table values , using php and javascript

开发者 https://www.devze.com 2023-03-16 17:48 出处:网络
I want to populate a combo-box on runtime with mysql table values, conditionally, on the basis of a value selected in another combo-box . Can this be implemented by only using PHP, or will i need some

I want to populate a combo-box on runtime with mysql table values, conditionally, on the basis of a value selected in another combo-box . Can this be implemented by only using PHP, or will i need some client side scripting language such as Javascript?

Please help wi开发者_StackOverflow社区th code..


Yes, it is possible using javascript and PHP. Your javascript would use AJAX to query a PHP script giving the PHP script the value of the first combo box. The PHP script would then return a list of values that the javascript can then use to populate the second combo box.

You might find it easier to use something like JQuery to make the javascript scripting part easier.


Suppose your table looked like this

mysql> select * from FRUITS;
+---------+-----------+
| fruitid | fruitname |
+---------+-----------+
|       1 | Orange    |
|       2 | Apple     |
|       3 | Pear      |
|       4 | Banana    |
+---------+-----------+
4 rows in set (0.02 sec)

Your code should then look something like this:

<?php

 $conn = mysql_connect('localhost','yourUsernameHere','yourPasswordHere');

 mysql_select_db('testdb',$conn);

 $query = "select fruitid,fruitname from FRUITS order by fruitname";

 $result = mysql_query($query,$conn);

 $selectbox='<select name=\'fruit\'>';

 while ($row = mysql_fetch_assoc($result)) {
     $selectbox.='<option value=\"' . $row['fruitid'] . '\">' . $row['fruitname'] . '</option>';
 }

 $selectbox.='</select>';

 mysql_free_result($result);

 echo $selectbox;

?>
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号