I'm trying to loop through my database and output all rows with a match to the joined table.
I have the following two tables:
quest_items stores all data related to an item:
join_questitems stores association between player ID and the items that player has:
JS: pass in all the necessary info to query the table...
$.getJSON("phpscripts.php", {
"_player" : Player,
"_playerID" : UserID
},
function(returned_data) {
var item_name = returned_data.item_name;
item_image = returned_data.item_image;
$(".questItems").html(item_name + ", " + item_image);
}
);
PHP:
$statsArray = array();
$qry =
'SELECT qi.*
FROM quest_items qi
LEFT JOIN join_questitems jqi ON (qi.item_id = jqi.item_id)
WHERE jqi.user_id = "' . $playerID . '"';
$result = $mysqli->query($qry) or die(mysqli_error($mysqli));
while ($row = $result->fetch_assoc()) {
$myrow = json_encode($row);
array_push($statsArray, $myrow);
}
$k = 0;
while ($k < count($statsArray)) {
echo $statsArray[$k];
$k++;
}
But if I just do one row, I get output, but only for one row. I need both rows:
while ($row = $result->fetch_assoc()) {
echo json_encode($row);
exit;
}
$(".questItems").html(item_name + ", " + item_image) gives: rice, test/path.png
Why can't I loop through the PHP array full of json_encoded rows and output them? Do I have to set item_name and item_image as arrays and loop through the arrays?
EDIT:
$(".questItems").append(item_name + ", " + item_image) doesn't work either
network output from debugger shows rows are being output, but in the first row, my UTF-8 character, fàn, is being garbled in the client output (as you can see). This is curious, as at the top of my phpscripts.php file, I put mysqli_set_charset($mysqli, "utf8");
You shouldn't encode each row separately. Put all the results in an array, and then call json_encode on that array when you're done:
while ($row = $result->fetch_assoc()) {
$statsArray[] = $row;
}
echo json_encode($statsArray);
Then in Javascript you need to loop over the returned array:
$.getJSON("phpscripts.php", {
"_player" : Player,
"_playerID" : UserID
},
function(returned_data) {
$.each(returned_data, function(i, e) {
var item_name = e.item_name;
var item_image = e.item_image;
$(".questItems").append(item_name + ", " + item_image + "<br/>");
});
};
);
rather than this:
while ($row = $result->fetch_assoc()) {
echo json_encode($row);
exit; //<--- this code breaks the while loop;
}
have this:
$quest_items = array();
while ($row = $result->fetch_assoc()) {
$quest_items[] = $row;
}
echo json_encode($quest_items);
exit;
because exit triggers the script to stop(even inside loops) so you will only get the first row.
Related
So I have a php which gets set of coordinates from the database , I want it to run through a jquery variable.
This is the PHP -
$sql = "SQL that works";
$vari = mysqli_query($con,$sql);
while($row = mysqli_fetch_array($loc))
{echo "[";
echo "''";
echo $row['cor1'];
echo ",";
echo $row['cor2'];
echo "]";
}
This is the jquery that I want it to pass through in this form -
var markers = [
['', 51.503454,-0.119562],
['', 51.499633,-0.124755]
];
Actually you have to change your php code like below:-
$sql = "SQL that works";
$vari = mysqli_query($con,$sql);
$data = array(); //create an rray variable
while($row = mysqli_fetch_assoc($loc)){ // use assoc for lighter $row array
$data[] = array('',$row['cor1'],$row['cor2']); // create sub-array and assign to final array
}
echo json_encode($data); //return final data to ajax
Note:-Now decode this json in your jQuery via parseJSON() and do further code.
If you don't want to use ajax, you can do something like this.
For the PHP,
...
$vari = mysqli_query($con,$sql);
$coOrds = mysqli_fetch_array($loc);
$coOrds = json_encode($coOrds);
?>
For the JS,
var coOrdsJson = <?php echo $coOrds; ?>;
var coOrds = $.parseJSON(coOrdsJson);
var markersArr = [];
for (var i=0; i < coOrds.length; i++ ) {
markersArr[] = "['', " + coOrds[i].cor1 + ", " + coOrds[i].cor2 + "]";
}
var markers = markersArr.join(',');
markers = "[" + markers + "]";
i have an ajax call that gets back json i am trying to send the items returned to specific input text id's.
This is the ajax:
$.ajax({
url: "php/myfirstfile.php",
type: "POST",
data: $("#frameroof").serialize(),
cache: false,
dataType: "json",
success: function (json) {
$.each(json, function () {
$.each(json, function (key, value) {
/// do stuff
$('#' + key ).val(value);
});
});
}
});
This is what is returned: [{"a-frame":"100"}][{"vertical":"350"}]
it looks im getting 2 arrays when i need one to loop over. Im not sure.
Here is the php
if(isset($_POST["cart"])){
$frameArray = ($_POST["cart"]);
if(is_array($frameArray)){
foreach($frameArray as $row){
$catalogue = $row['catalogue'];
$certification = $row['certification'];
$catagory = $row['catagory'];
$subcatagory = $row['subcatagory'];
$length = $row['length'] ;
$sql = "SELECT `price` AS '$subcatagory' FROM `products` WHERE `catalogue_id` = '$catalogue' AND `certification` = '$certification' AND `catagory` = '$catagory' AND `sub_catagory` = '$subcatagory' AND `length` = '$length' ";
$result = $short_connect->query($sql);
if (($result) && ($result->num_rows > 0)) {
$results = array();
//convert query result into an associative array
while ($row = $result->fetch_assoc()) {
$results[] = $row;
}
//dump all data from associative array converted from query result
echo (json_encode($results,true));
$result->free();
}
}
}
}
$short_connect->close();
I believe your problem is pretty simple. Inside of your loop you're initializing the results array and you're outputting it. This causes a new results array to be created, serialized to JSON, and outputted for every iteration of the loop. Thus what you're sending the browser is not JSON, but several chunks of JSON all run together.
This is the basic idea of what you need to be doing:
<?php
// Initialize the output data
$results = array();
foreach($something as $a_something) {
$results[] = do_something_to($a_something);
}
//Serialize and send the output data
echo (json_encode($results,true));
Rearranging your code with that pattern in mind produces this (which ought to work for you, and will return an empty array to the browser if your if conditions aren't met or the query doesn't return anything):
<?php
// Initialize the output data
$results = array();
if(isset($_POST["cart"])){
$frameArray = ($_POST["cart"]);
if(is_array($frameArray)){
foreach($frameArray as $row){
$catalogue = $row['catalogue'];
$certification = $row['certification'];
$catagory = $row['catagory'];
$subcatagory = $row['subcatagory'];
$length = $row['length'] ;
$sql = "SELECT `price` AS '$subcatagory' FROM `products` WHERE `catalogue_id` = '$catalogue' AND `certification` = '$certification' AND `catagory` = '$catagory' AND `sub_catagory` = '$subcatagory' AND `length` = '$length' ";
$result = $short_connect->query($sql);
if (($result) && ($result->num_rows > 0)) {
//convert query result into an associative array
while ($row = $result->fetch_assoc()) {
//Add to the output data
$results[] = $row;
}
$result->free();
}
}
}
}
$short_connect->close();
//Serialize and send the output data
//dump all data from associative array converted from query result
echo (json_encode($results,true));
I'm trying to loop through my database and output all rows with a match to the joined table.
I have the following two tables:
quest_items stores all data related to an item:
join_questitems stores association between player ID and the items that player has:
JS: pass in all the necessary info to query the table...
$.getJSON("phpscripts.php", {
"_player" : Player,
"_playerID" : UserID
},
function(returned_data) {
var item_name = returned_data.item_name;
item_image = returned_data.item_image;
$(".questItems").html(item_name + ", " + item_image);
}
);
PHP:
$statsArray = array();
$qry =
'SELECT qi.*
FROM quest_items qi
LEFT JOIN join_questitems jqi ON (qi.item_id = jqi.item_id)
WHERE jqi.user_id = "' . $playerID . '"';
$result = $mysqli->query($qry) or die(mysqli_error($mysqli));
while ($row = $result->fetch_assoc()) {
$myrow = json_encode($row);
array_push($statsArray, $myrow);
}
$k = 0;
while ($k < count($statsArray)) {
echo $statsArray[$k];
$k++;
}
But if I just do one row, I get output, but only for one row. I need both rows:
while ($row = $result->fetch_assoc()) {
echo json_encode($row);
exit;
}
$(".questItems").html(item_name + ", " + item_image) gives: rice, test/path.png
Why can't I loop through the PHP array full of json_encoded rows and output them? Do I have to set item_name and item_image as arrays and loop through the arrays?
EDIT:
$(".questItems").append(item_name + ", " + item_image) doesn't work either
network output from debugger shows rows are being output, but in the first row, my UTF-8 character, fàn, is being garbled in the client output (as you can see). This is curious, as at the top of my phpscripts.php file, I put mysqli_set_charset($mysqli, "utf8");
You shouldn't encode each row separately. Put all the results in an array, and then call json_encode on that array when you're done:
while ($row = $result->fetch_assoc()) {
$statsArray[] = $row;
}
echo json_encode($statsArray);
Then in Javascript you need to loop over the returned array:
$.getJSON("phpscripts.php", {
"_player" : Player,
"_playerID" : UserID
},
function(returned_data) {
$.each(returned_data, function(i, e) {
var item_name = e.item_name;
var item_image = e.item_image;
$(".questItems").append(item_name + ", " + item_image + "<br/>");
});
};
);
rather than this:
while ($row = $result->fetch_assoc()) {
echo json_encode($row);
exit; //<--- this code breaks the while loop;
}
have this:
$quest_items = array();
while ($row = $result->fetch_assoc()) {
$quest_items[] = $row;
}
echo json_encode($quest_items);
exit;
because exit triggers the script to stop(even inside loops) so you will only get the first row.
guys Im still having a problem about appending into an array then put it in json for me to use it in ajax here is my code.
global $school_id;
$get_section = "SELECT *
FROM section a
LEFT JOIN advisory_sections b ON(a.section_id = b.section_id)
LEFT JOIN school_faculty c ON (b.faculty_id = c.faculty_id)
WHERE a.school_id = '$school_id' ORDER BY section_level ASC";
$result=mysql_query($get_section)or die(mysql_error());
$i=0;
$data=array();
while ($row = mysql_fetch_array($result))
{
$data[] = array(
'sec_id'=>$row['section_id'],
'sec_name'=>$row['section_name'],
'sec_dept'=>$row['section_department'],
'sec_lvl'=>$row['section_level'],
'advisory_id'=>$row['advisory_id'],
'first_name'=>$row['f_firstname'],
'last_name'=>$row['f_lastname'],
'middle_name'=>$row['f_middlename'],
'advisor_id'=>$row['faculty_id'],
);
$get_subjects = "SELECT subject_name
FROM subjects
WHERE level = '".$row['section_level']."' ";
$result_get_subjects =mysql_query($get_subjects)or die(mysql_error());
$subjects_count = mysql_num_rows($result_get_subjects);
$check_archive_subjects = " SELECT b.subject_name
FROM registrar_grade_archive a
LEFT JOIN subjects b ON(a.subject_id=b.subject_id)
WHERE a.advisor_faculty_id = '".$row['faculty_id']."'
GROUP BY b.subject_name ASC
" ;
$query_checking =mysql_query($check_archive_subjects)or die(mysql_error());
$subjects_count_sent = mysql_num_rows($query_checking);
if($subjects_count_sent == $subjects_count){
array_push($data, 'status:complete');
}else{
array_push($data, 'status:Incomplete');
}
$i++;
}
echo json_encode($data);
AJAX:
function get_sections_status(){
$.ajax({
url: 'teacher_class_get.php',
dataType: 'json',
type: 'POST', //u missed this line.
data:{'func_num':'6'},
success: function (data){
$.each(data, function(i, item) {
html = "<tr>";
html += "<td style='width:10%;'><input type='radio' name='section_id' rel='"+data[i].advisory_id+"' value='"+data[i].sec_id+"'></td>";
html += "<td style='width:25%;'><label>"+data[i].status+"</label></td>";
html += "<td style='width:15%;'><label id='year_level' rel='"+data[i].sec_lvl+"''>"+data[i].sec_lvl+"</label></td>";
html += "<td style='width:20%;'><label>"+data[i].sec_name+"</label></td>";
html += "<td style='width:30%;'><label id='faculty_id' rel='"+data[i].advisor_id+"'>"+data[i].last_name+", "+data[i].first_name+" "+data[i].middle_name+"</label></td>";
html += "</tr>";
$('#table-sections-content').append(html);
});
}
});
}
get_sections_status();
and im getting this kind of response:
[{"sec_id":"36","sec_name":"black","sec_dept":"highschool","sec_lvl":"firstyear","advisory_id":"60","first_name":"asdf","last_name":"asdf","middle_name":"asdf","advisor_id":"1"},"status:Incomplete",{"sec_id":"32","sec_name":"level-up","sec_dept":"highschool","sec_lvl":"firstyear","advisory_id":"53","first_name":"asdf","last_name":"asdf","middle_name":"asdf","advisor_id":"1"},"status:Incomplete"
as you can see the status is not inside the array. thats why im getting this kind of out put.
in my out put im having a new row with a status but with other undefined values and the others has values but with an undefined status.. please help guys.. thanks in advance
You need to add status at a different level of your data structure.
Try this (see comments in the code):
....
while ($row = mysql_fetch_array($result))
{
//Create a new item to add to $data later
$item = array(
'sec_id'=>$row['section_id'],
'sec_name'=>$row['section_name'],
'sec_dept'=>$row['section_department']
....
//Add status to $item, rather than $data
//I don't think array_push will give you what you want here
if($subjects_count_sent == $subjects_count){
$item['status']='complete';
}else{
$item['status']='incomplete';
}
//Add the new item after status has been set
$data[]=$item;
$i++;
}
....
And yes, you should look at switching to mysqli or PDO.
<?
$query = mysql_query("SELECT * FROM poi_example");
while ($row = mysql_fetch_array($query)){
$name=$row['name'];
$lat=$row['lat'];
$lon=$row['lon'];
$desc=$row['desc'];
echo ("addMarker($lat, $lon,'<b>$name</b><br/>$desc');\n");
}
?>
this code (echo) shows the table data in HTML source code.. is there another way (which does not shows the data) to extract markers from table?
thank you.
tutorial & demo page
I prefer to render them as a JSON. You can either do that in-page as you have done above.
<?php
// do database connection here
// run query to fetch your results
$rows = array();
while ($row = mysql_fetch_array($query)) {
$rows[] = $row;
}
echo "<script>var items = '".json_encode($rows)."';</script>";
You can iterate over your items array in JavaScript.
for (var i = 0; i < items.length; i++) {
(function(item) {
addMarker(item.lat, item.lon, '<b>' + item.name + '</b><br />' + item.desc);
})(items[i]);
}
I presume your addMarker() function creates a standard Google Map marker.
Alternative, you can have a PHP script that fetches your items from the database as echoes them as a JSON string, and then just call that via AJAX with jQuery.
So your PHP script would simply be:
<?php
header('Content-Type: application/json');
// connect to database
// do query
$rows = array();
while ($row = mysql_fetch_array($res)) {
$rows[] = $row;
}
echo json_encode($rows);
exit;
And then in your JavaScript file:
$.getJSON('script.php', function(items) {
for (var i = 0; i < items.length; i++) {
(function(item) {
addMarker(item.lat, item.lon, '<b>' + item.name + '</b><br />' + item.desc);
})(items[i]);
}
});
Hope this helps.