Reputation: 9064
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 with code..
Upvotes: 1
Views: 13385
Reputation: 19251
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.
Upvotes: 1
Reputation: 18531
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;
?>
Upvotes: 0