JSON formatting errors for two files - php

I would like to know, I have just created my datatables, but two of them are giving JSON formatting errors. I am doing a join of two tables in these two. I tried running the query in phpmyadmin, and it works just fine Here is one example of my server-side files:
<?php
$username="drup197";
$password="*****";
$database="census";
$server="localhost";
$link = mysqli_connect($server,$username,$password,$database);
//#mysql_select_db($database,$link) or die( "Unable to select database");
$query = "
SELECT *
FROM national_age_gender_demographics INNER JOIN arizona_age_gender_demogrpahics
WHERE national_age_gender_demographics.age_group = arizona_age_gender_demogrpahics.age_group
ORDER BY national_age_gender_demographics.index_number";
$result = mysqli_query($link,$query);
if(!$result) die( "Query: " . $query . "\nError:" . mysql_error() );
//print_r($row);
$tableData = '{"aaData": [[';
$numRows = $result->num_rows;
$row = mysqli_fetch_array($result);
for ($i = 0; $i < $numRows; $i++) {
if ($i != 0) {
$tableData .= ",[";
}
$tableData .= '"' . $row['age_group'] . '",';
$tableData .= '"' . $row['national_age_gender_demographics.both_pop'] . '",';
$tableData .= '"' . $row['national_age_gender_demographics.male_pop'] . '",';
$tableData .= '"' . $row['national_age_gender_demographics.female_pop'] . '",';
$tableData .= '"' . $row['national_age_gender_demographics.male_percent'] . '",';
$tableData .= '"' . $row['national_age_gender_demographics.female_percent'] . '",';
$tableData .= '"' . $row['national_age_gender_demographics.both_percent'] . '",';
$tableData .= '"' . $row['national_age_gender_demographics.males_per_100_females'] . '",';
$tableData .= '"' . $row['arizona_age_gender_demographics.both_pop'] . '",';
$tableData .= '"' . $row['arizona_age_gender_demographics.male_pop'] . '",';
$tableData .= '"' . $row['arizona_age_gender_demographics.female_pop'] . '",';
$tableData .= '"' . $row['arizona_age_gender_demographics.male_percent'] . '",';
$tableData .= '"' . $row['arizona_age_gender_demographics.female_percent'] . '",';
$tableData .= '"' . $row['arizona_age_gender_demographics.both_percent'] . '",';
$tableData .= '"' . $row['arizona_age_gender_demographics.males_per_100_females'] . '"]';
if ($i != $numRows - 1) {
$row = mysqli_fetch_array($result);
}
}
$tableData .= ']}';
echo $tableData;
?>
Does anyone know what is wrong here?

Firstly Steven is right, its better to use the json encode (or at least neater) to create your json, save you from the messy ifs and bracket business.
I would also recommend using mysqli_fetch_assoc rather than using mysqli_fetch_array, which as you currently specified should return both associative and numbered results (see here http://php.net/manual/en/mysqli-result.fetch-array.php), which probably messes up your results.
eg:
...
$row = mysqli_fetch_assoc($result);
$json_data = json_encode($row);
echo $json_data;
?>
Try that and see how you get on?

Related

Fetching all columns of Inner Join

I need to fetch all the columns in the two tables. But i cant seem to fetch the data is there anything wrong with my php or is it my javascript.
<?php
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, PATCH, PUT, DELETE, OPTIONS');
header('Access-Control-Allow-Headers: Origin, Content-Type, X-Auth-Token');
header("Content-Type: application/json; charset=UTF-8");
include("global.php");
$conn = new mysqli(server, dbuser, dbpw, db);
$userid = $_GET['userid'];
$result = $conn->query("SELECT * FROM profiles INNER JOIN StudentProfile ON profiles.userid = StudentProfile.userid");
$outp = "[";
while($rs = $result->fetch_array(MYSQLI_ASSOC)) {
if ($outp != "[") {$outp .= ",";}
$outp .= '{"userid":"' . $rs["userid"] . '",';
$outp .= '"parentname":"' . $rs["parentname"] . '",';
$outp .= '"profilepic":"' . $rs["profilepic"] . '",';
$outp .= '"contact":"' . $rs["contact"] . '",';
$outp .= '"address":"' . $rs["address"] . '",';
$outp .= '"studentid":"' . $rs["studentid"] . '",';
$outp .= '"studentname":"' . $rs["studentname"] . '",';
$outp .= '"sclass":"' . $rs["sclass"] . '"}';
$outp .= '"sprofilepic":"' . $rs["sprofilepic"] . '",';
}
$outp .="]";
$conn->close();
echo($outp);
?>
studentprofile
profiles
1. you can do it with fetch_all. for this you must have mysqlnd driver
$result = $conn->query("SELECT * FROM profiles INNER JOIN StudentProfile ON profiles.userid = StudentProfile.userid");
$output = $result->fetch_all(MYSQLI_ASSOC);
$jsonOutput = json_encode($output);
2. with loop
$result = $conn->query("SELECT * FROM profiles INNER JOIN StudentProfile ON profiles.userid = StudentProfile.userid");
$output = [];
while($rs = $result->fetch_array(MYSQLI_ASSOC)) {
$output[] = $rs;
}
$jsonOutput = json_encode($output);
Problem is with your JavaScript in your code ...
check out last 2 lines of code inside while loop
just replace
$outp .= '"sclass":"' . $rs["sclass"] . '"}';
$outp .= '"sprofilepic":"' . $rs["sprofilepic"] . '",';
With
$outp .= '"sclass":"' . $rs["sclass"] . '",';
$outp .= '"sprofilepic":"' . $rs["sprofilepic"] . '"},';

Unexpected token in JSON at position 43

Im trying to Fetch Data From a PHP Server Running MySQL. In my angular controller I do $http.get("dbconnection.php")
In my dbconnection.php I have this code which just Selects everything from the database and sends it back.
$conn = new mysqli......
$result = $conn->query("SELECT * FROM ...");
$outp = "";
while ($rs = $result->fetch_array(MYSQLI_ASSOC)) {
if ($outp != "") {
$outp .= ",";
}
$outp .= '{"id":"' . $rs["id"] . '",';
$outp .= '"name":"' . $rs["name"] . '",';
$outp .= '"price":"' . $rs["price"] . '"}';
$outp .= '"created":"' . $rs["created"] . '"}';
$outp .= '"img":"' . $rs["img"] . '"}';
}
$outp = '{"records":[' . $outp . ']}';
$conn->close();
echo $outp;
When I visit my site to see take a look at the Data under
Network Tab > XHR > dbconnection.php > Preview
I see the data but its weird formatted.
See picture of weird formatted json
I think thats the reason for why I get the
Unexpected token in JSON at position 43 ERROR
when I am trying to fetch the data.
To got well formatted JSON outputs, use json_encode function.
In your case :
$conn = new mysqli......
$result = $conn->query("SELECT * FROM ...");
$json = ["records" => []];
while ($rs = $result->fetch_array(MYSQLI_ASSOC)) {
$json["records"][] = $rs;
}
$conn->close();
echo json_encode($json);

how can i make a json with category in mysql?

i need to make a page which show all the items and when clicked bring me all the places where it is available.
i need to make this in mysql
app.controller('namesCtrl', function($scope) {
$scope.items = [
{name: 'item1', place: ['place1', 'place2']},
{name: 'item2', place: ['place2', 'place3']},
{name: 'item3', place: ['place1', 'place2', 'place3']},
{name: 'item4', place: ['place1']},
{name: 'item5', place: ['place1', 'place2']}
];
});
my php is
<?php
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
$conn = new mysqli("localhost", "user", "pass", "table");
$result = $conn->query("SELECT * FROM `especialidades`");
$outp = "";
while($rs = $result->fetch_array(MYSQLI_ASSOC)) {
if ($outp != "") {$outp .= ",";}
$outp .= '{"id":"' . $rs["id"] . '",';
$outp .= '"nombre_especialidad":"' . $rs["nombre_especialidad"] . '",';
$outp .= '"aguadilla":"' . $rs["aguadilla"] . '",';
$outp .= '"arecibo":"' . $rs["arecibo"] . '",';
$outp .= '"bayamon":"' . $rs["bayamon"] . '",';
$outp .= '"caguas":"' . $rs["caguas"] . '",';
$outp .= '"carolina":"' . $rs["carolina"] . '",';
$outp .= '"guayama":"' . $rs["guayama"] . '",';
$outp .= '"hato_rey":"' . $rs["hato_rey"] . '"}';
}
$outp ='{"especialidades":['.$outp.']}';
$conn->close();
echo($outp);
?>
im getting a lot of error.
how is the correct whay to make this in mysql and get it in json.
Your code should be like this
<?php
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
$conn = new mysqli("localhost", "user", "pass", "table");
$result = $conn->query("SELECT id, nombre_especialidad,aguadilla,arecibo, bayamon,caguas,carolina,guayama,hato_rey FROM `especialidades`");
$outp = "";
while($rs = $result->fetch_array(MYSQLI_ASSOC)) {
$outArray["especialidades"][] = $rs;
}
$conn->close();
$outp = json_encode($outArray);
echo $outp;
?>
Hope this will help you!!

mySQL for loop stops working after 31 row updates [Actually PHP related]

I have a form that uses a PHP for loop after it is submitted. The loop updates individual rows in the database one after the next based on the form data submitted. However, I've noticed that the loop stops working if there are more than 31 rows that need to be updated. It will update everything perfectly for the first 31 loops but then will not work after the 31st loop?
UPDATE: I've done some testing and it seems that the loop never finishes. It just refreshes the page in the browser instead of printing the results. What is causing this?
Is there a MYSQL query setting somewhere that is causing this?
Here is my loop's code:
for($i=1;$i<=$total_results2;$i++)
{
$strSQL = 'UPDATE timesheets_items SET ';
$strSQL .= 'time_1 = "' . convert_time($_POST['item_' . $i . '_time_1']) . '"';
$strSQL .= ', time_2 = "' . convert_time($_POST['item_' . $i . '_time_2']) . '"';
$strSQL .= ', time_3 = "' . convert_time($_POST['item_' . $i . '_time_3']) . '"';
$strSQL .= ', time_4 = "' . convert_time($_POST['item_' . $i . '_time_4']) . '"';
$strSQL .= ', time_5 = "' . convert_time($_POST['item_' . $i . '_time_5']) . '"';
$strSQL .= ', time_6 = "' . convert_time($_POST['item_' . $i . '_time_6']) . '"';
$strSQL .= ', time_7 = "' . convert_time($_POST['item_' . $i . '_time_7']) . '"';
$strSQL .= ', time_8 = "' . convert_time($_POST['item_' . $i . '_time_8']) . '"';
$strSQL .= ', time_9 = "' . convert_time($_POST['item_' . $i . '_time_9']) . '"';
$strSQL .= ', time_10 = "' . convert_time($_POST['item_' . $i . '_time_10']) . '"';
$strSQL .= ', time_11 = "' . convert_time($_POST['item_' . $i . '_time_11']) . '"';
$strSQL .= ', time_12 = "' . convert_time($_POST['item_' . $i . '_time_12']) . '"';
$strSQL .= ', time_13 = "' . convert_time($_POST['item_' . $i . '_time_13']) . '"';
$strSQL .= ', time_14 = "' . convert_time($_POST['item_' . $i . '_time_14']) . '"';
$strSQL .= ', time_total = "' . convert_time($_POST['item_' . $i . '_time_total']) . '"';
$strSQL .= ', ot_1 = "' . convert_time($_POST['item_' . $i . '_ot_1']) . '"';
$strSQL .= ', ot_2 = "' . convert_time($_POST['item_' . $i . '_ot_2']) . '"';
$strSQL .= ', ot_3 = "' . convert_time($_POST['item_' . $i . '_ot_3']) . '"';
$strSQL .= ', ot_4 = "' . convert_time($_POST['item_' . $i . '_ot_4']) .'"';
$strSQL .= ', ot_5 = "' . convert_time($_POST['item_' . $i . '_ot_5']) . '"';
$strSQL .= ', ot_6 = "' . convert_time($_POST['item_' . $i . '_ot_6']) . '"';
$strSQL .= ', ot_7 = "' . convert_time($_POST['item_' . $i . '_ot_7']) . '"';
$strSQL .= ', ot_8 = "' . convert_time($_POST['item_' . $i . '_ot_8']) . '"';
$strSQL .= ', ot_9 = "' . convert_time($_POST['item_' . $i . '_ot_9']) . '"';
$strSQL .= ', ot_10 = "' . convert_time($_POST['item_' . $i . '_ot_10']) . '"';
$strSQL .= ', ot_11 = "' . convert_time($_POST['item_' . $i . '_ot_11']) . '"';
$strSQL .= ', ot_12 = "' . convert_time($_POST['item_' . $i . '_ot_12']) . '"';
$strSQL .= ', ot_13 = "' . convert_time($_POST['item_' . $i . '_ot_13']) . '"';
$strSQL .= ', ot_14 = "' . convert_time($_POST['item_' . $i . '_ot_14']) . '"';
$strSQL .= ', ot_total = "' . convert_time($_POST['item_' . $i . '_ot_total']) . '"';
$strSQL .= 'WHERE week_start = "' . $week_start . '" AND employee_id = "' . $id . '" AND project_number = "' . $_POST['item_' . $i . '_project_number'] .'" AND task = "' . $_POST['item_' . $i . '_task'] .'"';
mysql_query($strSQL);
}
I have now solved the issue ! The problem was caused by my version of PHP (5.3) and the amount of input variables allowed by PHP on a form.
The problem ended up not being MySQL related at all. The bug found was limiting how many form variables were taken in by PHP thus not allowing MySQL to ever get to see those variables when it came time to run the repeated queries loop.
To resolve the issue, I had to update to PHP (5.4 or greater) and then set the "max_input_vars" setting to 3000. (The default setting only allows 1000.)
I hope this helps anyone who ever comes across this same problem.

receiving newline inside a json object

i am trying to bring a set of texts from a PostgreSQL database (field type is text) with ajax into my webpage. The problem i encouter is the newline, it works great when there is no newlines into the text in database, but when i use new lines in the text inside database, the json doesnt give me the data it stored.
function selectCalendarEvents(user_id, event_datestart, event_datestop, callback) {
var request;
if(window.XMLHttpRequest)
request = new XMLHttpRequest();
else
request = new ActiveXObject("Microsoft.XMLHTTP");
request.onreadystatechange = function() {
if (request.readyState == 4 && request.status == 200) {
if(request.responseText.substr(0, 6) == "error ")
alert(errorName[request.responseText.substr(6)]);
else {
jsonCalendarEvents = $.parseJSON(request.responseText);
selectEvents(user_id, event_datestart, event_datestop, callback);
}
}
}
request.open("GET", "php/calendar.php?action=selectCalendarEvents&user_id=" + user_id + "&event_datestart=" + event_datestart + "&event_datestop=" + event_datestop, true);
request.setRequestHeader("If-Modified-Since", "Sat, 1 Jan 2000 00:00:00 GMT");
request.send();
}
this is my javascript function which requests the data set
if($action == "selectCalendarEvents") {
$user_id = $_GET["user_id"];
$event_datestart = "'" . $_GET["event_datestart"] . "'";
$event_datestop = "'" . $_GET["event_datestop"] . "'";
require_once("connect.php");
$query = "SELECT event_id, event_name, event_datestart, event_datestop, event_timestart, event_timestop, calendar_events.calendar_group, calendar_color, event_info FROM calendar_events LEFT JOIN calendar_calendars ON calendar_events.calendar_group = calendar_calendars.calendar_group WHERE user_id = " . $user_id . " AND calendar_show = true AND event_datestart <= ". $event_datestop . " AND event_datestop >= " . $event_datestart;
$result = pg_query($connect, $query);
if(!$result)
die("error 1"); // query error
$comma = '';
$json = '{"events":[';
while ($row = pg_fetch_row($result)) {
$json .= $comma . '{';
$json .= '"event_id":"' . $row[0] . '",';
$json .= '"event_name":"' . $row[1] . '",';
$json .= '"event_datestart":"' . $row[2] . '",';
$json .= '"event_datestop":"' . $row[3] . '",';
$json .= '"event_timestart":"' . $row[4] . '",';
$json .= '"event_timestop":"' . $row[5] . '",';
$json .= '"calendar_group":"' . $row[6] . '",';
$json .= '"calendar_color":"' . $row[7] . '",';
$json .= '"event_info":"' . $row[8] . '"';
$json .= '}';
$comma = ',';
}
$json .= ']}';
echo $json;
}
this is my php which returns the dataset. If row[8] aka event_info stores text with newlines in it .. when i try to populate my calendar with the events, it seems the json doesnt store any data in it or smt like that.
I found out that i should replace \r\n with <br/> and it will work. im using like this replace(/\r\n/g, "<br/>") when i give the response string to json
jsonCalendarEvents = $.parseJSON(request.responseText.replace(/\r\n/g, "<br/>"));

Categories