I am creating an internal web tool that inserts data into a database. I was trying to find out how to create a three-tier dropdown selection, where I would insert the third dropdown's value into the DB.
I stumbled across this answer here:
Populate another select dropdown from database based on dropdown selection
But was done as a two tier dropdown.
My php code is this:
<?php
require 'connect.php';
$query = "SELECT customer_id,customer FROM schema.customer";
$result = $DB_con->query($query);
while($row = $result->fetch(PDO::FETCH_ASSOC)){
$categories[] = array("customer_id" => $row['customer_id'], "customer" => $row['customer']);
}
$query = "SELECT contract_id, customer_id, contract FROM schema.contract";
$result = $DB_con->query($query);
while($row = $result->fetch(PDO::FETCH_ASSOC)){
$subcats[$row['customer_id']][] = array("contract_id" => $row['contract_id'], "contract" => $row['contract']);
}
// Third dropdown which isn't originally included with the previous answer
$query = "SELECT subcontract_id, contract_id, subcontract FROM schema.subcontract";
$result = $DB_con->query($query);
while($row = $result->fetch(PDO::FETCH_ASSOC)){
$subsubcats[$row['contract_id']][] = array("subcontract_id" => $row['subcontract_id'], "subcontract" => $row['subcontract']);
}
$jsonCats = json_encode($categories);
$jsonSubCats = json_encode($subcats);
$jsonSubSubCats = json_encode($subsubcats);
?>
Now, the given answer was this:
<head>
<script type='text/javascript'>
<?php
echo "var categories = $jsonCats; \n";
echo "var subcats = $jsonSubCats; \n";
//Below wasn't part of the answer
echo "var subsubcats = $jsonSubSubCats; \n";
?>
function loadCategories(){
var select = document.getElementById("categoriesSelect");
select.onchange = updateSubCats;
for(var i = 0; i < categories.length; i++){
select.options[i] = new Option(categories[i].customer,categories[i].customer_id);
}
}
function updateSubCats(){
var catSelect = this;
var customer_id = this.value;
var subcatSelect = document.getElementById("subcatsSelect");
subcatSelect.options.length = 0; //delete all options if any present
for(var i = 0; i < subcats[customer_id].length; i++){
subcatSelect.options[i] = new Option(subcats[customer_id][i].contract,subcats[customer_id][i].contract_id);
}
}
</script>
</head>
<body onload='loadCategories()'>
<select id='categoriesSelect'>
</select>
<select id='subcatsSelect'>
</select>
</body>
</html>
But I needed help with the third tier options based from the second dropdown selection. Thanks in Advance. :)
Was able to figure it out.
<script type='text/javascript'>
<?php
echo "var categories = $jsonCats; \n";
echo "var subcats = $jsonSubCats; \n";
echo "var subsubcats = $jsonSubSubCats; \n";
?>
function loadCategories(){
var select = document.getElementById("categoriesSelect");
select.onchange = updateSubCats;
for(var i = 0; i < categories.length; i++){
select.options[i] = new Option(categories[i].customer,categories[i].customer_id);
}
}
function updateSubCats(){
var customer_id = this.value;
var subcatSelect = document.getElementById("subcatsSelect")
subcatSelect.onchange = updateSubSubCats;;
for(var i = 0; i < subcats[customer_id].length; i++){
subcatSelect.options[i] = new Option(subcats[customer_id][i].contract,subcats[customer_id][i].contract_id);
}
}
function updateSubSubCats(){
var subsubcatSelect = this;
var contract_id = this.value;
var subsubcatSelect = document.getElementById("subsubcatsSelect");
subsubcatSelect.options.length = 0; //delete all options if any present
for(var i = 0; i < subsubcats[contract_id].length; i++){
subsubcatSelect.options[i] = new Option(subsubcats[contract_id][i].subcontract,subsubcats[contract_id][i].subcontract_id);
}
}
</script>
Related
I want to get the first dropdown menu to get the selected value for the selected dropbox, but I would like to to have all the categories still being in the second dropbox, so I can change the category of the article.
For example, the user chooses a article in the first dropbox, then the category that is associated with that article gets selected, but the user can change the category in the dropbox. Can this be done?
I have tried using Javascript from a previous question , but it's only getting the selected category associated with that article and not all the other categories. What should I do? Does anyone know how this can be done?
<?php $link = mysqli_connect("160.153.129.204", "username", "password", "lvo92");
$db = new mysqli("160.153.129.204", "laurensvo92", "90F0411553l", "lvo92");//set your database handler
$query = "SELECT catid, titel FROM artikelen";
$result = $db->query($query);
while($row = $result->fetch_assoc()){
$categories[] = array("catid" => $row['catid'], "val" => $row['titel']);
}
$query = "SELECT catid, cat FROM Categorie";
$result = $db->query($query);
while($row = $result->fetch_assoc()){
$subcats[$row['catid']][] = array("catid" => $row['catid'], "val" => $row['cat']);
}
$jsonCats = json_encode($categories);
$jsonSubCats = json_encode($subcats);
?>
<script type='text/javascript'>
<?php
echo "var categories = $jsonCats; \n";
echo "var subcats = $jsonSubCats; \n";
?>
function loadCategories(){
var select = document.getElementById("categoriesSelect");
select.onchange = updateSubCats;
for(var i = 0; i < categories.length; i++){
select.options[i] = new Option(categories[i].val,categories[i].catid);
}
}
function updateSubCats(){
var catSelect = this;
var catid = this.value;
var testSelectionArray = new Array();
for(var j = 0; j < this.options.length; j++) {
if (this.options[j].selected) {
testSelectionArray.push(this.options[j].value);
}
}
var subcatSelect = document.getElementById("subcatsSelect");
subcatSelect.options.length = 0; //delete all options if any present
var k=0;
for(var i = 0; i < testSelectionArray.length; i++){
catid = testSelectionArray[i];
for(var j = 0; j < subcats[catid].length; j++){
subcatSelect.options[k++] = new Option(subcats[catid][j].val,subcats[catid][j].catid);
}
}
}
</script>
<body onload='loadCategories()'>
<select id='categoriesSelect'>
</select>
<select id='subcatsSelect'>
</select>
I'm trying to use a PHP array in the JS but encountered the error I don't know how to fix.
I was using this example (in my case - it's PDO, not mysqli.): Inserting MYSQL results from PHP into Javascript Array
$pdo = new PDO('mysql:host=localhost; dbname=' . $db_name . '; charset=utf8mb4', $db_user, $db_password);
$pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$type_zagon = 1;
$id_kurat = 1;
$usid = 78;
$stmt1 = $pdo->prepare("SELECT num FROM tb_zagon_id WHERE status = :status
AND type = :type AND zagon_id = :zagon_id AND user_id = :usid ORDER BY num");
$num = $stmt1->fetchColumn();
$stmt1->execute(array(
':status' => 1,
':type' => $type_zagon,
':zagon_id' => $id_kurat,
':usid' => $usid
));
$gyvuliu_array = array();
while ($stmt1->fetch(PDO::FETCH_ASSOC)) {
$gyvuliu_array[] = $num;
}
$array_encode = json_encode($gyvuliu_array);
?>
<script>
$('.surinkti_produkcija_paserti_gyvulius').click(function() {
var gyvuliai_fermoje = '<?php echo $array_encode; ?>';
var gyvuliu_array = [1,2,3,4,5,6,7,8,9];
for (var i=0, l=gyvuliu_array.length; i<l; i++) { // WORKS
console.log(gyvuliu_array[i]);
}
// DOESN'T WORK (console returns f,a,l,s,e,f,a,l,s,e and so on..)
for (var i=0, l=gyvuliai_fermoje.length; i<l; i++) {
console.log(gyvuliai_fermoje[i]);
}
});
</script>
I guess something is bad with the $num variable but I'm not sure.
EDIT:
I've changed the second for loop and it looks like it's working:
for (var i=0, l=gyvuliai_fermoje.length; i<l; i++) {
console.log(gyvuliai_fermoje[i]);
}
But I'm not sure if it's ok they aren't in the same row.
http://prntscr.com/ft4i9m
EDIT 2 After rickdenhaan's comment, it looks exactly how first for loop. Is it ok? Am I done?
var gyvuliai_fermoje = <?php echo $array_encode; ?>;
You have to remove quotes, why? If you put the value in quotes that mean var gyvuliai_fermoje is a string not an array
Could You please try this once
$stmt1 = $pdo->prepare("SELECT GROUP_CONCAT(num) as nums FROM tb_zagon_id WHERE status = :status
AND type = :type AND zagon_id = :zagon_id AND user_id = :usid ORDER BY num");
$stmt1->execute(array(
':status' => 1,
':type' => $type_zagon,
':zagon_id' => $id_kurat,
':usid' => $usid
));
$row = $stmt1->fetch();
$array_encode = json_encode(explode(",",$row["nums"]));
?>
<script>
var gyvuliai_fermoje = <?php echo $array_encode; ?>;
$('.surinkti_produkcija_paserti_gyvulius').click(function() {
var gyvuliu_array = [1,2,3,4,5,6,7,8,9];
for (var i=0, l=gyvuliu_array.length; i<l; i++) { // WORKS
console.log(gyvuliu_array[i]);
}
// DOESN'T WORK (console returns f,a,l,s,e,f,a,l,s,e and so on..)
for (var i=0, l=gyvuliai_fermoje.length; i<l; i++) {
console.log(gyvuliai_fermoje[i]);
}
});
</script>
Try this
var gyvuliai_fermoje = <?php echo json_encode($array_encode, JSON_HEX_QUOT | JSON_HEX_APOS); ?>;
Problem solved! :) For future visitors, combined all this stuff you guys said, we have this code:
// PDO Connection
$pdo = new PDO('mysql:host=localhost; dbname=' . $db_name . ';
charset=utf8mb4', $db_user, $db_password);
$pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// Prepared statement with placeholders
$stmt1 = $pdo->prepare("SELECT num FROM tb_zagon_id WHERE status = :status
AND type = :type AND zagon_id = :zagon_id AND user_id = :usid ORDER BY num");
// Binding query result to the $num variable (1 is the first column)
$stmt1->bindColumn(1, $num);
// Executing query and replacing placeholders with some variables
$stmt1->execute(array(
':status' => 1,
':type' => $type_zagon,
':zagon_id' => $id_kurat,
':usid' => $usid
));
// Creating a PHP array
$gyvuliu_array = array();
// Fetching through the array and inserting query results using $num variable ((int) makes sure a value is an integer)
while ($stmt1->fetch(PDO::FETCH_ASSOC)) {
$gyvuliu_array[] = (int)$num;
}
// Encoding PHP array so we will be able to use it in the JS code
$array_encode = json_encode($gyvuliu_array);
?>
<script>
var gyvuliai_fermoje = <?php echo $array_encode; ?>;
for (var i = 0; i < gyvuliai_fermoje.length; i++) {
// Stuff you would like to do with this array, access elements using gyvuliai_fermoje[i]
}
</script>
I hope it will help you to understand how to use a PHP array in the JS code in PDO :)
I'm trying to manipulate my HTML table using datavalues from an SQL database that I'm extracting using PHP.
I've tried a tonne of different ways but I think the best way would be how I am approaching it now, by using a loop to assign an ID tag number corresponding to the Matrix Value of that array.
(EXAMPLE: 11, 12, 13, 21, 22, 23 etc..)
I am then calling a JavaScript function to find the element with that particular ID and replace the value with the SQL Data taken out by the PHP code.
I've inspected the elements on Chrome and can see the data going into the function but the values within the table are staying blank and not being set to the values from the mySQL.
Any help or suggestions will be greatly appreciated.
<?php
$sql = "SELECT * FROM `stock` WHERE 1";
$tableHeader = "<body><center><div><table id=\"infoTable\" class=\"myTable \"><tr><th></th><th> 1 </th><th> 2 </th><th> 3 </th></tr>";
$r_query = mysql_query($sql);
//To Table Details
//prints StackerReclaimer_StatusTable;
include("SR_TableStatus.php");
// output data of each row
echo $tableHeader;
for ($i=1;$i<5;$i++){ //Rows
$row = mysql_fetch_array($r_query);
if($i == 2 || $i==4)
echo"<tr><td> </td></tr>";
echo"<tr><td class = \"leftCol\"> Bed ".($i)."</td>";
for ($j=1;$j<4;$j++){ //Cols
echo"<td bgcolor=\"#E9E6E5\" id =\"$i$j\"></td>";
/***************************************/
$data = strtoupper($row["sortcode"])." (".(($row["stock"])/1000)."k)";
if( $row["bednumber"] == $i && $row["pilenumber"] == $j ){
// echo"<td bgcolor=\"#E9E6E5\" id = $i$j>".strtoupper($row["sortcode"])." (".(($row["stock"])/1000)."k)</td>";
echo "<script>swapValue($i$j, ".$data.");</script>";
}
/***************************************/
}
echo"</tr>";
}
echo "</table></div></body></center>";
?>
<!-- This script allows user to click on table rows to direct user to More info for that Coal -->
<script>
function swapValue(var location, var data){
var s = document.getElementById(location);
s.value = data;
}
var table = document.getElementById("infoTable");
if (table != null) {
for (var i = 1; i < table.rows.length; i++) {
for (var j = 1; j < table.rows[i].cells.length; j++)
table.rows[i].cells[j].onclick = function () {
tableText(this);
myFunc();
};
}
}
function tableText(tableCell) {
//alert(tableCell.innerHTML);
var Val = tableCell.innerHTML;
Val = Val.substring(0,7);
document.getElementById("searchBox").value = Val;
document.getElementById("searchButton").click();
}
</script>
echo "</table></div></body></center>"
first you did not end the tag properly. you placed out of body
second your block is not even inside body block
so i suggest you rewrite like this
<body>
<div>
<table id="infoTable" class="myTable">
<tr><th></th><th> 1 </th><th> 2 </th><th> 3 </th></tr>
<?php
$sql = "SELECT * FROM `stock` WHERE 1";
$r_query = mysql_query($sql);
//To Table Details
//prints StackerReclaimer_StatusTable;
include("SR_TableStatus.php");
// output data of each row
for ($i=1;$i<5;$i++){ //Rows
$row = mysql_fetch_array($r_query);
if($i == 2 || $i==4)
echo"<tr><td> </td></tr>";
echo"<tr><td class = \"leftCol\"> Bed ".($i)."</td>";
for ($j=1;$j<4;$j++){ //Cols
echo"<td bgcolor=\"#E9E6E5\" id =\"$i$j\"></td>";
/***************************************/
$data = strtoupper($row["sortcode"])." (".(($row["stock"])/1000)."k)";
if( $row["bednumber"] == $i && $row["pilenumber"] == $j ){
// echo"<td bgcolor=\"#E9E6E5\" id = $i$j>".strtoupper($row["sortcode"])." (".(($row["stock"])/1000)."k)</td>";
echo "<script>swapValue($i$j, ".$data.");</script>";
}
/***************************************/
}
echo"</tr>";
}
?>
</table>
</div>
<!-- This script allows user to click on table rows to direct user to More info for that Coal -->
<script>
function swapValue(var location, var data){
var s = document.getElementById(location);
s.value = data;
}
var table = document.getElementById("infoTable");
if (table != null) {
for (var i = 1; i < table.rows.length; i++) {
for (var j = 1; j < table.rows[i].cells.length; j++)
table.rows[i].cells[j].onclick = function () {
tableText(this);
myFunc();
};
}
}
function tableText(tableCell) {
//alert(tableCell.innerHTML);
var Val = tableCell.innerHTML;
Val = Val.substring(0,7);
document.getElementById("searchBox").value = Val;
document.getElementById("searchButton").click();
}
</script>
</body>
I've found a way to get the outcome needed.
After standing back and taking a break to rest the mind & Eyes, I've came back with fresh eyes and have now solved the issue, i was cluttering up the code by using javascript into the php which just adds to a mess if anyone was to decode or read.
so what the code does is reads values from an SQL database using PHP, reads the bednumber(Location(y)) and pileNumber(location(x))
it then makes the table using the for loops I for Rows and J for Columns,
then each column increment you need to update the SQL Query being sent back with the new cell location $i & $j which are held in the bed and pile number values.
i will post the code that now works, but any suggestions or corrections are gratefully appreciated.
<?php
$tableHeader = "<body><center><div><table id=\"infoTable\" class=\"myTable \"><tr><th></th><th> 1 </th><th> 2 </th><th> 3 </th></tr>";
//prints StackerReclaimer_StatusTable;
include("SR_TableStatus.php");
// output data of each row
echo $tableHeader;
/*####################################*/
for ($i=1;$i<5;$i++){
//$row = mysql_fetch_array($r_query);
if($i == 2 || $i==4)
echo"<tr><td> </td></tr>";
echo"<tr><td class = \"leftCol\"> Bed ".($i)."</td>";
for ($j=1;$j<4;$j++){
$sql = "SELECT * FROM `stock` WHERE `bednumber` = $i AND `pilenumber` = $j";
$r_query = mysql_query($sql);
$row = mysql_fetch_array($r_query); //Creates a loop to loop through results
if( $row["bednumber"] == $i && $row["pilenumber"] == $j ){
echo"<td bgcolor=\"#E9E6E5\">".strtoupper($row["sortcode"])." (".(($row["stock"])/1000)."k)</td>";
}
else
echo"<td bgcolor=\"#E9E6E5\"> --- </td>";
}
echo"</tr>";
} /*################################*/
echo "</table></div></center></body>";
?>
<!-- This script allows user to click on table rows to direct user to More info for that Coal -->
<script>
var table = document.getElementById("infoTable");
if (table != null) {
for (var i = 1; i < table.rows.length; i++) {
for (var j = 1; j < table.rows[i].cells.length; j++)
table.rows[i].cells[j].onclick = function () {
tableText(this);
};
}
}
function tableText(tableCell) {
//alert(tableCell.innerHTML);
var Val = tableCell.innerHTML;
Val = Val.substring(0,7);
document.getElementById("searchBox").value = Val;
document.getElementById("searchButton").click();
}
</script>
Summary of problem: I have a mysql table with some data, I use some phpcode to display the data to an html page, to setup JavaScript variables before a page loads. The loop seems to work fine with one exception, the first row of the table gets dropped or doesnt show. I cant figure out why, is there a small bit of logic Im missing?
I have a mySQL table here:
http://gyazo.com/ac75247b1a3f11f59721f03ff9c80d08
and some php code to display it here:
//...
$sql = "SELECT * FROM ".TABLE_CALCULATOR." WHERE calculation_status = 'A'";
$result = mysql_query($sql);
$row = mysql_fetch_array($result);
$num_rows = mysql_num_rows($result);
if(count($num_rows) > 0 ){
while ($row = mysql_fetch_assoc($result)) {
$calculator_data[] = $row;
}
}else{
// Send Notication to admin Calculator not set
}
//...
<?php
if(!empty($calculator_data)){
foreach($calculator_data as $k => $v ){
if($v['name_value'] == 'perWinPriceMatrix'){
$per_win_matrinx = explode(",", $v['calculation_values'] );
$per_win_matrinx_final = array_chunk($per_win_matrinx, 5, true);
foreach($per_win_matrinx_final as $key => $values ){
$var[$key] = $key.':['.implode(',',$values).']';
}
?> var <?php echo $v['name_value'] ;?> = <?php echo "{".implode(",", $var)."}";?>;<?php echo "\n";
}else{
?> var <?php echo $v['name_value'] ;?> = [<?php echo $v['calculation_values'] ;?>];<?php echo "\n";
}
}
}
?>
this is the output:
var tax_bronze2 = [30,20,20,5,0];
var tax_bronze3 = [30,20,20,5,0];
var tax_bronze4 = [25,20,20,5,0];
var tax_bronze5 = [25,20,20,5,0];
var tax_silver1 = [35,30,30,5,0];
var tax_silver2 = [30,20,20,5,0];
var tax_silver3 = [30,20,20,5,0];
var tax_silver4 = [30,20,20,5,0];
var tax_silver5 = [30,20,20,5,0];
var tax_gold1 = [70,50,30,10,0];
var tax_gold2 = [60,40,20,8,0];
var tax_gold3 = [60,40,20,8,0];
var tax_gold4 = [60,40,20,8,0];
var tax_gold5 = [60,40,20,8,0];
var tax_platinum1 = [100,75,40,10,0];
var tax_platinum2 = [80,65,40,10,0];
var tax_platinum3 = [80,65,40,10,0];
var tax_platinum4 = [80,65,40,10,0];
var tax_platinum5 = [80,65,40,10,0];
var tax_diamond1 = [0,0,0,0,0];
var tax_diamond2 = [120,85,50,20,0];
var tax_diamond3 = [120,85,50,20,0];
var tax_diamond4 = [120,85,50,20,0];
var tax_diamond5 = [120,85,50,20,0];
var perWinPriceMatrix = {0:[4,4,4,4.5,4.75],1:[5,5.3,5.7,6.2,6.2],2:[7.8,8.6,9.7,10.8,11.8],3:[13,15,17,18,18],4:[19,21,25,30,40]};
var price_matrix = [19,20,20,20,32,24,24,24,24,42,46,51,53,56,60,60,65,74,79,140,186,214,242,298];
var provisionalPrice = [60,80,9.25,13,1.3,0.75];
question: Why is output missing a row?
delete $row = mysql_fetch_array($result); this line fetch row #1
I have a form with 2 <select>, select1 allows simple selection and select 2 allows multiple selection. What I want is, when the user select something in select1, associated data in select2 should be selected according to my array of data.
function selectIt() {
var divArray = new Array();
// this is the value for first element on select1
divArray[0] = 3;
// these are the corresponding values on select2 that should be selected
divArray[0] = new Array();
divArray[0][0] = 5;
divArray[0][1] = 1;
divArray[0][2] = 2;
// and so on
divArray[1] = 2;
divArray[1] = new Array();
divArray[1][0] = 6;
divArray[1][1] = 3;
divArray[1][2] = 2;
var select2 = document.getElementById("secondSelect");
for (var i=0; i < select2.options.length; i++)
select2.options[i].selected = false;
}
So if the user selects index 1, in select2 items 2,3 and 6 should be selected.
First I deselect previously selected items using:
var select2 = document.getElementById("secondSelect");
for (var i=0; i < select2.options.length; i++)
select2.options[i].selected = false;
After that, I do not know what to do.
some loop here
select2.options[i].selected = true;
Any help will be greatly apreciated!!!!
You can declare arrays in this way:
divArray[0] = [5, 1, 2];
I will just try to answer by writing it without testing so bare in mind it can have some errors:
document.getElementById("firstSelect").onchange = function() {
var optionIndex = this.selectedIndex; // in this function 'this' is select element
var optionsToSelect = divArray[optionIndex];
var select2 = document.getElementById("secondSelect");
for (var i = 0; i < optionsToSelect.length; i++){
select2.options[optionsToSelect[i]].selected = true;
}
};
Becuase I need some database data I combined some PHP code inside the JS:
<script type="text/javascript">
function selectM() {
var divArray = new Array();
<?
if ($result = $database->getDivs()){
$cont = 0;
while ($divs = mysql_fetch_array($result)) {
$da = "divArray[".$divs['iddiv']."]";
if ($resultEd = $database->getEdic($divs['iddiv'])){
if ($cont == 0) $da .= " = [";
$tot = mysql_num_rows($resultEd);
while ($divEd = mysql_fetch_array($resultEd)) {
$da .= $divEd['ed_id']." ";
$cont++;
if ($cont < $tot) $da .= ", ";
}
}
$da .= "]; ";
$cont = 0;
echo $da;
}
}
?>
var largo, valor;
var inexE = document.getElementById("idDiv").value ;
var ediciones = document.getElementById("ediciones");
if (inexE > 0) {
var toSelect = divArray[inexE];
for (var i=0; i < ediciones.options.length; i++) {
ediciones.options[i].selected = false;
valor = ediciones.options[i].value;
largo = toSelect.length;
for(var j = 0; j < largo; j++) {
if(toSelect[j] == valor)
ediciones.options[i].selected = true;
}
}
} else {
for (var i=0; i < ediciones.options.length; i++)
ediciones.options[i].selected = false;
}
}
</script>
Works perfect!
Thank you for pointing me in the right direction!!!