parsing multidimensional array from php to jquery - php

I am using php and jquery to read data out of a database, put it into a 2-dimensional array, return it with jquery, and display it on a webpage. I get tripped up when I try to display it.
Here's my jquery code:
$('.sf1930').click(function(){
$year = "1930";
$.post('get_year.php', {year:$year},
function(data){
console.log(data);
$('#occupant_rect').show();
var obj = jQuery.parseJSON(data);
//$('#occupantList').append( data[0][1] );
console.log(obj[0].address);
$('#occupantList').append( obj[0].address );
})
})
The first console.log displays my data beautifully:
"[{\"address\":\"1202 Arch St.\",\"occupant\":\"Morris Wolfe tailor\"},{\"address\":\"1400 Arch St.\",\"occupant\":\"The Great A&P Tea Co. Grocery\"},{\"address\":\"1500 Arch St.\",\"occupant\":\"Hoge's Drug Store\"}]"
but the second console log shows that obj[0].address is undefined.
Here's my php code:
$year = $_POST['year'];
//echo json_encode($year);
if ($year == '1930') {
$q1930 = "SELECT address, occupant1930 FROM mytable WHERE occupant1930 <> ''";
$result = $mysqli_getstores->query($q1930);
while($row = $result->fetch_array(MYSQLI_ASSOC)) {
//echo json_encode($row['address'] . ',' . $row['occupant1930']);
$response = array(address=>$row['address'],occupant=>$row['occupant1930']);//end array
array_push($responses, $response);//push this array of one record into a larger
//array to hold all records
} //end while
echo json_encode(json_encode($responses)); //return the array of arrays
}//end year == 1930
?>
Note that I've double json_encoded the results.
I've looked at a number of stackoverflow questions on this topic, but the answers don't appear to be working for me.
Does anyone see what I'm doing wrong, please?

Related

Finding a match between array and database

I have an array called "selected_checkboxes". In my database I have multiple columns and some of them contain the value 1, otherwise the value will be NULL. The names of those columns are exactly the same as the values of the array.
I would now like to check dynamically if the values of my array ($_POST['selected_checkboxes']) match with the values of my columns in the database. If ALL values from the array have the value 1 in the database, it should echo something like Match!
This is what I have tried so far but I think it's completely wrong:
if(!$result = $db->query("SELECT * FROM products")){
die('Error');
}
while($row = $result->fetch_object()){
foreach($_POST['selected_checkboxes'] as $value) {
if ($value == 1) {
$say .= $value . ' is = 1';
}
}
}
echo $say;
I appreciate any help!!
Edit:
This is how the array 'selected_checkboxes' is getting generated:
$('.show_result').click(function() {
// Get all selected checkboxes
var selected = [];
$.each($("input[type=checkbox]:checked"), function(){
selected.push($(this).attr('id'));
});
// Get the selected option field
selected.push($('#PG_Select_Bereich1').val());
// Deliver data to PHP
$.ajax({
url : "typo3conf/ext/produkteguide_sg/pi1/products.php",
type: "POST",
data : { selected_checkboxes:selected },
success: function(data, textStatus, jqXHR)
{
$("#PG_Resultate").html(data);
},
error: function (jqXHR, textStatus, errorThrown)
{
//alert(errorThrown);
}
});
And this is how my database looks like:
I've done something similar but in a different way, I hope this is what you're looking for:
// Query execution
$result = mysqli_query($CONN,"SELECT * FROM whatever");
while($row_from_db = mysqli_fetch_array($result)){
$db_value = is_null($row_from_db['myValue']) ? 0 : 1;
$check_value = !isset($_POST['selected_checkboxes']['myValue']) ? 0 : 1
echo $db_value == $check_value ? "Match!" : "Not matching :(";
}
I am writing pseudo code for your requirement.
1) loop through array.
2) while loop through array if value of element is found 1 the go to next step otherwise continue loop.
3) If array element value is 1 then get a key of element and prepare sql query which checks that column name same as key name have value as 1 for each record then mark it as Match.
Hope this helps to you. If you not get with this then let me know i will write the code for you.
Edit:
Each of your checkbox name must be same as column name in database.
$array_checkbox = $_POST['selected_checkboxes'];
$query =" SELECT count(*) FROM <tabel_name> WHERE 1=1";
// get count from query and store it in $total_rows variable
$total_rows = 10; // for example purpose we take count value as 10
foreach($array_checkbox as $key => $checkbox){
$query = $query =" SELECT count(*) FROM <tabel_name> WHERE $key=1"; // here we take key of array as column name in sql query and getting that how many rows of the column have value 1
// get count from query and store it in $result variable
$result = 10;
if($result == $total_rows){
echo "Match";
}
}
Hope this is according to your requirement.

Fetching database records with MySQL - random row selection with PDO

I'm trying o fetch data from a database specific to a quiz. I have two tables named 'questions' and 'options'. Each question has 2 corresponding options and 'questionID' row is present in 'options' table as a foreign key.
I'm fetching 4 random questions and their corresponding answers with this query:
SELECT * FROM questions INNER JOIN options ON
questions.questionID=options.questionID, (SELECT questionID AS sid FROM questions
ORDER BY RAND( ) LIMIT 4 ) tmp WHERE questions.questionID = tmp.sid AND
options.questionID=questions.questionID ORDER BY questions.questionID
This query runs fine and retrieves appropriate rows from both questions and options tables on phpMyAdmin but when I fetch the array in php and then retrieve the arrays with AJAX all the options are random and not matching with their questions - some of them do not match with any of the questions selected.
Thanks in advance for any advice.
I checked the php fiel on its own and it seems like it's only the AJAX's fault. Now I see why - I'm making two calls to the file and I think it might be running the query again and that's why the answers do not match. Any solution?
Here's my AJAX call the same is for answers just with different url parameter:
var dataQuest = (function() {
var questions;
function load(){
$.ajax({
type: "GET",
url: "randomQ.php?q=0",
dataType: 'json',
async: false,
success: function(data){
questions = data;
//alert(questions);
alert(questions);
},
error: function(XMLHttpRequest, textStatus, errorThrown){
$('#place1').text("Error: " +textStatus +" "+ errorThrown);
}
});//end ajax
} //end of load
return {
load: function() {
if(questions) return;
load();
},
getQuest: function(){
if(!questions) load();
return questions;
}
}
})();//end of dataQuest function
As requested - the php bit:
while( $row = $stmt->fetch()) {
$quests[] = $row['question'];
$answers[] = $row['option'];
}
//$questions = array_unique($quests);
//$answs = array_chunk($answers, 2);
if($_GET['q']==0)
{
echo json_encode($quests);
}
else
{
echo json_encode($answers);
}
I've changed that into:
$arrays[] = $quests;
$arrays[] = $answers;
echo json_encode($arrays);
//echo json_encode($answers);
And that returns the appropriate answers and questions to AJAX - however to make that work - I need to split this 2D array in Javascript - any recommendations on how to achieve that appreciated.
Try this...
SELECT * FROM questions
LEFT JOIN options ON
questions.questionID=options.questionID
WHERE options.questionID=questions.questionID
ORDER BY RAND()
LIMIT 8 //You will need 8 rows as each question has 2 option rows
Hard to know without seeing your db schema but this should work.
In your PHP script this change may help you associate the data in your jQuery:
while( $row = $stmt->fetch()) {
///use the PK of the question instead of arbitrary index
$quests[$row['question_id']] = $row['question'];
$answers[$row['question_id']] = $row['option'];
}
Or maybe..
while( $row = $stmt->fetch()) {
//create a single array indexed by question pk with sub array of options
$quests[$row['question_id']]['question'] = $row['question'];
$quests[$row['question_id']]['options'][] = $row['option'];
}

jQueryUI autocomplete JSON not returning expected data

Using jQueryUI autocomplete to search a MySQL database. When user presses enter in the search field, I want to populate a div with the result(s) returned from DB.
The code works and does return an autocomplete list of suggestions.
However, the JSON data returned in the select: function is not what I expected.
In the PHP code sample below, the query requests all fields from the database related to each title matched by the query. There should have been other fields, like author, bid, isbn, genre, etc. -- however, only the title field was returned.
Google Chrome's console looks like this:
Object {item: Object}
item: Object
label: "Much Obliged Jeeves"
value: "Much Obliged Jeeves"
__proto__: Object
Object {label: "Much Obliged Jeeves", value: "Much Obliged Jeeves"}
Where are the other fields?
My jQuery:
$('#srxbks').autocomplete({
source: "autocomplete_test.php",
minLength: 1,
select: function( event, ui ) {
console.log(ui);
console.log(ui.item);
console.log(ui.item.label);
//Not working:
var out = 'Title: ' + ui.item.title + '<br>';
out += 'Author: ' + ui.item.author + '<br>';
$('.booksTableDIV').val(out);
}
});
My PHP:
<?php
include 'connect.php';
$term = strip_tags($_GET['term']);//retrieve search term sent by autocomplete
$qstring = "SELECT * FROM `books` WHERE `title` LIKE '%" .$term. "%'";
$query = mysql_query($qstring) or die(mysql_error());
while ($row = mysql_fetch_array($query)) {
$row['title']=htmlentities(stripslashes($row['title']));
$row['bid']=(int)$row['bid'];
$row_set[] = $row['title'];
}
echo json_encode($row_set);
You just need to be sure all your variables are included in the returning array. Your PHP is the part having an issue, your are not transferring the variables to JSON correctly. Your jQuery is fine. The following is what you need to do for each extra variable you wish to send back to your jQuery.
// Initialize your variables here
$returns = array();
$i = 0;
while ($row = mysql_fetch_array($query)) {
// Format your variables here
$row['title']=htmlentities(stripslashes($row['title']));
$row['bid']=(int)$row['bid'];
// Enter results into JSON array here
$returns[$i]['title'] = $row['title'];
$returns[$i]['bid'] = $row['bid'];
$i++;
}
echo json_encode($returns);

Populating PHP array from MySQL for use by Amcharts

I'm trying to set up some simple Amcharts graphs for a company intranet webpage. Over the last two weeks I have created HTML/JS and produced a nice graphic using Amcharts (data hard-coded in the HTML for demo purposes). I also installed XAMPP and created a MySQL database, populated with tables and some data that gets imported from csv files.
So far, everything is working fine - I can display nice graphics and I can collect the data for supplying data to the graphs. However, I have been approaching this problem from the 2 ends (getting the source data into a database AND presenting the data in a graph on a webpage). Now I need to join these 2 ends, so I can feed Amcharts with data from MySQL.
I know I need to use PHP to get the data from MySQL and put this into an array that can be used by Amcharts but my PHP knowledge is very basic and I'm struggling with the code.
What I have is PHP code which successfully connects to MySQL and extracts data to display in a browser - that works. I just don't know how to get that data into a multi-dimensional array in the format that Amcharts needs for plotting its graph.
It would be really great if you guys could give me some help here and fill in the missing pieces. I have some pseudo code for the logic of creating the array as the basis for the 'real' php code.
This is the pseudo code for populating the array:
;charset=UTF-8', '', '', array(PDO::ATTR_EMULATE_PREPARES => false,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));
$stmt = $db->query("SELECT * FROM <mytable> WHERE <mycondition>");
$prevweek = "9999";
$headrowdone = 0;
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
if ($prevweek < $row['WeekNumber']) {
// New week so write out Category X Label ('Week') with the week number of the following data rows
chartData.push($DataRow);
$headrowdone = 0;
}
if (!$headrowdone) {
$DataRow = "Week: "+$row['WeekNumber'];
$headrowdone = 1;
}
// Write out the X-Axis Category value and the Y-Axis value
$DataRow = $DataRow+$row['XAxisCategory']+": "+$row['YAxisCategory'];
$prevweek = $row['WeekNumber'];
}
chartData.push($DataRow); ?>
The SQL table looks like:
CREATE TABLE ( WeekNumber varchar(4), XAxisCategory
varchar(50), YAxisValue integer );
and has data like: '1301','A',10 '1301','B',20 '1301','C',24
'1302','A',11 '1302','B',22 '1302','C',27 '1303','A',14 '1303','B',23
'1303','C',28 ...etc
The data array for amcharts needs to look like:
var chartData = [{ Week: "1301",
A: 10,
B: 20,
C: 24
}, {
Week: "1302",
A: 11,
B: 22,
C: 27
}, {
Week: "1303",
A: 14,
B: 23,
C: 28
....etc
}];
// This is spoofing your fetch via pdo
$rows [] = array('WeekNumber'=>1301, 'A'=>10);
$rows [] = array('WeekNumber'=>1301, 'B'=>20);
$rows [] = array('WeekNumber'=>1301, 'C'=>25);
$rows [] = array('WeekNumber'=>1302, 'A'=>12);
$rows [] = array('WeekNumber'=>1302, 'B'=>22);
$rows [] = array('WeekNumber'=>1302, 'C'=>27);
//var_dump($rows);
// set up some vars
$lastweek = '';
$ctr = 0;
$data = array();
// loop thru the vars, build another array
foreach( $rows as $row){
if($row['WeekNumber'] !== $lastweek){
$ctr++;
$data[$ctr] = array('Week'=>$row['WeekNumber']);
$lastweek= $row['WeekNumber'];
}
// this could be nicer, but for now will do
if( isset($row['A']) ) $data[$ctr]['A'] = $row['A'];
if( isset($row['B']) ) $data[$ctr]['B'] = $row['B'];
if( isset($row['C']) ) $data[$ctr]['C'] = $row['C'];
}
var_dump($data);
Then use json_encode() to get into the format you want.
This answer is a bit kludgy, but at least gets away from building strings to make json.

Error with my dojo ajax php request

Im trying to use a dojo ajax function to call a PHP file that then returns the contents of a DB table in JSON format.
My function:
var _getWeatherInfo = function(){
dojo.xhrget({
url: "PHP/weather.php?ntown=" + _ntown,
handleAs: "json",
timeout: 5000,
load: function(responce, details) {
_updateWeathertData
},
error: function(error_msg, details) {
_handleError(error_msg);
}
});
}
My PHP:
<?php include('configHome.php'); ?>
<?php
$ntown = $_GET['ntown'];
$weather = array();
$query="SELECT * FROM `weather` WHERE `town` = '$ntown'";
$result=mysql_query($query);
while($row = mysql_fetch_row($result)) {
$weather[] = $row[0];
}
echo json_encode($weather);
mysql_close();
?>
When using this code I am getting an error message saying that "$ntown = $_GET['ntown'];" is an undefined index. I have tried removing the index all together and using an actual value in the select statement (i.e. SELECT * FROM weather WHERE town = 'Auckland') but all I get back is the value i enter ["Auckland"], and not the 3 other values that are meant to be returned, ["Auckland", "Sunny", "8", "14"].
Any ideas? I can try add more info if needed. Thanks!
There are some other issues with your code, but to get to the one you are asking the question about. You have this:
while($row = mysql_fetch_row($result)) {
$weather[] = $row[0];
}
What you are doing is just taking the first value of the row (of which there is probably only one, and just sending that back. This is what you need:
$weather = mysql_fetch_row($result);

Categories