Forum Moderators: coopster
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
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!
<?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>
// 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
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) {
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
<?
// 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
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 = '';
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).
while($onemodel = mysql_fetch_row($qry)) {
Says the mysql_fetch_row is not a valid result resource.
What do you suggest?
$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! :)
[url=http://us3.php.net/mysql-select-db]mysql_select_db[/url]("db_name");
"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>
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
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))
// 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
<?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'];
?>