Cascading Dropdown Boxes - php

I have used various script and attempted to modify them to suit my database, but this is what I want to Achieve
MySQL Database, single table "Carlist"
I want to put together a form where the user will select a "Make" from the database, this will then filter the 2nd Dropdown box for "Model" where then the third dropdown box will filter out the different variants of that particular model.
MY Database has the fields Make, Model and Version
Box 1: SELECT DISTINCT Make FROM Carlist SORT BY Make
Box 2: SELECT Distinct Model FROM Carlist WHERE Make=$Make SORT BY Model
Box 3: SELECT DISTINCT Version FROM Carlist WHERE Make=$Make AND Model=$Model SORT BY Version
I would also like to put in a mechanism where the 2nd and third boxes could not be selected until the previous box had been
All the scripts I have come across utilise more than one table in the database, at the moment my database has over 1500 records.
If anyone has any useful links or advice on this that would be great, as mentioned I have tried to modify other peoples scripts without success, but those scripts were designed for multiple tables

Assuming that you're trying to fill an HTML form, use Ajax to get the appropriate drop box values from the database after each selection.

Got a solution, code is as follows:
<?php
/* Written for Khaoskreations 2010-06-13 */
//db connect code
require "config.php"; // Your Database details
$query = "SELECT * FROM Carlist ";
$result = mysql_query($query);
//==============================================================================build arrays from db
$Make = array();
$Model = array();
$Version = array();
if (!$result) echo "Error: ".mysql_error();
else {
$Make_group = "";
$Model_group = "";
$num = mysql_num_rows($result);
for ($i = 0;$i<$num;$i++) {
$r = mysql_fetch_array($result);
if ($r['Make'] != $Make_group) {
$Make[$r['Make']] = $r['Make'];
$Model[$r['Make']][$r['Model']] = $r['Model'];
$Version[$r['Make']][$r['Model']][$r['Version']] = $r['Version'];
$Make_group = $r['Make'];
$Model_group = $r['Make'];
} else if ($r['Model'] != $Model_group) {
$Model[$r['Make']][$r['Model']] = $r['Model'];
$Version[$r['Make']][$r['Model']][$r['Version']] = $r['Version'];
$Model_group = $r['Make'];
} else {
$Version[$r['Make']][$r['Model']][$r['Version']] = $r['Version'];
}
}
}
//==============================================================================create scripts
$script = "\n<script type='text/javascript'>\n";
//build last name array
$script .= "var Make = new Array(";
$list = "";
foreach ($Make as $key => $val) {
$list .= " \"".$val."\",";
//echo $val ."<br />";
}
$list = substr($list, 0, -1);
$list .= " );\n";
$script .= $list;
$list = "";
//build Model array
$script .= "\nvar Model = new Array();";
foreach ($Model as $Maken => $fary) {
$list .= "\nModel[\"".$Maken."\"] = new Array(";
foreach ($fary as $key => $value) {
$list .= " \"". $value . "\",";
}
$list = substr($list, 0, -1);
$list .= " );";
}
$script .= $list;
$list = "";
//build Version array
$list = "\nvar Version = new Array();";
foreach ($Version as $Maken => $fary) {
$list .= "\nVersion[\"".$Maken."\"] = new Array();";
foreach ($fary as $Modeln => $aary) {
$list .= "\nVersion[\"".$Maken."\"][\"".$Modeln."\"] = new Array(";
foreach ($aary as $key => $value) {
$list .= " \"" . $value . "\",";
}
$list = substr($list, 0, -1);
$list .= " );";
}
}
$script .= $list;
//script functions to update tiers
$script .= <<< EOSCRIPT
function resetForm(theForm) {
theForm.Makes.options[0] = new Option("--- Select Make ---", "");
for (var i=0; i<Make.length; i++) {
theForm.Makes.options[i+1] = new Option(Make[i], Make[i]);
}
theForm.Makes.options[0].selected = true;
theForm.Models.options[0] = new Option("--- Select Model ---", "");
theForm.Models.options[0].selected = true;
theForm.Version.options[0] = new Option("--- Select Version ---", "");
theForm.Version.options[0].selected = true;
document.getElementById("selectbox").innerHTML = "";
}
function reloadForm(theForm,Manufacturer,product,specific) {
theForm.Makes.options[0] = new Option("--- Select Version ---", "");
for (var i=0; i<Make.length; i++) {
theForm.Makes.options[i+1] = new Option(Make[i], Make[i]);
if (Manufacturer == Make[i]) theForm.Makes.options[i+1].selected = true;
}
document.getElementById("selectbox").innerHTML = "here";
var fn = Model[Manufacturer];
theForm.Models.options.length = 0;
for (var i=0; i<fn.length; i++) {
theForm.Models.options[i] = new Option(fn[i], fn[i]);
if (product == fn[i]) {
theForm.Models.options[i].selected = true;
}
}
var Versions = Version[Manufacturer][product];
theForm.Version.options.length = 0;
for (var i=0; i<Versions.length; i++) {
theForm.Version.options[i] = new Option(Versions[i], Versions[i]);
if (specific == Versions[i][0]) {
theForm.Version.options[i].selected = true;
}
}
document.getElementById("selectbox").innerHTML = "You selected person #"+specific;
}
function updateproducts(theForm) {
var lname = theForm.Makes.options[theForm.Makes.options.selectedIndex].value;
var fnames = Model[lname];
theForm.Models.options.length = 0;
for (var i=0; i<fnames.length; i++) {
theForm.Models.options[i] = new Option(fnames[i], fnames[i]);
}
var findex = theForm.Models.options[theForm.Models.options.selectedIndex].value;
var Versions = Version[lname][findex];
theForm.Version.options.length = 0;
for (var i=0; i<Versions.length; i++) {
theForm.Version.options[i] = new Option(Versions[i], Versions[i]);
}
theForm.Version.options[0].selected = true;
}
function updateVersion(theForm) {
var lname = theForm.Makes.options[theForm.Makes.options.selectedIndex].value;
var findex = theForm.Models.options[theForm.Models.options.selectedIndex].value;
var Versions = Version[lname][findex];
theForm.Version.options.length = 0;
for (var i=0; i<Versions.length; i++) {
theForm.Version.options[i] = new Option(Versions[i], Versions[i]);
}
theForm.Version.options[0].selected = true;
}
</script>
EOSCRIPT;
$reload_script = "";
if ($_POST['Makes'] != "" && $_POST['Models'] != "") {
$reload_script .= "<script type='text/javascript'> "
."reloadForm(document.vehicleform,'".$_POST['Makes']."','".$_POST['Models']."',".$_POST['Version'].");"
."</script>";
} else {
$reload_script .= "<script type='text/javascript'>"
."resetForm(document.vehicleform);"
."</script>";
}
//============================================================================== build page
$page = <<< EOPAGE
<html>
<head>
{$script}
</head>
<body>
<form method="post" action="test3.php" name='vehicleform'>
<select name='Makes' onchange="updateproducts(this.form)"></select><BR>
<select name="Models" onchange="updateVersion(this.form)"></select><BR>
<select name="Version"></select>
<input type='button' value='Reset' onclick='resetForm(document.vehicleform)'/>
<input type='submit' value='Reload'/>
</form>
<div id='selectbox'></div>
{$reload_script}
</body>
</html>
EOPAGE;
echo $page;
?>

Related

unable to insert multiple array data from dynamic generated field?

I am unable to enter multiple data, it enter only single data. I have tried using for loop and then entering data, using 3 user and 2 task, there is an error previously offset.
public function add($postData)
{
// dd($postData);
$c = count($postData['user_name']);
$t = count($postData['task_name']);
for ($i = 0; $i < $c; $i++) {
$user_name = $postData['user_name'][$i];
$user_email = $postData['user_email'][$i];
$data['insert']['user_name'] = $user_name;
$data['insert']['user_email'] = $user_email;
}
for ($j = 0; $j < $t; $j++) {
$task_name = $postData['task_name'][$j];
$data['insert']['task_name'] = $task_name;
}
$data['insert']['name'] = $postData['name'];
$data['insert']['description'] = $postData['description'];
$data['insert']['customer_name'] = $postData['customer_name'];
$data['insert']['billing_method'] = $postData['billing_method'];
$data['insert']['dt_created'] = DT;
$data['table'] = PROJECT;
$result = $this->insertRecord($data);
if ($result == true) {
$response['status'] = 'success';
$response['message'] = 'Project created';
} else {
$response['status'] = 'danger';
$response['message'] = DEFAULT_MESSAGE;
}
return $response;
}
As Per lack of question details attached, I am supposing that you want to insert multiple task entry with project name, description etc.
Here is updated code:
<?php
// dd($postData);
$username = $postData['username'];
$user_email = $postData['user_email'];
$task_name = $postData['task_name'];
foreach ($username as $key => $value) {
$data['insert']['name'] = $postData['name'];
$data['insert']['description'] = $postData['description'];
$data['insert']['customer_name'] = $postData['customer_name'];
$data['insert']['billing_method'] = $postData['billing_method'];
$data['insert']['username'] = $value;
$data['insert']['user_email'] = $user_email[$key];
$data['insert']['task_name'] = $task_name[$key];
$data['insert']['dt_created'] = DT;
$data['table'] = PROJECT;
$result = $this->insertRecord($data);
}

Flash Database Operation Failed

I have a problem with my Flash (.fla) project. I've connected my flash with database with php script. I used ActionScript 2.0.
The problem is data can show at compile program on AdobeFlash CS6 (CTRL+Enter) but data cant show in datagrid when I open the .swf.
It's my php script
<?php
mysql_pconnect ("localhost", "root", "");
mysql_select_db ("modul");
$qr = mysql_query("SELECT * from nilaisiswa");
if (!qr || mysql_num_rows($qr)==0) {
$r_string = '&errorcode=3&msg='.mysql_error().'&';
} else {
$r_string = '&errorcode=0&n='.mysql_num_rows ($qr);
$i = 0;
while ($row = mysql_fetch_assoc ($qr)) {
while (list ($key, $val) = each ($row)) {
$r_string .= '&' . $key . $i . '=' . stripslashes($val);
}
$i++;
}
$r_string .='&';
}
echo $r_string;
?>
And here it's my ActionScript 2.0
var select_lv:LoadVars = new LoadVars();
var insert_lv:LoadVars = new LoadVars();
var delete_lv:LoadVars = new LoadVars();
var today:Date = new Date();
var deleteIndex:Number;
var errorMsgs:Array = [
"",
"Couldn't connect to server",
"Couldn't connect to database",
"Error running query",
"First four entries may not be deleted"];
var filepath:String;
var scoreInfo:Array = [];
var headerListener:Object = {};
headerListener.headerRelease = function(event:Object) {
switch (event.columnIndex) {
case 0:
if (scores_dg.getColumnAt(0).sortedUp) {
scores_dg.sortItemsBy(scores_dg.columnNames[0], Array.CASEINSENSITIVE | Array.DESCENDING);
} else {
scores_dg.sortItemsBy(scores_dg.columnNames[0], Array.CASEINSENSITIVE);
}
scores_dg.getColumnAt(0).sortedUp = !scores_dg.getColumnAt(0).sortedUp;
break;
case 1:
if (scores_dg.getColumnAt(1).sortedUp) {
scores_dg.sortItemsBy(scores_dg.columnNames[1], Array.NUMERIC | Array.DESCENDING);
} else {
scores_dg.sortItemsBy(scores_dg.columnNames[1], Array.NUMERIC);
}
scores_dg.getColumnAt(1).sortedUp = !scores_dg.getColumnAt(1).sortedUp;
break;
}
}
function zerofill(n:Number):String {
if (n<10) return '0' + n.toString();
else return n.toString();
}
filepath = "http://localhost/tesis/";
nickname_ti.maxChars = 50;
date_ti.maxChars = 10;
score_ti.text = 0;
date_ti.text = today.getDate() + '-' + zerofill(today.getMonth()+1) + '-' + zerofill(today.getFullYear());
select_lv.onLoad = function(ok:Boolean) {
if (ok) {
if (this.errorcode=="0") {
for (var i:Number=0; i < this.n; i++) {
scoreInfo.push(
{record:this["id"+i],
nickname:this["nickname"+i],
score:Number(this["score"+i]),
dateposted:this["dateposted"+i]
});
}
scores_dg.columnNames = ["nickname", "score", "dateposted"];
scores_dg.getColumnAt(0).width = 130;
scores_dg.getColumnAt(0).sortOnHeaderRelease = false;
scores_dg.getColumnAt(0).sortedUp = false;
scores_dg.getColumnAt(0).headerText = "Nickname";
scores_dg.getColumnAt(1).width = 130;
scores_dg.getColumnAt(1).sortOnHeaderRelease = false;
scores_dg.getColumnAt(1).sortedUp = false;
scores_dg.getColumnAt(1).headerText = "Score";
scores_dg.getColumnAt(2).width = 130;
scores_dg.getColumnAt(2).headerText = "Date Posted";
scores_dg.dataProvider = scoreInfo;
scores_dg.addEventListener("headerRelease", headerListener);
msg_ta.text = "Enter data and click Add to add a score.";
} else {
msg_ta.text = errorMsgs[Number(this.errorcode)];
if (this.errorcode == "3") msg_ta.text += ": " + this.msg;
}
} else {
msg_ta.text = "Flash-database select operation failed";
}
}
msg_ta.text = "Getting high scores from database...";
select_lv.sendAndLoad(filepath + "getscores.php", select_lv, "GET");

search every word in string with mysql and php

I need to search every word of an string in the database. If an word exist it needs to be highlighted. The current script works, but needs a lot of memory for my server. I don't know how i make it easier, but maybe do you?
<?php
$total_messages = $_POST['total'] - 1;
for($x = 0; $x <= $total_messages; $x++)
{
//Search highlights
$result = $mysqli->query("SELECT * FROM highlights WHERE enabled=1")
while($row = $result->fetch_assoc())
{
//Vars for highlights
$highlight_txt = $row['value'];
$highlight_type = $row['type'];
$highlight_color = "black";
$highlight_title = null;
//If the text isnt empty
if($highlight_txt != null || $highlight_txt != "")
{
//Type highlights
if($highlight_type == "tree") //Tree type
{
$highlight_type = "18"; //Category number
$highlight_background = "pink"; //Background
if($row['option1'] != null)
{
$highlight_title = htmlentities($row['option1']);
}
}
else
{
$highlight_background = "yellow"; //Background
}
//Add highlight
$message = preg_replace("/\b($highlight_txt)\b/i", "<span class='bc_highlight' highlight-type='$highlight_type' highlight-value='$highlight_txt' style='background: $highlight_background; color: $highlight_color;' title=''>$highlight_txt</span>", $message);
}
}
echo $message; //Display the message
}
Why not doing something like this?
$messages = ["This is my message1","This is my message2"];
$highlights = [];
$result = $mysqli->query("SELECT * FROM highlights WHERE enabled=1")
while($row = $result->fetch_assoc()) {
$highlights[$row["value"]] = [
"type" => $row["type"],
"color" => $row["color"]
];
}
$callback = function($matches) use ($highlights) {
$word = $matches[1];
if(isset($highlights[$word])) {
$highlight = $highlights[$word];
return sprintf('<span style="color:%s">%s</span>',$highlight["color"],$word);
} else {
return $word;
}
};
foreach($messages as &$message) {
$message = preg_replace_callback("/(\w+)/i",$message,$callback);
}

get data from mysql with multiple value

I have some data in url
sub_cat.php?s=1&os=3,1&brand=10,9&camera=19&storage=15,13&data=17
I have:
operating systems with id 3 and 1
brands with id 10 and 9
camera with id 19
storage with id 15 and 13
data with id 17
i want to show mobiles having these specifications from sql database
if (isset($_GET['brand'])) {
$sf_brand = $_GET['brand'];
$brand_split = explode(',', $sf_brand);
$sf_brand_len = count($brand_split);
for ($ab=0; $ab < $sf_brand_len; $ab++) {
$append_sf_brand .= 'OR product.product_brand LIKE \''.$brand_split[$ab].'\' ';
}
$append_sf_brand_f = '('.substr($append_sf_brand, 3).')';
}else{
$append_sf_brand_f = '';
}
if (isset($_GET['os'])) {
$sf_os = $_GET['os'];
$os_split = explode(',', $sf_os);
$sf_os_len = count($os_split);
for ($ao=0; $ao < $sf_os_len; $ao++) {
$append_sf_os .= 'OR productspec.prospec_expspec_id LIKE \''.$os_split[$ao].'\' ';
}
$append_sf_os_f = '('.substr($append_sf_os, 3).')';
}else{
$append_sf_os_f = '';
}
if (isset($_GET['camera'])) {
$sf_camera = $_GET['camera'];
$camera_split = explode(',', $sf_camera);
$sf_camera_len = count($camera_split);
for ($ac=0; $ac < $sf_camera_len; $ac++) {
$append_sf_camera .= 'OR productspec.prospec_expspec_id LIKE \''.$camera_split[$ac].'\' ';
}
$append_sf_camera_f = '('.substr($append_sf_camera, 3).')';
}else{
$append_sf_camera_f = '';
}
if (isset($_GET['data'])) {
$sf_data = $_GET['data'];
$data_split = explode(',', $sf_data);
$sf_data_len = count($data_split);
for ($ad=0; $ad < $sf_data_len; $ad++) {
$append_sf_data .= 'OR productspec.prospec_expspec_id LIKE \''.$data_split[$ad].'\' ';
}
$append_sf_data_f = '('.substr($append_sf_data, 3).')';
}else{
$append_sf_data_f = '';
}
if (isset($_GET['storage'])) {
$sf_storage = $_GET['storage'];
$storage_split = explode(',', $sf_storage);
$sf_storage_len = count($storage_split);
for ($as=0; $as < $sf_storage_len; $as++) {
$append_sf_storage .= 'OR productspec.prospec_expspec_id LIKE \''.$storage_split[$as].'\' ';
}
$append_sf_storage_f = '('.substr($append_sf_storage, 3).')';
}else{
$append_sf_storage_f = '';
}
$sf_condition = '(product.product_id LIKE productspec.prospec_product_id) AND '.$append_sf_brand_f.' AND '.$append_sf_os_f.' AND '.$append_sf_camera_f.' AND '.$append_sf_data_f.' AND '.$append_sf_storage_f;
I have query:
$get_brand_query = mysqli_query($connect, "SELECT * FROM product, productspec WHERE $sf_condition");
But it is not working well, so how I can show mobiles can anyone help me thanks.

Previous/next button in PHP

I´m pretty much entirely new to PHP, so please bear with me.
I´m trying to build a website running on a cms called Core. I'm trying to make it so that the previous/next buttons cycle through tags rather than entries. Tags are stored in a database as core_tags. Each tag has it own tag_id, which is a number. I've tried changing the excisting code for thep previous/next buttons, but it keeps giving me 'Warning: mysql_fetch_array() expects parameter 1 to be resource, null given in /home/core/functions/get_entry.php on line 50'.'
Any help would be greatly appreciated.
Get_entry.php:
<?php
$b = $_SERVER['REQUEST_URI'];
if($entry) {
$b = substr($b,0,strrpos($b,"/")) . "/core/";
$id = $entry;
$isPerma = true;
} else {
$b = substr($b,0,mb_strrpos($b,"/core/")+6);
$id = $_REQUEST["id"];
}
$root = $_SERVER['DOCUMENT_ROOT'] . $b;
$http = "http://" . $_SERVER['HTTP_HOST'] . substr($b,0,strlen($b)-5);
require_once($root . "user/configuration.php");
require_once($root . "themes/".$theme."/configuration.php");
require_once($root . "functions/session.php");
if(is_numeric($id)) {
$type = "entry";
} else {
$type = "page";
}
$id = secure($id);
if($type == "page") {
$data = mysql_query("SELECT p.* FROM core_pages p WHERE p.page_title = \"$id\"");
$page_clicks = 0;
while($p = mysql_fetch_array($data)) {
$url = $p["page_url"];
$path = $root . "user/pages/" . $url;
$page_clicks = $p['hits']+1;
require($path);
}
mysql_query("UPDATE core_pages p SET
p.hits = $page_clicks
WHERE p.page_title = $id");
}
if($type == "entry") {
// queries the dbase
$data_tags = mysql_query("SELECT entry_id,entry_title FROM core_entries WHERE entry_show = 1 ORDER BY entry_position DESC") or die(mysql_error());
$navArr=array();
while($tmparray = mysql_fetch_array($data_entries,MYSQL_ASSOC)){
array_push($navArr,$tmparray['entry_id']);
}
function array_next_previous($array, $value) {
$index = array_search($value,$array);
//if user clicked to view the very first entry
if($value == reset($array)){
$return['prev'] = end($array);
$return['next'] = $array[$index + 1];
//if user clicked to view the very last entry
}else if($value == end($array)){
$return['prev'] = $array[$index - 1];
reset($array);
$return['next'] = current($array);
}else{
$return['next'] = $array[$index + 1];
$return['prev'] = $array[$index - 1];
}
return $return;
}
$data = mysql_query("SELECT e.* FROM core_entries e WHERE e.entry_id = $id AND e.entry_show = 1");
$entry_clicks = 0;
if(#mysql_num_rows($data) < 1) {
die("Invalid id, no entry to be shown");
}
while($e = mysql_fetch_array($data)) {
$nextPrevProject = array_next_previous($navArr,$id);
$entry_id = $e['entry_id'];
$entry_title = $e['entry_title'];
// DATE
$t = $e["entry_date"];
$y = substr($t,0,4);
$m = substr($t,5,2);
$d = substr($t,8,2);
$entry_date = date($date_format,mktime(0,0,0,$m,$d,$y));
$entry_text = $e['entry_text'];
$entry_extra1 = $e['entry_extra1'];
$entry_extra2 = $e['entry_extra2'];
$entry_client = $e['entry_client'];
$entry_position = $e['entry_position'];
$entry_hits = $e['hits']+1;
$entry_new = $e['entry_new'];
if($entry_new == 1) {
$isNew = true;
} else {
$isNew = false;
}
if($nice_permalinks) {
$entry_perma = "$http".$entry_id;
} else {
$entry_perma = "$http"."?entry=$entry_id";
}
$data_e2t = #mysql_query("SELECT e2t.tag_id FROM core_entry2tag e2t WHERE e2t.entry_id = $entry_id");
$tag_str = "";
while($e2t = #mysql_fetch_array($data_e2t)) {
$tag_id = $e2t["tag_id"];
$data_tags = #mysql_query("SELECT t.tag_text FROM core_tags t WHERE t.tag_id = $tag_id");
while($t = #mysql_fetch_array($data_tags)) {
$tag_text = $t["tag_text"];
$tag_str = $tag_str . "<a class=\"tag-link\" name=\"tag".$tag_id."\" href=\"#tag-"._encode($tag_text)."\">".$tag_text."</a>".$separator_tags;
}
}
$entry_tags = substr($tag_str,0,strlen($tag_str)-strlen($separator_tags));
$layout_path = $root . "user/uploads/" . treat_string($entry_title) . "/layout.php";
if(is_file($layout_path) && (#filesize($layout_path) > 0)) {
require($layout_path);
} else {
require($theme_path . "parts/entry.php");
}
}
mysql_query("UPDATE core_entries e SET
e.hits = $entry_hits
WHERE e.entry_id = $id");
}
if($isPerma) {
echo "<a class=\"index-link\" href=\"$http\">back to index</a>";
}
?>
You have not defined $data_entries, before using it here:
while($tmparray = mysql_fetch_array($data_entries,MYSQL_ASSOC)){
array_push($navArr,$tmparray['entry_id']);
}
That is why you get the very descriptive error message.
Did you mean to use $data_tags?
Use: "SELECT p.* FROM core_pages p WHERE p.page_title = '".$id."'
Note: mysql_connect is not sql-injection save. If you use mysql_connect, change to PDO.
$data_entries is not defined on line 50, then mysql_fetch_array return an exception of null value given.
Try to change $tmparray = mysql_fetch_array($data_entries,MYSQL_ASSOC) to $tmparray = mysql_fetch_array($data_tags,MYSQL_ASSOC).
Hope this help!

Categories