Monday, October 12, 2009

Listbox values in PHP with MySql

Today got some free time to write a simple tutorial for PHP with MySql for listbox.
So lets start.

Mostly we use drop down on many occasions, populated from database dynamically or giving it values statically. And then use PHP code to parse it and store it in database or get our desired results.
One type of that dropdown is listbox, where we can select multiple entries.
Here is a sample example of it:


In the above code:
multiple: represent multiple list for values
size: will show 2 values in the list, and others will be shown by scrolling.
name: is holding name in array.

Now lets take a MySql example:


Now lets jump to PHP to get the desired results.
There are many ways to get the results like:
foreach, for and etc. As we know, POST is also an array. So the best bet is to use array.

$drop_list = $_POST['drop_list'];
$_SESSION['drop_list'] = $drop_list;
if (in_array(1, $drop_list)) { //id 1
$query1 = "SELECT * FROM test2 where id='1'";
$res1 = mysql_query($query1) or die(mysql_error());
//You can do some other stuff here too
}


You can use multiple if statements to verify the variable resulted value.
You can save the value in session to use it globally in your scripts.
Example:
if (in_array(2, $drop_list)) { //id 2
$query1 = "SELECT * FROM test3 where id='2'";
$res1 = mysql_query($query1) or die(mysql_error());
//You can do some other stuff here too
}
if (in_array(3, $drop_list)) { //id 3
$query1 = "SELECT * FROM test4 where id='3'";
$res1 = mysql_query($query1) or die(mysql_error());
//You can do some other stuff here too
}


Apart from the above example, there are many ways like foreach, if you don't want to just use one by one. Like:

foreach($_POST['drop_list'] as $drop_list){
//Do your stuff here like, updating multiple records at one shot.
}


Best of luck.
ANL

No comments: