Return result from php to json file - php

I have created API from my DB and the result appears in a PHP file, so the question is how I can read this result in a .json file?
<?php
$con = mysqli_connect("localhost","root","Password##","Mydb");
$response = array();
if($con){
$sql = "select * from limit_order";
$result = mysqli_query($con,$sql);
if($result){
header("Content-Type: JSON");
$i=0;
while($row = mysqli_fetch_assoc($result)){
$response[$i]['order_type'] = $row ['order_type'];
$response[$i]['from'] = $row ['from'];
$response[$i]['to'] = $row ['to'];
$response[$i]['quantity'] = $row ['quantity'];
$response[$i]['limit_price'] = $row ['limit_price'];
$response[$i]['created_at'] = $row ['created_at'];
$response[$i]['updated_at'] = $row ['updated_at'];
$response[$i]['status'] = $row ['status'];
$i++;
}
echo json_encode($response,JSON_PRETTY_PRINT);
}
}
else{
echo "Database connection failed";
}
?>

Related

How to format a json response in php

I am new to php and am trying to return a json response in a particular structure. Here is what I have tried so far:
$response = array();
if ($con) {
$sql = "select * from admission_view";
$result = mysqli_query($con, $sql);
if ($result) {
$x = 0;
while ($row = mysqli_fetch_assoc($result)) {
$response[$x]['id'] = $row['id'];
$response[$x]['name'] = $row['name'];
$response[$x]['isActive'] = $row['isActive'];
$response[$x]['branchId'] = $row['branchId'];
$response[$x]['branch'] = $row['branch'];
$response[$x]['customerGroupId'] = $row['customerGroupId'];
$response[$x]['customerGroup'] = $row['customerGroup'];
$response[$x]['orderNo'] = $row['orderNo'];
$x++;
}
echo json_encode($response, JSON_PRETTY_PRINT);
}
} else {
echo "Connection error";
}
The code above returns this response:
However, instead of returning for example "branchId" and "branch" as individual properties, I want to pass their values inside a branchObject such that branch.id == "branchId" and branch.name == "branch".I mean, How may I return the response in the following structure:
And Here is how my database looks like:
How can I achieve this?
You ask for stuff that we are unsure if db result returns but as nice_dev pointed out, you need something like this:
$response = [];
if ($con) {
$sql = "select * from admission_view";
$result = mysqli_query($con, $sql);
if ($result) {
$x = 0;
while ($row = mysqli_fetch_assoc($result)) {
$response[$x]['id'] = $row['id'];
$response[$x]['name'] = $row['name'];
$response[$x]['isActive'] = $row['isActive'];
$response[$x]['branch']['id'] = $row['branchId'];
$response[$x]['branch']['name'] = $row['branch'];
$response[$x]['customerGroup']['id'] = $row['customerGroupId'];
$response[$x]['customerGroup']['name'] = $row['customerGroup'];
$response[$x]['customerGroup']['orderNo'] = $row['orderNo'];
$x++;
}
echo json_encode($response, JSON_PRETTY_PRINT);
}
} else {
echo "Connection error";
}

JSON encoding not working

Here is my code to encode data in JSON format, but it doesn't work. The result is []. Where is my mistake?
<?php
$conn = new mysqli('localhost','root','','project');
$data =array();
if(!empty($_GET['masp'])){
$masp =$_GET['masp'];
$sql ="SELECT *FROM sanpham WHERE masp='$masp'";
$result = mysqli_query($conn,$sql);
if($result){
while($r = mysqli_fetch_assoc($result)){
$r['masp'] =$data['masp'];
$r['loai'] =$data['loai'];
$r['hangsx']=$data['hangsx'];
$r['tensp']=$data['tensp'];
$r['img']=$data['img'];
$r['gia']=$data['gia'];
$r['nx']=$data['nx'];
}
}
}
print json_encode($data);
?>
You are setting your variables wrong.
In every while cycle you get a new $r variable that you want to add to your $data variable.
$conn = new mysqli('localhost', 'root', '', 'project');
$data = array();
if (!empty($_GET['masp'])) {
$masp = $_GET['masp'];
$sql = "SELECT *FROM sanpham WHERE masp='$masp'";
$result = mysqli_query($conn, $sql);
$i = 0;
if ($result) {
while ($r = mysqli_fetch_assoc($result)) {
$data[$i]['masp'] = $r['masp'];
$data[$i]['loai'] = $r['loai'];
$data[$i]['hangsx'] = $r['hangsx']];
$data[$i]['tensp'] = $r['tensp'];
$data[$i]['img'] = $r['img'];
$data[$i]['gia'] = $r['gia'];
$data[$i]['nx'] = $r['nx'];
$i += 1;
}
}
}
print json_encode($data);
You make mistake. You should swap variable data with r inner loop, but probably than also will works unpropely. write in while loop $data [] = $r;

MySQL Query Returns 0 When Running Multirowed Response Query

When I run the following code In PHP
$connect = mysqli_connect("localhost", "root", "dbpass", "db");
function csvfromarray($array) {
$result = $array[0]+","+$array[1];
return $result;
}
$query = mysqli_query($connect, "SELECT * FROM dbtable");
$row = mysqli_fetch_assoc($query);
$data = array();
$i = 0;
while($row = mysqli_fetch_assoc($query)) {
$data[$i] = $row['last'];
$i++;
}
$csv = csvfromarray($data);
echo $csv;
mysqli_close();
I end up getting an echoed response of "0" when I should be returning "lname1,lname2".
All of chris85's stuff is correct...
Here's a tidy up:
$query=mysqli_query($connect,"SELECT `last` FROM dbtable");
$data=array();
while($row=mysqli_fetch_assoc($query)) {
$data[]=$row['last']; // push into array
}
echo implode(',',$data); // echo comma-separated values
mysqli_close();

multiple data queries php ajax mysql not working

<?php
$link = mysql_connect("localhost:8889", "root", "root", "Testdata");
if(!link) {echo "Database connexion not possible"; exit;}
$id = $_GET('testeId');
$jsonData = [];
The first query is working:
$jsonData['table1'] = [];
$sql = "SELECT * FROM registerData WHERE testeId = $id";
if ($result = mysqli_query($link, $sql){
while ($row = mysqli_fetch_assoc($result)) {
$jsonData['table1'][] = $row;
}
}
else {
$jsonData['table1'][] = "Error 1";
}
This second query is not working:
$jsonData['table2'] = [];
$sql = "SELECT * FROM factsData WHERE factsId = $id";
if ($result = mysqli_query($link, $sql){
while ($row = mysqli_fetch_assoc($result)) {
$jsonData['table2'][] = $row;
}
}
else {
$jsonData['table2'][] = "Error 2";
}
mysqli_free_result($result);
echo json_encode($jsonData);
The jsonData string only includes the 1st query:
mysqli_close($link);
The responseText of the ajax request only has data from "table1" array

json formatting_adding a tag to it

here is the PHP file that im using to generate the JSON with:
<?
$databasehost = "wbw.com";
$databasename = "wtest";
$databaseusername ="w";
$databasepassword = "123";
$query = "SELECT * FROM `and` LIMIT 0 , 30";
$con = mysql_connect($databasehost,$databaseusername,$databasepassword) or die(mysql_error());
mysql_select_db($databasename) or die(mysql_error());
$sth = mysql_query($query);
if (mysql_errno()) {
header("HTTP/1.1 500 Internal Server Error");
echo $query.'\n';
echo mysql_error();
}
else
{
$rows = array();
while($r = mysql_fetch_assoc($sth)) {
$rows[] = $r;
}
print json_encode($rows);
}
?>
The problem with it is that it generates a result like this:
[{"Reg_user_name":"nn","Username":"ns","Device
Code":"2366c84dead","HTTP":"https://api.ee.com/v1//306ad73427e262r9","Device
Name":"office"},{"Reg_user_name":"nn","Username":"nn","Device
Code":"2366c84dead","HTTP":"https://api.ee.com/v1/e/306ad73427e262e7","Device
Name":"LAB lighting"}]
BUT in order to use the JSONobject and get the elements in it I need to give JSON like follows:
["Information":{"Reg_user_name":"nn","Username":"ns","Device
Code":"2366c84dead","HTTP":"https://api.ee.com/v1//306ad73427e262r9","Device
Name":"office"},{"Reg_user_name":"nn","Username":"nn","Device
Code":"2366c84dead","HTTP":"https://api.ee.com/v1/e/306ad73427e262e7","Device
Name":"LAB lighting"}]
I want to know that what I have to add in the PHP file to get that data with the added "information:" tag to it automatically using the above PHP file.
If you only want one index, you can change this
$rows = array();
while($r = mysql_fetch_assoc($sth)) {
$rows[] = $r;
}
print json_encode($rows);
into this
$rows = array();
while($r = mysql_fetch_assoc($sth)) {
$rows[] = $r;
}
$json = array(
'information' => $rows,
);
print json_encode($json);
just add string index to the array the json encoder will automatically convert it
check this
while($r = mysql_fetch_assoc($sth))
{
$rows['information'][] = $r;
}
echo json_encode($rows);

Categories