Forum Moderators: coopster

Message Too Old, No Replies

PHP Dependant list boxes how? All i find is ASP!

         

slimnutty5000

11:58 pm on Jan 17, 2007 (gmt 0)

10+ Year Member



HI,
I desperately need to figure this out. I am trying to create Dynamic Dependant list boxes that will use:
BRAND > MODEL > Output results in HTML Table.
1. I want the first box to be static and manually updated by me(its only about 8 items), but when one of those (brands) selected,
2. to filter the 2nd box dynamically from my database to show only the models of the selected brand.
3. When the model selected,(either onClick or on Submit button), to place the appropriate results into a table that i have made according to that specific model selected.

A major plus would also be able to have the 2nd box hidden and to become visible after the Brand is selected, and the same with the last step, to have my table hidden until the submit button is clicked. (This is optional, would love it, but if without this function is perfectly fine)

I have found a good tutorial on this at adobe site, but it uses ASP VB and Javascript. I am so close, but cant convert the ASP to PHP to get it to work.

Any help please? THANKS

eelixduppy

4:28 am on Jan 18, 2007 (gmt 0)



Well, you are going to have to use JavaScript for this solution (unless you want to refresh the page), but more specifically you are going to need an AJAX solution. There are tons of tutorials online for ajax and php.

Rasmus' 30 second AJAX Tutorial [news.php.net] is of course very nicely written and proves a great explanation of the basics. Familiarize yourself with this and you will be set to get started.

Another great reference: The HttpRequest Object [w3schools.com].

If you need further help with the PHP aspect then feel free to respond. You'd get better assistance with the Ajax part of it if you asked those questions in the Ajax and Javascript forum. :)

Best of luck!

cameraman

8:09 am on Jan 18, 2007 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



If you don't mind the refresh, something like this would work:

<?php
$static_models = array("apple","pear","grape");

// would come from your database table
$rows['apple'] = array("washington","granny");
$rows['pear'] = array("common","sand");
$rows['grape'] = array("concord","white","seedless");

$pbrand = '';
$pmodel = '';

// Specifically for this example this is overkill but always validate your form data
if(isset($_POST['brand']))
if(in_array($_POST['brand'],$static_models))
$pbrand = $_POST['brand'];

if(isset($_POST['Submit']))
if(in_array($_POST['model'],$rows[$pbrand]))
$pmodel = $_POST['model'];
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
<title>Dynamic select</title>
<style type="text/css">
<!--
#output { border: solid navy 1px; margin-top:10px;}
#output th { border-bottom: solid navy 1px;padding-left:5px; padding-right:5px; }
#output th+th,#output td+td { border-left: solid navy 1px; }
-->
</style>
</head>
<body>
<form action="<?php echo $_SERVER['PHP_SELF'];?>" method="post">
<select name="brand" onchange="form.submit();">
<option value="">Select</option>
<?php // I dumped them dynamically for brevity
foreach($static_models as $brandname) {
echo " <option value=\"$brandname\"";
if($brandname == $pbrand)
echo " selected=\"selected\"";
echo ">$brandname</option>\n";
}// EndForEach brand
?>
</select>
<?php // Model select appears once brand is selected
if(isset($_POST['brand'])) {?>
<select name="model">
<option value="">Select</option>
<?php // Populate by selected brand
foreach($rows[$pbrand] as $model) {
echo " <option value=\"$model\"";
if($model == $pmodel)
echo " selected=\"selected\"";
echo ">$model</option>\n";
}// EndForEach model
?>
</select>
<input type="submit" name="Submit" value="Submit" />
<?php }?>
</form>
<?php // Appears once model is selected
if(isset($_POST['Submit'])) {?>
<table id="output" cellspacing="0">
<tr>
<th>Brand</th>
<th>Model</th>
</tr>
<tr>
<td><?php echo $pbrand;?></td>
<td><?php echo $pmodel;?></td>
</tr>
</table>
<?php }?>
</body>
</html>

henry0

12:09 pm on Jan 18, 2007 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Cameraman,
Welcome to WemasterWorld!
Out of curiosity I did a cut and paste:
It even works :)

cameraman

6:13 pm on Jan 18, 2007 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



It even works :)

Well it's bound to happen once in a while!

Thanks for the welcomes, h & e.

slimnutty5000

11:28 pm on Jan 19, 2007 (gmt 0)

10+ Year Member



Cameraman,
Ive just copy and pasted the code and it is EXACTLY WHAT I WAS LOOKING FOR! I still have yet to modify it to my needs but THANK YOU.

Will update if i have any problems

slimnutty5000

11:57 pm on Jan 19, 2007 (gmt 0)

10+ Year Member



Might need a little help with this part:

// would come from your database table
$rows['apple'] = array("washington","granny");
$rows['pear'] = array("common","sand");
$rows['grape'] = array("concord","white","seedless");

I am still a beginner with PHP. I know how to connect to database etc.. but in this part, what exactly must i do?

My Database is called "tnt_items", the table where my information is called "mt_tips". The table is built as such: (for example)

Brand ------ Model ------ Item ------ CLA ------- Bluetooth
sony xF2 06-mt CLA2 Yes
sony xF4 06-mt4 CLA4 No
Kyocera X99 06-K9 CLA1 No

So i think that kinda gets the point clear. My question is, i want the "model" field to populate according to the brand selected. So according to my table how would i write this? It looks like in your example that you have determined the array manually. OR am i missing something? Or do i need seperate tables?

Thanks

cameraman

1:19 am on Jan 20, 2007 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



I did mine that way so I could use one array name for several brands (it's an array of arrays), but you can actually make it a little simpler since you only need to deal with one brand at a time.

Let's say that you put the user's answer to brand name in variable $pbrand, and you've opened the database and its link resource is in variable $linkid.
Your query would look like this (I'm assuming your field names are exactly the same as the column headers you used):

$qry = mysql_query("SELECT Model FROM tnt_items WHERE Brand='$pbrand'",$linkid);

// collect the models:
$rows = array(); // initialize the variable, not strictly necessary but good practice
while($onemodel = mysql_fetch_row($qry)) { // We'll do this until we run out of data
// The empty brackets say 'the next element's gonna be'
// The [0] is because even though we're just getting one field, it still comes out as an array
$rows[] = $onemodel[0];
} // EndWhile getting records

At this point you will now have the equivalent of:
$rows = array("washington","granny");
and you can rejoin the program (note that it's not $rows[$pbrand] anymore):
foreach($rows as $model) {

fintan

1:55 am on Jan 20, 2007 (gmt 0)

10+ Year Member



Sorry to butt in, here what I use. It needs cleaning, I'll get around to it sometime ;) .It may be of some use

SQL PART
$rsSubCat = "SELECT c.cat_id, subcat, subcat_id, c.category FROM categories c INNER JOIN subcat sc on c.cat_id = sc.cat_id ORDER BY c.cat_id";
$subcat = new Get_MYSQL_RS(); $subcat_rslts = $subcat->MYSQL_LOOP($rsSubCat); $subcat_count = $subcat->MYSQL_COUNT($rsSubCat);

PHP FUNCTION

function build($array, $array_count, $array_display, $output=false){

// First value in $array_display should be the defining grouping key

$x = 0; // Sets a constant

while($x < $array_count){
$group_array[] = $array[$x++][$array_display[0]]; /** Begins grouping and builds the array as
$group_array */
}

$group_array_unique = array_unique($group_array);// Distinct number of array values
$group_array_count = count($group_array_unique); // Counts values in the array
$group_array_values = array_values($group_array_unique); /** Gets the values of the array also more importantly
resets the array keys */

$array_display_count = count($array_display); // Counts values in the display array

function findkey($source, $searchkey){ // Begins search function

reset($source);// Resets the array

while(list($key, $val) = each($source)) { // Breaks up the array

// if(strstr($searchkey, $val)){ // Searches the array for a given value (strstr is faster)
if(!(strcmp($searchkey, $val))){ // Searches the array for a given value
$newindex[] = $key; // builds a new array
}
}
return $newindex;
}

for($i = 0; $i < $group_array_count ; $i++){ // Gathers all the keys from the original array

$find = findkey($group_array, $group_array_values[$i]); // Begins the search for the array keys
$find_count = count($find); // Counts grouping key

for($z = 0; $z <= $find_count; $z++){ // Finnally the finished result

for($y = 0; $y < $array_display_count; $y++) { // Dynamically builds varibles

// $var becomes $array_display_v0
$var = 'array_display_v'.$y; // Dynamically builds varibles
// Short hand source array[array key][sub array key]
${$var} = $array[$find[$z]][$array_display[$y]];
// Short hand
}

if($z == 0 && $i == 0){
$js_array = "depend_dd[\"$array_display_v0\"]=";
}
elseif($i > 0 && $z == 0){
$js_array .= "depend_dd[\"$array_display_v0\"]=";
}

if(!empty($array_display_v2) && $z == 0){
$js_array .= '[';
}
if(!empty($array_display_v2)){
$js_array .= '"'.$array_display_v2.' '.$array_display_v3.'¦'.$array_display_v1.'"';
if($z < $find_count-1){
$js_array .= ",";
}
}
if(empty($array_display_v2) && $z <> 0){ // fixes ]] error
$js_array .= "]\n";
}
}
}
return $js_array;
}

JAVASCRIPT PART

var depend_dd = new Array();
depend_dd["0"]=["then Select Sub-Category¦0"];
<?= build($subcat_rslts, $subcat_count, $selection = array('cat_id', 'subcat_id', 'subcat');?>

function updateDroplist(MainSelectedIndex){

document.getElementById('SubCat').length=0;

var list = depend_dd[MainSelectedIndex];

document.getElementById('SubCat').options[document.getElementById('SubCat').options.length]=new Option("then Select Sub-Category","0");

for (var i=0; i<list.length; i++){
document.getElementById('SubCat').options[document.getElementById('SubCat').options.length]=new Option(list[i].split("¦")[0], list[i].split("¦")[1]);
}
}

HTML PART

<select name="Category" id="Category" onchange="updateDroplist(this.options[this.options.selectedIndex].value);">

Hope this helps

henry0

12:10 pm on Jan 20, 2007 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



slimnutty5000 here are two ways to get data from your DB

<?
// Above is your DB conn script
// Simple query
$query = "SELECT id, username FROM your_table";
$result = mysql_query($query) or die(mysql_error()); // rem SQl error when going live
echo "<table border='1'>";
echo "<tr><th>id</th><th>Code</th></tr>";
while($row = mysql_fetch_array($result)){
echo "<tr><td>";
echo $row['id'];
echo "</td><td>";
echo $row['username'];
echo "</td></tr>";
}
echo "</table>";
?>

<?
// Above is your DB conn script
error_reporting (E_ALL); // turn it off when going live
$sql ="select username from auth_assess where password = '$password' ";
$result = mysql_query($sql,$conn);
$num=mysql_numrows($result);
mysql_close();
$i=0;
while ($i <$num)
{
$username= mysql_result($result,$i,"username");
++$i;
} // of course you may select more items from your DB and generate more results from the while loop
?>

Also in our library we have a few very good threads/tutorial on how getting data/information from a database

slimnutty5000

4:11 pm on Jan 22, 2007 (gmt 0)

10+ Year Member



Thanks for the help everyone, but i think im going to stick with you cameraman, your's seems the easiest to follow.

I used the code you gave me but now im getting this error:
"Warning: mysql_fetch_row(): supplied argument is not a valid MySQL result resource in /data/../htdocs/tip_test.php on line 9"

This is how i have the first part setup, where the error is coming from (line 9 would be the "while" function):
<?
require_once('Connections/mysql.php');
$static_models = array("audiovox","ipod","kyocera","lg","motorola","nextel","nokia","samsung","sanyo","siemens","sony","treo");

$qry = mysql_query("SELECT model FROM tnt_items WHERE brand='$pbrand,$linkid'");

// collect the models:
$rows = array(); // initialize the variable, not strictly necessary but good practice
while($onemodel = mysql_fetch_row($qry)) { // We'll do this until we run out of data
// The empty brackets say 'the next element's gonna be'
// The [0] is because even though we're just getting one field, it still comes out as an array
$rows[] = $onemodel[0];
} // EndWhile getting records

$pbrand = '';
$pmodel = '';

cameraman

7:05 pm on Jan 22, 2007 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



There's an error in this line:
$qry = mysql_query("SELECT model FROM tnt_items WHERE brand='$pbrand,$linkid'");

Move that single quote on the right side of $linkid to the right side of $pbrand:
$qry = mysql_query("SELECT model FROM tnt_items WHERE brand='$pbrand',$linkid");

Do you open the database connection in that include file? $linkid should be the resource identifier that is returned from the open (a lot of people use $conn or $connection).

slimnutty5000

8:21 pm on Jan 22, 2007 (gmt 0)

10+ Year Member



I fixed the quote problem, and i changed the $linkid to $mysql, which is what I used to connect to the DB. I think the database connection seems to be fine. IT keeps giving me the error for this string:

while($onemodel = mysql_fetch_row($qry)) {

Says the mysql_fetch_row is not a valid result resource.

What do you suggest?

eelixduppy

8:30 pm on Jan 22, 2007 (gmt 0)



The error exists because your query isn't working correctly. You have an extra quote, too:

$qry = mysql_query("SELECT model FROM tnt_items WHERE brand='$pbrand'",$mysql) or die(mysql_error());

I fixed the quote problem and added error reporting, so you can tell what went wrong with the query.

Good luck! :)

slimnutty5000

9:43 pm on Jan 22, 2007 (gmt 0)

10+ Year Member



I get a "No database selected" error. Is Opening a database different from Connecting to the DB?

eelixduppy

10:01 pm on Jan 22, 2007 (gmt 0)



Yes it is ;) You must select the database after you open up the connection:

[url=http://us3.php.net/mysql-select-db]mysql_select_db[/url]("db_name");

slimnutty5000

11:50 pm on Jan 22, 2007 (gmt 0)

10+ Year Member



Ok thanks, got the DB connected and opened up now. Now i get no errors, but my second field does not populate with the items from the database. Everything else seems to be in order. I dont know what to do next.

jatar_k

1:35 pm on Jan 23, 2007 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



do you mean the second field value is never displayed or that the first row displays and nothing else

maybe show us what code you have now

slimnutty5000

3:06 pm on Jan 23, 2007 (gmt 0)

10+ Year Member



Yeah, the second feild value is never displayed after selecting the brand. The functionality seems to be working perfect, field 1 shows, then after click field 2 shows, but just says "Select", then after clicking submit, the table shows, but it gives this warning:

"Warning: in_array() [function.in-array]: Wrong datatype for second argument in /data/../htdocs/tip_test.php on line 25"

Heres my code as it is now:

<?php
require_once('Connections/mysql.php');
mysql_select_db("tnt_items");
$static_models = array("audiovox","ipod","kyocera","lg","motorola","nextel","nokia","samsung","sanyo","siemens","sony","treo");

$qry = mysql_query("SELECT model FROM mt_tips WHERE brand='$pbrand'",$mysql) or die(mysql_error());

// collect the models:
$rows = array(); // initialize the variable, not strictly necessary but good practice
while($onemodel = mysql_fetch_row($qry)) { // We'll do this until we run out of data
// The empty brackets say 'the next element's gonna be'
// The [0] is because even though we're just getting one field, it still comes out as an array
$rows[] = $onemodel[0];
} // EndWhile getting records

$pbrand = '';
$pmodel = '';

// Specifically for this example this is overkill but always validate your form data
if(isset($_POST['brand']))
if(in_array($_POST['brand'],$static_models))
$pbrand = $_POST['brand'];

if(isset($_POST['Submit']))
if(in_array($_POST['model'],$rows[$pbrand]))
$pmodel = $_POST['model'];
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
<title>Dynamic select</title>
<style type="text/css">
<!--
#output { border: solid navy 1px; margin-top:10px;}
#output th { border-bottom: solid navy 1px;padding-left:5px; padding-right:5px; }
#output th+th,#output td+td { border-left: solid navy 1px; }
-->
</style>
</head>
<body>
<form action="<?php echo $_SERVER['PHP_SELF'];?>" method="post">
<select name="brand" onchange="form.submit();">
<option value="">Select</option>
<?php // I dumped them dynamically for brevity
foreach($static_models as $brandname) {
echo " <option value=\"$brandname\"";
if($brandname == $pbrand)
echo " selected=\"selected\"";
echo ">$brandname</option>\n";
}// EndForEach brand
?>
</select>
<?php // Model select appears once brand is selected
if(isset($_POST['brand'])) {?>
<select name="model">
<option value="">Select</option>
<?php // Populate by selected brand
foreach($rows as $model) {
echo " <option value=\"$model\"";
if($model == $pmodel)
echo " selected=\"selected\"";
echo ">$model</option>\n";
}// EndForEach model
?>
</select>
<input type="submit" name="Submit" value="Submit" />
<?php }?>
</form>
<?php // Appears once model is selected
if(isset($_POST['Submit'])) {?>
<table id="output" cellspacing="0">
<tr>
<th>Brand</th>
<th>Model</th>
</tr>
<tr>
<td><?php echo $pbrand;?></td>
<td><?php echo $pmodel;?></td>
</tr>
</table>
<?php }?>
</body>
</html>

jatar_k

3:12 pm on Jan 23, 2007 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



the only slect I see is this one

SELECT model FROM mt_tips WHERE brand='$pbrand'

if that is the same one you are using then you will need to add the other column into the query

you will then need to change the way you put it into the array here

$rows[] = $onemodel[0];

because you will now have 2 columns of data

I may be way off base but I think that's right, I haven't read the whole thread in detail

slimnutty5000

9:01 pm on Jan 23, 2007 (gmt 0)

10+ Year Member



I still dont have a resolution to this problem....

Any help? I am kinda stuck.

jatar_k

11:23 pm on Jan 23, 2007 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



is there another select than the one I mentioned?

slimnutty5000

11:27 pm on Jan 23, 2007 (gmt 0)

10+ Year Member



no, there isnt, should there be?

cameraman

5:53 am on Jan 24, 2007 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Remember how $rows was an array of arrays, when it was
$rows['apple'] = array(...)
$rows['pear'] = array(...)

Now that it's simplified it to only refer to one brand at a time, it's not an array of arrays anymore, it's just an array.

So in this section, just before the doctype:
if(isset($_POST['Submit']))
if(in_array($_POST['model'],$rows[$pbrand]))
$pmodel = $_POST['model'];

$rows[$pbrand] isn't an array anymore, it's an element of an array. Try changing the line to:
if(in_array($_POST['model'],$rows))

henry0

12:57 pm on Jan 24, 2007 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



cameraman is ref to what was in his example
multidimensional array
Please look AT THAT [us3.php.net]

slimnutty5000

4:59 pm on Jan 24, 2007 (gmt 0)

10+ Year Member



Thanks Cameraman, that fixed the error page on submit. But i still am not getting any data to populate the 2nd field(models).

cameraman

7:19 pm on Jan 24, 2007 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Where you've got the query, $pbrand hasn't been assigned yet. Rearrange the query stuff so it's further down:

// Move it to below this section:
if(isset($_POST['Submit']))
if(in_array($_POST['model'],$rows[$pbrand]))
$pmodel = $_POST['model'];

$qry = mysql_query("SELECT model FROM mt_tips WHERE brand='$pbrand'",$mysql) or die(mysql_error());

// collect the models:
$rows = array(); // initialize the variable, not strictly necessary but good practice
while($onemodel = mysql_fetch_row($qry)) { // We'll do this until we run out of data
// The empty brackets say 'the next element's gonna be'
// The [0] is because even though we're just getting one field, it still comes out as an array
$rows[] = $onemodel[0];
} // EndWhile getting records

slimnutty5000

8:39 pm on Jan 24, 2007 (gmt 0)

10+ Year Member



FINALLY! I am getting somewhere! Thank you so much. I had to play around with the positioning of the code, but now i understand that the ordering really does matter in PHP. This is how i had to order the final code to get it to work without any errors:

<?php
require_once('Connections/mysql.php');
mysql_select_db("tnt_items");
$static_models = array("audiovox","ipod","kyocera","lg","motorola","nextel","nokia","samsung","sanyo","siemens","sony","treo");
$rows = array(); // initialize the variable, not strictly necessary but good practice
$pbrand = '';
$pmodel = '';

// Specifically for this example this is overkill but always validate your form data
if(isset($_POST['brand']))
if(in_array($_POST['brand'],$static_models))
$pbrand = $_POST['brand'];

$qry = mysql_query("SELECT model FROM mt_tips WHERE brand='$pbrand'",$mysql) or die(mysql_error());

// collect the models:
$rows = array(); // initialize the variable, not strictly necessary but good practice
while($onemodel = mysql_fetch_row($qry)) { // We'll do this until we run out of data
// The empty brackets say 'the next element's gonna be'
// The [0] is because even though we're just getting one field, it still comes out as an array
$rows[] = $onemodel[0];
} // EndWhile getting records

if(isset($_POST['Submit']))
if(in_array($_POST['model'],$rows))
$pmodel = $_POST['model'];
?>

jatar_k

3:32 am on Jan 25, 2007 (gmt 0)