Converting SQL to JSON and keeping the null values? - php

The issue:
I'm converting some SQL tables into JSON format and I have some null values which aren't being presented in the format I would like. When there's a null value in my table, it turns into " " when converted to JSON, but I want it to just say null instead of double quotation marks.
The code:
$conn = new mysqli($servername, $username, $password, $dbname);
$result = $conn->query("SELECT firstname, middlename, lastname FROM nametable");
$outp = "[";
while($rs = $result->fetch_array(MYSQLI_ASSOC)) {
if ($outp != "[") {$outp .= ",";}
$outp .= '{"firstname":"' . $rs["firstname"] . '",';
$outp .= '"middlename":"' . $rs["middlename"] . '",';
$outp .= '"lastname":"' . $rs["lastname"] . '"}';
}
$outp .="]";
$conn->close();
echo($outp);
The JSON format that I am getting:
[
{"firstname":"John", "middlename": "Timothy", "lastname":"Doe"} ,
{"firstname":"Mary", "middlename":"", "lastname":"Jane"}
]
The JSON format that I want: (the different part is the null after middlename)
[
{"firstname":"John", "middlename":"Timothy", "lastname":"Doe"} ,
{"firstname":"Mary", "middlename": null, "lastname":"Jane"}
]
Edit: I don't want this: (because null will be treated as a string)
[
{"firstname":"John", "middlename":"Timothy", "lastname":"Doe"} ,
{"firstname":"Mary", "middlename":"null", "lastname":"Jane"}
]
What I have tried:
I tried editing my query to
SELECT firstname, middlename, lastname
FROM nametable
WHERE (nametable->>'middlename') is null
but it gets buggy and won't run.
I've also tried
SELECT firstname, middlename, lastname
FROM nametable
FOR JSON AUTO, INCLUDE_NULL_VALUES
but it also won't run.
Final edit: I played around with everyone's suggestions and I made it work with an if/else statement in the middle:
$conn = new mysqli($servername, $username, $password, $dbname);
$result = $conn->query("SELECT firstname, middlename, lastname FROM nametable");
$outp = "[";
while($rs = $result->fetch_array(MYSQLI_ASSOC)) {
if ($outp != "[") {$outp .= ",";}
$outp .= '{"firstname":"' . $rs["firstname"] . '",';
if (is_null($rs['middlename']) == true)
$outp .= '"middlename":null,';
else
$outp .= '"middlename":"' . $rs["middlename"] . '",';
$outp .= '"lastname":"' . $rs["lastname"] . '"}';
}
$outp .="]";
$conn->close();
echo($outp);

Convert your null field to string if you want to want JSON to print NULL instead of blank
while($rs = $result->fetch_array(MYSQLI_ASSOC)) {
if ($outp != "[") {$outp .= ",";}
$outp .= '{"firstname":"'. $rs["firstname"] == null ?"null":$rs["firstname"]. '",';
$outp .= '"middlename":"'. $rs["middlename"] == null ?"null":$rs["middlename"]. '",';
$outp .= '"lastname":"'. $rs["lastname"] == null ?"null":$rs["lastname"]. '"}';
}

Since having null inside the database causes problem, why not store "null" string instead, and when creating the JSON format, use conditional operator to select the real null .This is a sample, how your code suppose look like:
$outp = "[";
while($rs = $result->fetch_array(MYSQLI_ASSOC)) {
if ($outp != "[") {$outp .= ",";}
$outp .= '{"firstname":"' . $rs["firstname"] == "null" ? null : $rs["firstname"].'",';
$outp .= '"middlename":"' . $rs["middlename"] == "null" ? null : $rs["middlename"].'",';
$outp .= '"lastname":"' . $rs["lastname"] == "null" ? null : $rs["lastname"].'"}';
}
$outp .="]";

Here is an example with some dummy data
$db_results = array(
array('fname'=>'john', 'lname'=>'doe', 'property'=>''),
array('fname'=>'john', 'lname'=>'doe', 'property'=>''),
array('fname'=>'john', 'lname'=>'doe', 'property'=>NULL)
);
$output='';
$rowStr = '';
foreach($db_results as $i=>$row) {
$rowStr="{";
$rowStr.= '"fname":'.((is_null($row['fname']) || empty($row['fname'])) ? 'null' : '"'.$row['fname'].'"');
$rowStr.= ',"lname":'.((is_null($row['lname']) || empty($row['lname'])) ? 'null' : '"'.$row['lname'].'"');
$rowStr.= ',"property":'.((is_null($row['property']) || empty($row['property'])) ? 'null' : '"'.$row['property'].'"');
$rowStr.='}'; //add a comma here when a condition is met
$output.= $rowStr;
}
echo '['.$output.']';

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!!

Web services login page in PHP

if($_SERVER['REQUEST_METHOD'] == "GET"){
// Get post data`
$username = isset($_POST['username']) ? mysql_real_escape_string($_POST['username']) : "";
$password = isset($_POST['password']) ? mysql_real_escape_string($_POST['password']) : "";
//$status = 1;
// Here we set by default status In-active.
// Save data into database
//$resultarray = array();
$query = "select admin_user , admin_password from doc_admin where admin_user = '".$username."' and admin_password = '".$password."'";
$insert = mysql_query($query) or die (mysql_error());
if (mysql_num_rows($insert)>0)
{
while ($rs = mysql_fetch_assoc($insert))
{
$outp .= '{"id":"' . $rs["id"] . '",';
$outp .= '"admin_user":"' . $rs["admin_user"]. '",' ;
$outp .= '"admin_password":"' . base64_encode($rs["admin_password"]). '",' ;
$outp .= '"admin_status":"' . $rs["admin_status"] . '",';
$outp .= '"admin_data":"' . $rs["admin_data"] . '",';
$outp .= '"admin_calender":"' . $rs["admin_calender"] . '",';
$outp .= '"admin_suggestion":"' . $rs["admin_suggestion"] . '",';
$outp .= '"admin_agenda":"'. $rs["admin_agenda"] . '"}';
// array_push($resultarray,$result);
}
}
}
mysql_close($conn);
/* JSON Response */
header("Content-type: application/json");
echo json_encode($outp);
I want to show data of logged in person but it showing null value, but if it get null value in database it showing result in JSON format.
<?php
if($_SERVER['REQUEST_METHOD'] == "GET"){
// Get post data`
$username = isset($_POST['username']) ? mysql_real_escape_string($_POST['username']) : "";
$password = isset($_POST['password']) ? mysql_real_escape_string($_POST['password']) : "";
//$status = 1;
// Here we set by default status In-active.
// Save data into database
//$resultarray = array();
$query = "select * from doc_admin where admin_user = '".$username."' and admin_password = '".$password."'";
$insert = mysql_query($query) or die (mysql_error());
if (mysql_num_rows($insert)>0)
{
$rs = mysql_fetch_assoc($insert);
$outp = json_encode($rs);
} else {
$outp = json_encode(array());
}
}
mysql_close($conn);
/* JSON Response */
header("Content-type: application/json");
echo json_encode($outp);
?>

JSON formatting errors for two files

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?

Categories