Populate an associative select from a database - php

Here's my problem: I have two select fields in my web application.
The second one depends on the choice made on the first one. The first one is populated from my database with the classical:
<?php
//connection to database in an include file
$query = "SELECT DISTINCT platform
FROM Appversions";
$res = mysql_query($query);
while($row = mysql_fetch_array($res)) {
echo "<option value=\"\"" . $row['platform'] . "</option>\n";
}
?>
which is working just fine.
But then I need to populate my second select with a query that would look like:
SELECT version
FROM Appversions
WHERE platform = <choice made in first select>;
I understand that I need to use JavaScript with an onChange function call to do that, but I can't figure out what that function should look like or how it will have access to my query result.

Usually i have this jquery code:
$('#select1').change(function(){
if($(this).val() == ''){
$('#select2').attr('disabled', 'true');
}else{
var select1 = $(this).val();
$.getJSON('index.php',
{
option: "com_spin",
controller: "guest",
task: "getProvincieByRegionId",
idRegione: idRegione
},
function(json){
$('#select2').html(json.html);
}
);
$('#select2').removeAttr('disabled');
}
});
in php i have something like this (basically i return the html for the options:
Zend_Loader::loadClass ( 'Zend_Json' );
$idRegione = JRequest::getVar ( "idRegione" );
$modelProvince = new Spin_lkpprovincia ();
$provincie = $modelProvince->getElencoProvinciePerRegione ( $idRegione );
$html = "<option value=''>Selezionare una voce</option>";
foreach ( $provincie as $provincia ) {
$html .= "<option value='" . $provincia ['idProvincia'] . "'>" . $provincia ['nome'] . "</option>";
}
$json = array (
success => "OK",
html => $html );
$json = Zend_Json::encode ( $json );
echo $json;
die ();

Related

Fill missing array values with zero if an array is empty in php mysql

i want to produce an array in this format [x,x,x] where each x is grouped by the addition of each retail id, however, for an empty array list, i want to have [x,x,0] assuming the third array is empty, instead of [x,x]
Below is my code
<?php
$q = "SELECT DISTINCT outletid FROM " . TBL_SALES_LOGS;
$result = $database->query($q);
$outlets = [];
?>
data: [<?php
while ($row = $result->fetch_assoc()) {
// $outletname = $row['title'];
$outlet_id = $row['outletid'];
$outlets[] = $row['outletid'];
$amount = $row['amount'];
?>
<?php echo $outlet_id; ?>,
<?php } ?> ]
data: [<?php
$outlet = implode("','", $outlets);
$qsum3 = "SELECT outletid, SUM(amount) AS totalsum FROM " . TBL_SALES_LOGS . " WHERE outletid IN ('{$outlet}') and fueltype='PMS' group by `outletid`";
$qresult3 = $database->query($qsum3);
while ($rowq3 = $qresult3->fetch_assoc()) {
$tot3 = $rowq3['totalsum'];
?>'<?php echo $tot3; ?>',<?php } ?>]
instead of having [3,4,2,3] and missing value not showing, i want to have [3,4,2,0,3] for the missing values, assuming 0 is the missing values
thanks
I have made a few changes. Mostly created a key value array depending on the id as the key, and setting all those values to sum => 0. Then, when you loop through all of the id and their sum's it changes the sum of the id's it finds.
It is untested, but should solve it. You may need to change the end. It was messy with all the opening and closing php tags.
<?php
$q = "SELECT DISTINCT outletid FROM " . TBL_SALES_LOGS;
$result = $database->query($q);
$outlets = [];
$outletsIdSum = [];
?>
data: [<?php
while ($row = $result->fetch_assoc()) {
// $outletname = $row['title'];
$outlet_id = $row['outletid'];
$outlets[] = $outlet_id;
$outletsIdSum[(int)$outlet_id] = 0;
$amount = $row['amount'];
?>
<?php echo $outlet_id; ?>,
<?php } ?> ]
data: [<?php
$outlet = implode("','", $outlets);
$qsum3 = "SELECT outletid, SUM(amount) AS totalsum FROM " . TBL_SALES_LOGS . " WHERE outletid IN ('{$outlet}') and fueltype='PMS' group by `outletid`";
$qresult3 = $database->query($qsum3);
while ($rowq3 = $qresult3->fetch_assoc()) {
$outletsIdSum[(int)$rowq3['outletid']] = $rowq3['totalsum'];
}
echo "'" . implode( "','", $outletsIdSum );
?>]
add if condition on array
<?php
foreach(some_array as a)
{
if(a=="" or a==NULL)
a=0;
}
?>
this will check array element which is empty and then ,if it is empty it will assign array element to '0'
use this algorithm

How to remove quotes from each element in a javascript array containing JSON encoded html strings returned from a mysql database with php

Ajax call to the mysql data base using data1.php file with pdo returns hmtl strings that are put into an array, encoded with json and sent to the ajax response function for display in html. Of course the elements in the array have tags and quotations, which are difficult to remove. Easiest and closest solution so far is to replace the quotes in the strings with javascript .replace(). This doesn't work for the array of arrays unless the single element is referenced. What's the way around this? Here is the code.
Ajax call:
function processForm_L(){
var topic = $("#topic").val();
// send data
$.ajax({
url: "../php/get_data1.php",
data: {
topic1:topic},
type: 'POST',
dataType: 'json',
success: processResult_L
}); // end .onclick
}
The response function:
function processResult_L(data, textStatus){
// Required Callback Function
if(data['status']['response'] == 1){
//if(data[0] == 1){
table_1 = [];
table_2 = [];
table_3 = [];
table_1 = data.table['a'].replace( /"/g,"");
table_2 = data.data.replace(/"/g,"");
table_3 = data.table['b'].replace( /"/g,"");
//table_1 = JSON.parse(data.table['a']);
//table_2 = JSON.parse(data.data);
//table_3 = JSON.parse(data.table['b']);
//console.log(table_1);
console.log(table_2);
//console.log(table_3);
}//end if response == 1
else if(data.response == 0){
//var response = data + textStatus;
var table_4 = data.error;
$('#display').html(table_4);
}//end if response==0
}//end process results
The query part of get_data1.php
<?php
$ret_s = Array();//return status
$ret_t = Array();//return table
$ret_d = Array();//return data
$result = Array();
$row_1 = 1;
if(!empty($_POST)){
try{
if(!empty($_POST)){
//connect to database and insert data
// include "db_connect_df.php";
// select everything from the raw_data database
$sql = "SELECT * FROM `raw_data`";
// prepare the sql statement
$stmt_s = $db->prepare($sql);
$stmt_s->execute();
$result = $stmt_s->fetchAll(PDO::FETCH_ASSOC);
//set response variable
$ret_s['response'] = 1;
//table header
$ret_t['a'] ="<table id='display_table'><tr><th>ID</th><th>Organization</th><th>Contact Names</th><th>Telephone</th><th>Email</th><th>Website</th><th>Country</th><th>Region</th><th>City</th><th>Street</th><th>Unit</th><th>Postal Code</th><th>Topic</th><th>Message</th><th>Date</th></tr>";
//fetch each row from database as html
foreach($result as $row){
$ret_d[$row_1] = "<tr>" ."<td>" . $row['ID'] . "</td>" ."<td>" .
$row['Organization'] . "</td>" ."<td>" . $row['Telephone'] . "</td>" . "<td>" . $row['Email'] . "</td>" ."<td>" . $row['Website'] . "</td>" ."<td>" . $row['Country'] . "</td>" ."<td>" . $row['Region'] . "</td>" ."<td>" . $row['City'] . "</td>" ."<td>" . $row['Street'] . "</td>" ."<td>" . $row['Unit'] . "</td>" ."<td>" . $row['Postal_Code'] . "</td>" ."<td>" . $row['Topic'] . "</td>" ."<td>" . $row['Message'] . "</td>" ."<td>" . $row['ts'] . "</td>" ."</tr>";
$row_1++;
}
// end table tag
$ret_t['b'] = "</table>";
//echo and encode array
echo json_encode(array('status' => $ret_s, 'table' => $ret_t,'data'=> $ret_d),JSON_HEX_QUOT|JSON_HEX_TAG);
// echo json_encode(stripslashes_nested(array('status' => $ret_s, 'table' => $ret_t,'data'=> $ret_d)),JSON_HEX_QUOT|JSON_HEX_TAG);
}//end connect
}//end try
catch (PDOException $e) {
$error16 = '<span class="error_s">Try again another time.</span>';
$error17 = '<span class="error_s">ERROR:' . $e->getMessage();
$ret_s['response'] = 0;
$ret_s['error'] = $error16 . $error17;
echo json_encode($ret_s);
} //end failure
}//end if is !empty($_POST)
?>
Note: this queries a localhost database served through xampp. This isn't all the code but everything works just fine except the following:
1) table_2 = data.data.replace(/"/g,""); returns 'data.data.replace() is not a function, because the array is an object not a string
2) when comment out above line and comment in only console.log(table_1); result in console is:
<table id='display_table'><tr><th>ID</th><th>Organization</th><th>Contact Names</th><th>Telephone</th><th>Email</th><th>Website</th><th>Country</th><th>Region</th><th>City</th><th>Street</th><th>Unit</th><th>Postal Code</th><th>Topic</th><th>Message</th><th>Date</th></tr> So that works.
3) similarly commenting in only console.log(table_3); returns in console:
</table> so that also works.
4) if comment in table_2 = data.data; and enter table_2 into console result is:
undefined
5) tried this code to remove quotes from the array of arrays:
a) putting a function in the js init file for the page:
function replace_quotes(x){
for(var i=0; i < x.length; i++) {
x[i] = x[i].toString().replace(/"/g,"");
}
}
and using that function on the data array in the data object created by the response callback function (so x = data.data)
result is undefined, and it doesn't work.
JSON.parse(table_1); just runs into a < right away and won't parse, for any of the strings in the data array (table_2 or table 3).
adding JSON_HEX_QUOT | JSON_HEX_TAG didn't work.
Presumably looping through the array data.data with a function and using .replace() and a reg exp to replace quotes with nothing should be the easiest solution. Any tips on how to loop through a json_encoded array of html strings in an array returned in an ajax callback?
Don't replace anything anywhere. The only thing you need is to add htmlspecialchars() when you building the HTML string.
<?php
// ...
$rows = [];
foreach ($result as $r) {
$rows[] = '<tr><td>'.htmlspecialchars($r['id'])
.'</td><td>'.htmlspecialchars($r['phone_number'])
.'</td></tr>';
}
header('Content-Type: application/json; encoding=utf-8');
echo json_encode(array('table_rows' => join("\n", $rows)));
Then, when you receive such JSON, just put it into HTML as it is.
$('table#display').html(received_data.table_rows);
But there is better way to implement this. -- Send only data without markup via JSON and build markup in JS:
<?php
// ...
$rows = [];
foreach ($result as $r) {
$rows[] = [
'id' => $r['id'],
'phone_number' => $r['phone_number']
];
}
header('Content-Type: application/json; encoding=utf-8');
echo json_encode(array('table_rows' => $rows));
And then:
// ...
for(var i = 0; i < received_data.table_rows.length; i++) {
var r = received_data.table_rows[i];
$table.append($('<tr>')
.append($('td').text(r.id))
.append($('td').text(r.phone_number))
);
}
PHP case 0, file called from ajax dropdown selector form submission:
if(!empty($_POST)){
//connect to database and insert data
// include "db_connect_df.php";
include "db_connect_df_test.php";
//switch statement for mysql queries based on dropdown selected
switch($topic_2){
case "Address":
//set response variable
$ret_s['response'] = 0;
// select organization address
$sql = "SELECT IFNULL(ID, '--') AS ID,
IFNULL(Organization, '--') AS Organization,
IFNULL(Contact_Names, '--') AS Contact_Names,
IFNULL(City, '--') City,
IFNULL(Street, '--') AS Street,
IFNULL(Unit, '--') AS Unit,
IFNULL(Postal_Code, '--') AS Postal_Code,
IFNULL(Region, '--') AS Region,
IFNULL(Country, '--') AS Country,
IFNULL(ts, '--') AS ts
FROM `raw_data`";
// prepare the sql statement
$stmt_s = $db->prepare($sql);
$stmt_s->execute();
$result = $stmt_s->fetchAll(PDO::FETCH_ASSOC);
// extract table rows
foreach($result as $row){
$ret_d[$row_1] = [
'Id'=> $row['ID'],
'Organization' => $row['Organization'],
'Contact_Names' => $row['Contact_Names'],
'City'=> $row['City'],
'Street'=> $row['Street'],
'Unit' => $row['Unit'],
'Postal_Code' => $row['Postal_Code'],
'Region' => $row['Region'],
'Country'=> $row['Country'],
'Date'=> $row['ts']
];//end load data from data base
$row_1++;
}//end table data as rows
break;
Javascript init file, case 0 section of ajax response function:
function processResult_L(data, textStatus){
// Required Callback Function
//create dom elements for table head and body
//to check variables in dev console remove 'var'(make public)
var $table = $("<table id='display_table'>");
$table.append($('<tbody>'));
//create response array
var response = {};
response = data['status']['response'];
//create row array for building table data
var r = [];
switch(response){
case 0: /*Address case */
// build table header
$table.append($('<tr>')
.append($('<th>').text('ID'))
.append($('<th>').text('Organization'))
.append($('<th>').text('Contact'))
.append($('<th>').text('City'))
.append($('<th>').text('Street'))
.append($('<th>').text('Unit'))
.append($('<th>').text('Post Code'))
.append($('<th>').text('Region'))
.append($('<th>').text('Country'))
.append($('<th>').text('Date')));
// build table content
for(var i = 0; i < data.table_rows.length; i++) {
r[i] = data.table_rows[i];
$table.append($('<tr>')
.append($('<td>').text(r[i].Id))
.append($('<td>').text(r[i].Organization))
.append($('<td>').text(r[i].Contact_Names))
.append($('<td>').text(r[i].City))
.append($('<td>').text(r[i].Street))
.append($('<td>').text(r[i].Unit))
.append($('<td>').text(r[i].Postal_Code))
.append($('<td>').text(r[i].Region))
.append($('<td>').text(r[i].Country))
.append($('<td>').text(r[i].Date))
); // end append table content
} // end build table content
break;

Single jQuery to update multiple elements

I have the following jquery statement:
$("#add").click(
function(event){
var groupName = $("#groupName option:selected").text();
var studentsToAdd = $('select#mainList').val();
var mode = "exempt";
$.post(
"addToList.php",
{ studentsToAdd: studentsToAdd, mode: mode },
function(data) {
$('#groupList').html(data[exemptList]);
$('#mainList').html(data[nonexemptList]);
}
);
});
With the following php code:
$studentsToAdd = $_REQUEST['studentsToAdd'];
$arrayLength = count($studentsToAdd);
$exemptList = "";
$nonexemptList = "";
for ($i=0;$i<$arrayLength;$i++){
$result = mysql_query("UPDATE students SET exempt=1 WHERE id = '$studentsToAdd[$i]'");
}
$result = mysql_query("SELECT * from students WHERE exempt = 1");
while($row = mysql_fetch_array($result))
{
$exemptList = $exemptList . "<option value=\"" . $row['id'] . "\">" . $row['last'] . ", " . $row['first'] . "</option>";
}
$result = mysql_query("SELECT * from students WHERE exempt = 0");
while($row = mysql_fetch_array($result))
{
$nonexemptList = $nonexemptList . "<option value=\"" . $row['id'] . "\">" . $row['last'] . ", " . $row['first'] . "</option>";
}
$data = array(
'exemptList' => $exemptList,
'nonexemptList' => $nonexemptList
);
echo json_encode($data);
I am trying to update both mainList and exemptList select elements with the single jQuery .post. It is not working. Thoughts?
If your php code is in another page or in a function, which you haven't mentioned, return $data instead of return json_encode($data) should work and leave it as an array. Otherwise you are getting a json string back, from json_encode(), which you need to parse into a javascript object, so try:
var decoded = $.parseJSON(data);
$('#groupList').html(decoded.exemptList);
$('#mainList').html(decoded.nonexemptList);
At least from what i can tell at first glance and 11 pm.
Edit: You can always try console.log(data) with Firefox Firebug plugin and see what you are getting from the server and then see if you need to decode what you are getting, change how you write the array or quotes or whatever.
A possible solution is to decode the JSON object when it is returned. Additionally, the stuff inside the [] needs to have quotes around it:
function(data) {
var json = JSON.parse(data);
$('#groupList').html(json["exemptList"]);
$('#mainList').html(json["nonexemptList"]);
}
Also, maybe try $.ajax, and set dataType to json (even though the default is intelligent guess, which should work anyway since the PHP is sending a JSON object.)
Maybe you could try:
function(data) {
$('#groupList').html(data["exemptList"]);
$('#mainList').html(data["nonexemptList"]);
}
exemptList and nonexemptList were probably treated as variables instead of names.

PHP JQuery Checkbox Array - Selecting only 1 value

Following is an ajax post page which renders the checkboxes on run-time. I am facing issue while writting the script for select all button, when I click on the button only 1 value is getting selected not the entire array:
<?php
session_start();
error_reporting(E_ALL);
ini_set("display_errors", 1);
include("../includes/functions.php");
if(isset($_REQUEST['t']))
{
$td = $_REQUEST['t'];
$t = split(",",$td);
$all = "";
$box_in_row = 0 ;
$this_box="<table border=0><tr>";
foreach($t as $table)
{
$this_box = "<td><h3>$table</h3>";
$result = mysql_query("SHOW FULL COLUMNS FROM $table FROM prfxcom1_prfx");
$options = "";
while($r = mysql_fetch_object($result))
{
if(!empty($r->Comment))
{
$options .= "<br><input type=checkbox name=\"".$table."[]\" value='$r->Field' id=\"$table\">" . $r->Field;
}
}
if($table == "transfer_req")
{
$options .= "<br><input type=checkbox name=\"".$table."[]\" value='Net Profit' id=\"$table\">NetProfit";
}
$this_box .= $options;
// Button
$click = "$('#$table').attr('checked', 'checked')";
$button = "<br /><input style='margin-top:10px;' type='button' name='$table_button' id='$table_button' value=' Select All ' onclick=\"$click\"/>";
$all .= "<div class='tblBox'>".$this_box.$button."</div></td>";
}
//$all = "<table class=\"listing form\" cellpadding=\"0\" cellspacing=\"0\">".$all."</table>";
echo $all;
}
?>
Issue is faced in the line:
$click = "$('#$table').attr('checked', 'checked')";
Please suggest, I am stuck on this.
Thanks,
Hardik
WHAT???
$click = "$('#$table').attr('checked', 'checked')";
How can you write Javascript in the middle of a PHP file? It needs to be in script tags but even then PHP runs at the server and will not render your Javascript for you.
Add script tags, change your ID's to separate ones and give them the same class like tableClassName, and then write the following.
$(function(){
$('.tableClassName').attr('checked', 'checked')";
});
Ignoring the many issues with the code and simply answering the question:
You need to refer to the checkboxes using a class name not a ID (you have given them all the same ID)
For these lines: $options .= "<br><input type=checkbox name=\"".$table."[]\" value='$r->Field' id=\"$table\">" . $r->Field;
Change to: $options .= "<br><input type=checkbox name='" . $table . "[]' value='" . $r->Field ."' class='" . $table . "'>" . $r->Field;
For this line: $click = "$('#$table').attr('checked', 'checked')"; use single quotes or escape the $
Change to: $click = '$("."'.$table.'").attr("checked", "checked")';

How to set multiple select options by default from array

I'm trying to retrieve options/values from my database in the from of an array i would like to set these option/values as selected by default in a multiple select list and display them to the user where they will be able to updated their data if necessary.
//data in database
$mytitle = array(
'Arbitrator',
'Attorney',
'Student',
'Other'
);
//data for multiple select
$title = array(
'Judge' ,
'Magistrate' ,
'Attorney' ,
'Arbitrator',
'Title Examiner' ,
'Law Clerk','Paralegal' ,
'Intern' ,
'Legal Assistant',
'Judicial Assistant',
'Law Librarian' ,
'Law Educator' ,
'Attorney',
'Student',
'Other'
);
echo "<select name='title[]' multiple='multiple'>";
$test = implode(',', $mytitle);
for ($i=0; $i<=14; $i++) {
if($test == $title[$i]) {
echo "<option selected value='$title[$i]'>$title[$i]</option>";
}
else {
echo "<option value='$title[$i]'>$title[$i]</option>";
}
}
echo "</select>";
I think you may have a logic error. Try this as your loop:
foreach ($title as $opt) {
$sel = '';
if (in_array($opt, $mytitle)) {
$sel = ' selected="selected" ';
}
echo '<option ' . $sel . ' value="' . $opt . '">' . $opt . '</option>';
}
Use the in_array() function.
for ($i=0; $i<=14; $i++) {
if(in_array($title[$i], $mytitle)){
echo "<option selected value='$title[$i]'>$title[$i]</option>";
}else {
echo "<option value='$title[$i]'>$title[$i]</option>";
}
}
Very simple with the help of jQuery where the select has the id test
$('#test option').attr('selected', 'selected');
JSFiddle Example

Categories