JSON to MySql using PHP - php

Hi and I need your help
I'm working on a project for class, I'm looking to write from JSON to a MySql database.
The JSON looks like this
{
"offset": 0,
"results": [
{
"aq1": 22,
"aq3": 27,
"aq2": 27,
"ateam/_source": "/nba/teams/page/NO/new-orleans-pelicans",
"aq4": 24,
"hqf/_source": "108",
"hq2": 27,
"hq1": 22,
"hq4": 36,
"hq3": 23,
"aqf/_source": "100",
"ateam/_text": "New Orleans",
"aq3/_source": "27",
"hq4/_source": "36",
"hteam": "http://www.cbssports.com/nba/teams/page/BOS/boston-celtics",
"aq2/_source": "27",
"hteam/_text": "Boston",
"aq1/_source": "22",
"hteam/_source": "/nba/teams/page/BOS/boston-celtics",
"ateam": "http://www.cbssports.com/nba/teams/page/NO/new-orleans-pelicans",
"aqf": 100,
"hq1/_source": "22",
"hq3/_source": "23",
"hq2/_source": "27",
"hqf": 108,
"aq4/_source": "24"
},
],
"cookies": [],
"connectorVersionGuid": "dgsadjgofsjkgkfsmghjfhf",
"connectorGuid": "fbcjsdbgfjdjgkf",
"pageUrl": "http://xsftbfbjjjsfaf.com/"
}
and my php reads like this
<?php
$server = "localhost";
$username = "lies";
$password = "madeup";
$database = "dgjsfdgjv";
mysql_connect($server,$username,$password) or die("Failed");
mysql_select_db($database) or die("Database Failed");
$url = "https://api.import.io/store/data/jjjjj-ec0f-4553-bda5-def61ca1756c/_query?input/webpage/url=http%3A%2F%2Fwww.jjjjj.com%2Fnba%2Fscoreboard%2F20150111&_user=f1508a78-05c5-4487-9219-51a990391329&_apikey=aLZu2wmRCvUlBwopi%2F6Kj%2F4wnscvZRh7DYQf80LE2e3hL22rtAp0nJ3lujy10cyx9JC9Ed73xb3zGp3aArhYDQ%3D%3D";
$string = file_get_contents($url);
$arr = json_decode($string, true);
foreach($arr as $item){
$aq1 = $item['aq1'];
$aq3 = $item['aq3'];
$aq2 = $item['aq2'];
$ateam/_source = $item['aqeam/_source'];
$aq4 =$item['aq4'];
$hqf/_source =$item['aqf/_source'];
$hq2 =$item['aq2'];
$hq1 =$item['aq1'];
$hq4 =$item['aq4'];
$hq3 =$item['aq3'];
$aqf/_source =$item['aqf/_source'];
$ateam/_text =$item['aqeam/_text'];
$aq3/_source =$item['aq3/_source'];
$hq4/_source =$item['aq4/_source'];
$hteam =$item['aqeam'];
$aq2/_source =$item['aq2/_source'];
$hteam/_text =$item['aqeam/_text'];
$aq1/_source =$item['aq1/_source'];
$hteam/_source =$item['aqeam/_source'];
$ateam =$item['aqeam'];
$aqf =$item['aqf'];
$hq1/_source =$item['aq1/_source'];
$hq3/_source =$item['aq3/_source'];
$hq2/_source =$item['aq2/_source'];
$hqf =$item['aqf'];
$aq4/_source =$item['aq4/_source'];
mysql_query("INSERT INTO createdb (aq1,aq3,aq2,ateam/_source,aq4,hqf/_source,hq2,hq1,hq4,hq3,aqf/_source,ateam/_text,aq3/_source,hq4/_source,hteam,aq2/_source, hteam/_text,aq1/_source,hteam/_source,ateam,aqf,hq1/_source,hq3/_source,hq2/_source,hqf,aq4/_source) VALUES('$aq1','$aq3','$aq2','$ateam/_source','$aq4','$hqf/_source','$hq2','$hq1','$hq4','$hq3','$aqf/_source','$ateam/_text', '$aq3/_source','$hq4/_source','$hteam','$aq2/_source','$hteam/_text','$aq1/_source','$hteam/_source','$ateam','$aqf','$hq1/_source','$hq3/_source','$hq2/_source','$hqf','$aq4/_source')") or die ("Failed");
}
I dont trigger any of the error messages to appear but no data ends up in the database. What am I doing wrong? Is it the php code reading the json string correctly???

By carefully, looking at your problem , I have realized that , the problem was inside foreach() Loop. It should be
foreach($arr as $item){
echo $aq1 = $item[0]['aq1']; # note that [0] here
echo $aq3 = $item[0]['aq3'];
#...........Rest of Loop
}
And also rename variables like this $aqf/_source to $aqf_source , and so on .

I got it working.
foreach ($phpArray['results'] as $key => $value) {
// This is to make the data to be saved into the database
foreach ($value as $k => $v) {
$aq1 = $value['aq1'];
$aq3 = $value['aq3'];
$aq2 = $value['aq2'];
$ateam_source = $value['ateam/_source'];
$aq4 =$value['aq4'];
$hqf_source =$value['hqf/_source'];
$hq2 =$value['aq2'];
$hq1 =$value['aq1'];
$hq4 =$value['aq4'];
$hq3 =$value['aq3'];
$aqf_source =$value['aqf/_source'];
$ateam_text =$value['ateam/_text'];
$aq3_source =$value['aq3/_source'];
$hq4_source =$value['hq4/_source'];
$hteam =$value['hteam'];
$aq2_source =$value['aq2/_source'];
$hteam_text =$value['hteam/_text'];
$aq1_source =$value['aq1/_source'];
$hteam_source =$value['hteam/_source'];
$ateam =$value['ateam'];
$aqf =$value['aqf'];
$hq1_source =$value['hq1/_source'];
$hq3_source =$value['hq3/_source'];
$hq2_source =$value['hq2/_source'];
$hqf =$value['hqf'];
$aq4_source =$value['hq4/_source'];
}

Related

PHP json_encode 2 arrays

I need to create a json with two (or more) arrays that can have other arrays inside. I did several tests, but I can never get a correct output. This is the output I would like to get to:
{
"servizi" : [
{"id": 1, "nomeservizio": "Menu","value": 1},
{"id": 2, "nomeservizio": "Prenotazione","value": 0}
],
"pietanze" : [
{"tipopietanza": "PANINI","PANINI" : [
{"id": 1, "nomepietanza": "Royal avec du fromage", "prezzo": 5.50, "ingredienti": "Hamburger di manzo, cetriolini sott'aceto, cheddar, cipolle, senape, ketchup"},
{"id": 2, "nomepietanza": "Big Belly Burger", "prezzo": 5.50, "ingredienti": "Hamburger di manzo, cipolla,senape, salsa worchester, prezzemolo, aglio, peperone, lattuga"}
]},
{"tipopietanza": "CONTORNI E STUZZICHINI", "CONTORNI E STUZZICHINI" :[
{"id":1, "nomepietanza": "Caprese", "prezzo": 4.00, "ingredienti": "Mozzarella"},
{"id":2, "nomepietanza": "Insalata", "prezzo": 3.50, "ingredienti": "Insalata"}
]}
]
}
I want to take the data from a database and this is the first part of the output where I get "servizi", now I want to get "pietanze" and put it like in the json I showed
<?php
$user = 'root';
$pass = '';
$db = 'taurosdb';
$connect = mysqli_connect("localhost", "root", "", "taurosdb");
$sql = "-query that takes me the "servizi"-";
$result = mysqli_query($connect, $sql);
$json_array = array();
while($row = mysqli_fetch_assoc($result))
{
$json_array[] = $row;
}
echo json_encode(array('servizi' => $json_array));
?>
Just make your array a variable so you can work with it. Instead of this:
echo json_encode(array('servizi' => $json_array));
You can say:
$my_big_array = ["servizi" => $json_array];
Then later on:
$my_big_array["pietanze"] = $some_other_data;
Then at the end you can output the JSON. Don't forget to set the Content-Type header.
header("Content-Type: application/json");
echo json_encode($my_big_array);

I have json array data which needs to be fetched in a foreach loop for capacitor and DG using php

I want to fetch the below json data using php:
$str ='{
"site_Id": "1",
"site_Name": "Guajarat",
"site_Address": "Emami",
"site_StartDate": "10 / November / 2017 To 11 / November / 2017",
"Capacitor": [
{
"checkList_Id_PointNo": "1",
"checkList_Name": "APFC Panel doors and covers properly closed",
"checkList_Status": "Not OK",
"checkList_Remark": "Remark 1",
"checkList_Photo": "11Capacitor BankCapacitor Name1",
"fk_equipmentType": "Capacitor Bank"
},
{
"checkList_Id_PointNo": "2",
"checkList_Name": "APFC Panel door locks working properly.",
"checkList_Status": "Not OK",
"checkList_Remark": "Remark ",
"checkList_Photo": "11Capacitor BankCapacitor Name2",
"fk_equipmentType": "Capacitor Bank"
}
],
"DG": [
{
"checkList_Id_PointNo": "1",
"checkList_Name": "Substation earthing layout clearly making the position or earthing pits with identification number and the route of earthing lead / strip",
"checkList_Status": "Not OK",
"checkList_Remark": "Remark gg",
"checkList_Photo": "12EarthingDG Earthing1",
"fk_equipmentType": "Earthing"
},
{
"checkList_Id_PointNo": "2",
"checkList_Name": "All earhting pits should have identification number as indicated in earthing layout written over them with permanent paint",
"checkList_Status": "Not OK",
"checkList_Remark": "Remark gg",
"checkList_Photo": "12EarthingDG Earthing2",
"fk_equipmentType": "Earthing"
}
]
}';
Until now i have only coded for the Capacitor but i also need to fetch both Capacitor and DG from the same loop. Below is the foreach loop from which i have only fetch data of Capacitor but in that loop i also need to fetch DG at the same time.
foreach ($json['Capacitor'] as $field => $value) {
$id = $json['Capacitor'][$field]['checkList_Id_PointNo'];
$name = $json['Capacitor'][$field]['checkList_Name'];
$status = $json['Capacitor'][$field]['checkList_Status'];
$remark = $json['Capacitor'][$field]['checkList_Remark'];
$photo = $json['Capacitor'][$field]['checkList_Photo'];
echo $id.'<br>'.$name.'<br>'.$status.'<br>'.$remark.'<br>'.$photo.'<br><br>';
}
You can do it like below:-
<?php
$json = json_decode($str,true);
print_r($json);
foreach ($json as $value) {
if(is_array($value)){
foreach($value as $val){
$id = $val['checkList_Id_PointNo'];
$name = $val['checkList_Name'];
$status = $val['checkList_Status'];
$remark = $val['checkList_Remark'];
$photo = $val['checkList_Photo'];
echo "INSERT INTO table (id, name, status, remark, photo) VALUES ('$id', '$name', '$status','$remark','$photo')".PHP_EOL; // i have printed it so that you can see that it's printing perfectly.
}
}
}
Output:- https://eval.in/898497

Parsing JSON data and inserting to MySQL

So basically I want to parse a JSON file in PHP and insert the data into specific tables/columns. At the moment I have a working script but requires me to modify the JSON largely until it works. However, it won't end up working because the JSON data I'm collecting can vary in size having more data rows.
The JSON file is structured differently to most I have seen. Maybe because its output data from sensor units. I want to insert the data and the serial number into the data table, and have an error_log table where I can store the serial number and error messages as strings. How can I achieve this?
JSON File:
{
"device": {
"sn": 5165654,
"name": "FDI_AWS_DEMO",
"v": "2.7B3"
},
"channels": [
{
"code": "RH",
"name": "Relative Humidity",
"unit": "%"
},
{
"code": "AT",
"name": "Air Temperature",
"unit": "C"
},
{
"code": "MINVi",
"name": "Min voltage",
"unit": "V"
},
{
"code": "PTi",
"name": "Processor temperature",
"unit": "C"
},
{
"code": "SDB",
"name": "Network signal dB",
"unit": "dB"
},
{
"code": "LWS",
"name": "Leaf Wetness",
"unit": "%"
},
{
"code": "WSAV",
"name": "Wind Speed Avg",
"unit": "km/h"
},
{
"code": "WSMX",
"name": "Wind Speed Max",
"unit": "km/h"
},
{
"code": "WSMN",
"name": "Wind Speed Min",
"unit": "km/h"
},
{
"code": "PR_TOT",
"name": "PR Tot",
"unit": "mm"
},
{
"code": "RAIN",
"name": "Rain",
"unit": "mm"
},
{
"code": "FDI",
"name": "fdi",
"unit": "Unit"
},
{
"code": "DT",
"name": "Delta-T",
"unit": "C"
},
{
"code": "LAT",
"name": "Latitude",
"unit": "deg"
},
{
"code": "LON",
"name": "Longitude",
"unit": "deg"
},
{
"code": "WD",
"name": "Wind Direction",
"unit": "Degrees"
},
{
"code": "P1",
"name": "Par1",
"unit": ""
},
{
"code": "AVGCi",
"name": "Average Current",
"unit": "mA"
},
{}
],
"data": [
{
"$ts": 170801164400,
"$msg": "SD_FAIL;1"
},
{
"$ts": 170801170000,
"$msg": "WDT;WV01"
},
{
"$ts": 170801170000,
"$msg": "WDT;SDI12"
},
{
"$ts": 170801170000,
"$msg": "WDT;LWS"
},
{
"$ts": 170801170000,
"RH": 67.15,
"AT": 12.87,
"MINVi": 3.81,
"PTi": 23.4,
"LWS": "0*T",
"WSAV": 0,
"WSMX": 0,
"WSMN": 0,
"PR_TOT": 156,
"RAIN": 0,
"FDI": 0.239,
"DT": 2.881,
"WD": "0*T",
"P1": "0*T",
"AVGCi": 175
},
{}
]
}
PHP Code:
<?php
//connect to mysql db
$myConnection= mysqli_connect("localhost","root","******", "ii") or die ("could not connect to mysql");
//read the json file contents
$jsondata = file_get_contents('test.json');
//convert json object to php associative array
$data = json_decode($jsondata, true);
$id = $data['device']['sn'];
$ts = $data['data']['$ts'];
$RH = $data['data']['RH'];
$AT = $data['data']['AT'];
$MINVi = $data['data']['MINVi'];
$PTi = $data['data']['PTi'];
$SDB = $data['data']['SDB'];
$LWS = $data['data']['LWS'];
$WSAV = $data['data']['WSAV'];
$WSMX = $data['data']['WSMX'];
$WSMN = $data['data']['WSMN'];
$PR_TOT = $data['data']['PR_TOT'];
$RAIN = $data['data']['RAIN'];
$FDI = $data['data']['FDI'];
$DT = $data['data']['DT'];
$LAT = $data['data']['LAT'];
$LON = $data['data']['LON'];
$WD = $data['data']['WD'];
$P1 = $data['data']['P1'];
$AVGCi = $data['data']['AVGCi'];
//insert into mysql table
$sql = "INSERT INTO test(sn, date, RH, AT, MINVi, PTi, SDB, LWS, WSAV, WSMX, WSMN, PR_TOT, RAIN, FDI, DT, LAT, LON, WD, P1, AVGCi)
VALUES('$id', '$ts', '$RH','$AT', '$MINVi', '$PTi', '$SDB', '$LWS', '$WSAV', '$WSMX', '$WSMN', '$PR_TOT', '$RAIN', '$FDI', '$DT', '$LAT', '$LON', '$WD', '$P1', '$AVGCi')";
$query=mysqli_query($myConnection, $sql) or die(mysqli_error($myConnection));
?>
Tables Test data table and error_log table
JSON array var_dump - JSON var dump
Any help would be great
(After i get the general gist i want to incorporate PDO)
Do not convert json to associative array blindly. It creates more problems.
For accessing properties containing special characters or reserved
words use placeholders like $data->{'$ts'}
Loop through arrays and objects if needed.
Adding an auto increment id column to tables helps to store data
for one device.
It is a good idea to add time to error_log table as well
Tested bellow short version of your original question and it works.
<?php
$_user = 'root';
$_password= 'root';
$_db = 'localtest';
$_host = 'localhost';
$_port = 3306;
$con = new mysqli($_host, $_user, $_password, $_db) or die(mysql_error);
//read the json file contents
$jsondata = file_get_contents('test.json');
//do not convert to array
$json = json_decode($jsondata);
$id = $json->device->sn;
foreach($json->data as $key => $data){
if(empty($data) || !isset($data->{'$ts'})){
continue;
}
if (isset($data->{'$msg'})){
$msg = $data->{'$msg'};
$time = $data->{'$ts'};
$sql="INSERT into error_log (sn, time, MSG) VALUES (?,?,?); ";
$stmt = $con-> prepare($sql);
$stmt -> bind_param("iss", $id,$time, $msg);
$stmt -> execute();
}else{
$time = (isset($data->{'$ts'}))? $data->{'$ts'}:'';
$RH = (isset($data->RH))? $data->RH:'';
$AT = (isset($data->AT))? $data->AT:'';
$MINVi = (isset($data->MINVi))? $data->MINVi:'';
//insert into mysql table
$sql="INSERT into test (sn, date, RH, AT, MINVi) VALUES (?,?,?,?,?); ";
$stmt = $con-> prepare($sql);
$stmt -> bind_param("issss", $id,$time,$RH,$AT,$MINVi);
$stmt -> execute();
}
}
mysqli_close($con);
?>
looks like the json decode is turning the array into one that is object based...run the $data through the function below to turn it into more of a relational array that is setup the way you are trying to read it....
I cannot find the function i had for this at the moment but If you read the array more like this:
$newvar = $data->node;
//to echo this try this...
echo '<pre style="text-align:left;">';
print_r($data);
echo '</pre>';
OR try fb logs for php to see the arrays in console of ya browser - use firephp for the addon.
it should work just fine...
Hope that helps.
Consider building dynamic SQL calls conditionally depending on the error output. The array keys create the columns in INSERT clause and array values are quote wrapped in VALUES clause. Below echoes the sql statements just to demonstrate.
This should work for any change to JSON suffice no other new keys are added. Also, the array_splice is used to remove the $ts value the second time since you pass it in date column.
$jsondata = file_get_contents('Input.json');
$data = json_decode($jsondata, true);
$id = $data['device']['sn'];
foreach ($data['data'] as $k=>$v){
if (array_key_exists("\$msg",$v) & !empty($v)){
$sql = "INSERT INTO error_log (sn, msg)"
." VALUES('$id', '". $v["\$msg"] ."')";
echo $sql."\n";
// INSERT INTO error_log (sn, msg) VALUES('5165654', 'SD_FAIL;1')
// INSERT INTO error_log (sn, msg) VALUES('5165654', 'WDT;WV01')
// INSERT INTO error_log (sn, msg) VALUES('5165654', 'WDT;SDI12')
// INSERT INTO error_log (sn, msg) VALUES('5165654', 'WDT;LWS')
$query = mysqli_query(...);
}
if (!array_key_exists("\$msg",$v) & !empty($v)) {
$keysArray = array_keys($v);
$keysArray = array_splice($keysArray, 1);
$vVals = array_splice($v, 1);
$sql = "INSERT INTO test(sn, date, ". implode(", ", $keysArray) .")\n"
." VALUES('$id', '". $v['$ts'] ."',". implode("', '", $vVals) .")";
echo $sql."\n";
// INSERT INTO test(sn, date, RH, AT, MINVi, PTi, LWS, WSAV, WSMX, WSMN,
// PR_TOT, RAIN, FDI, DT, WD, P1, AVGCi)
// VALUES('5165654', '170801170000',67.15', '12.87', '3.81', '23.4', '0*T',
// '0', '0', '0', '156', '0', '0.239', '2.881', '0*T', '0*T', '175)
$query=mysqli_query(...)
}
}
Maybe something like this can get you on track... One thing I did notice is there doesn't appear to be an SDB entry in the given JSON data (FYI).
<?php
//connect to mysql db
$myConnection= mysqli_connect("localhost","root","******", "ii") or die ("could not connect to mysql");
//read the json file contents
$jsondata = file_get_contents('test.json');
//convert json object to php associative array
$data = json_decode($jsondata, true);
// Make sure $data has values
if (empty($data)) {
// Process error here
}
else {
// Make sure the proper keys have been set
if (!(isset($data['device']) && !empty($data['device']) && isset($data['data']) && !empty($data['data']))) {
// Process error here if not set
}
// If so, make sure the sn key has been set
elseif (!isset($data['device']['sn']) || empty($data['device']['sn'])) {
// Process error here if not set
}
else {
$data_arr = $data['data'];
foreach ($data_arr as $key => $arr) {
// Iterate through for loop
for ($i = 0; $i < count($data_arr); $i++) {
// Make sure every single key is set
if (!(isset($data_arr[$i]['$ts']) && isset($data_arr[$i]['RH']) && isset($data_arr[$i]['AT']) && isset($data_arr[$i]['MINVi']) && isset($data_arr[$i]['PTi']) && isset($data_arr[$i]['SDB']) && isset($data_arr[$i]['LWS']) && isset($data_arr[$i]['WSAV']) && isset($data_arr[$i]['WSMX']) && isset($data_arr[$i]['WSMN']) && isset($data_arr[$i]['PR_TOT']) && isset($data_arr[$i]['RAIN']) && isset($data_arr[$i]['FDI']) && isset($data_arr[$i]['DT']) && isset($data_arr[$i]['LAT']) && isset($data_arr[$i]['LON']) && isset($data_arr[$i]['WD']) && isset($data_arr[$i]['P1']) && isset($data_arr[$i]['AVGCi']) && isset($data_arr[$i]['DT']) && isset($data_arr[$i]['DT']))) {
// Process error here if not set
}
else {
// If all is well, perform the query
$id[$key][$i] = $arr['device']['sn'];
$ts[$key][$i] = $data_arr[$i]['$ts'];
$RH[$key][$i] = $data_arr[$i]['RH'];
$AT[$key][$i] = $data_arr[$i]['AT'];
$MINVi[$key][$i] = $data_arr[$i]['MINVi'];
$PTi[$key][$i] = $data_arr[$i]['PTi'];
$SDB[$key][$i] = $data_arr[$i]['SDB'];
$LWS[$key][$i] = $data_arr[$i]['LWS'];
$WSAV[$key][$i] = $data_arr[$i]['WSAV'];
$WSMX[$key][$i] = $data_arr[$i]['WSMX'];
$WSMN[$key][$i] = $data_arr[$i]['WSMN'];
$PR_TOT[$key][$i] = $data_arr[$i]['PR_TOT'];
$RAIN[$key][$i] = $data_arr[$i]['RAIN'];
$FDI[$key][$i] = $data_arr[$i]['FDI'];
$DT[$key][$i] = $data_arr[$i]['DT'];
$LAT[$key][$i] = $data_arr[$i]['LAT'];
$LON[$key][$i] = $data_arr[$i]['LON'];
$WD[$key][$i] = $data_arr[$i]['WD'];
$P1[$key][$i] = $data_arr[$i]['P1'];
$AVGCi[$key][$i] = $data_arr[$i]['AVGCi'];
$sql[$key][$i] = "INSERT INTO test(sn, date, RH, AT, MINVi, PTi, SDB, LWS, WSAV, WSMX, WSMN, PR_TOT, RAIN, FDI, DT, LAT, LON, WD, P1, AVGCi)
VALUES('{$id[$key][$i]}', '{$ts[$key][$i]}', '{$RH[$key][$i]}','{$AT[$key][$i]}', '{$MINVi[$key][$i]}', '{$PTi[$key][$i]}', '{$SDB[$key][$i]}', '{$LWS[$key][$i]}', '{$WSAV[$key][$i]}', '{$WSMX[$key][$i]}', '{$WSMN[$key][$i]}', '{$PR_TOT[$key][$i]}', '{$RAIN[$key][$i]}', '{$FDI[$key][$i]}', '{$DT[$key][$i]}', '{$LAT[$key][$i]}', '{$LON[$key][$i]}', '{$WD[$key][$i]}', '{$P1[$key][$i]}', '{$AVGCi[$key][$i]}')";
//insert into mysql table
$query[$key][$i] = mysqli_query($myConnection, $sql[$key][$i]) or die(mysqli_error($myConnection));
}
}
}
}
}
?>

how to access data from one website to other using api and json

I have a page where i get whole data from database
http://localhost/staff/home.php
if($btn_search =='Serach' && $btn_search !='') {
$search_field = isset($_GET['search_field'])?$_GET['search_field']:'';
$all_users = $obj->getAllUsers($search_field);
}else{
$all_users = $obj->getAllUsers();
$r = json_encode($all_users);
echo "<pre>";
print_r($r);
die();
}
here got the data in JSON format.
but now i want same data in other website and the path is
http://localhost/staff_json/
and the code i have done like this
<?php
$rs = file_get_contents('http://localhost/staff/home.php');
$obj = json_decode($rs);
echo "<pre>";
print_r($obj);
?>
the page is successfully run but data is not showing.
please help me if someone know this
In your http://localhost/staff/home.php in your else part:
else{
$all_users = $obj->getAllUsers();
$r = json_encode($all_users);
echo $r;
}
Updated my code as per your JSON:
put below JSON on "http://localhost/staff/home.php" as it is (actually this is your JSON output you are getting from your code)
[{
"id": "94",
"username": "jems",
"password": "123",
"email": "jems#gmail.com",
"mobile": "8596558499",
"address": "Banglor",
"gender": "male",
"salary": "0",
"status": "1",
"image_name": "1320294973-screenshot.jpg"
}, {
"id": "99",
"username": ".sapna",
"password": "sapna9",
"email": "sapnapapola15#gmail.com",
"mobile": "8826089668",
"address": "laxminagar",
"gender": "male",
"salary": "0",
"status": "1",
"image_name": "no-image.jpg"
}]
And below is the code your "http://localhost/staff_json/index.php"
<?php
$rs = file_get_contents("http://localhost/staff/home.php");
$obj = json_decode($rs);
echo "<pre>";
print_r($obj);
?>
I am getting the desired output
]3
AS per your code:
Prepare a separate file "userdata.php" place it to same folder where the "home.php" page /staff/userdata.php
<?php
include('config/controller.php');
$obj = new Controller();
$all_users = $obj->getAllUsers();
$r = json_encode($all_users);
echo $r;
?>
And below is the code your "http://localhost/staff_json/index.php"
<?php
$rs = file_get_contents("http://localhost/staff/userdata.php");
$obj = json_decode($rs);
echo "<pre>";
print_r($obj);
?>
Then you get the desired output:
Below is your "home.php" page PHP script:
<?php
include('config/controller.php');
$obj = new Controller();
include('header.php');
$obj->authenticate();
$all_users = '';
$search_field ='';
$btn_search = isset($_GET['btn_search'])?$_GET['btn_search']:'';
if($btn_search =='Serach' && $btn_search !='') {
$search_field = isset($_GET['search_field'])?$_GET['search_field']:'';
$all_users = $obj->getAllUsers($search_field);
}
?>
I removed your else part
Try this hope it will work for you
You need to echo you response
if($btn_search =='Serach' && $btn_search !='') {
$search_field = isset($_GET['search_field'])?$_GET['search_field']:'';
$all_users = $obj->getAllUsers($search_field);
}else{
$all_users = $obj->getAllUsers();
$r = json_encode($all_users);
echo $r;
}
Now hit the url.
AS per your comment you need the data of other project into your current project. So you need and CURL request to fetch the data from other project into your current one.
$ch = curl_init();
$curlConfig = array(
CURLOPT_URL => "http://localhost/staff/home.php",
CURLOPT_POST => true,
CURLOPT_RETURNTRANSFER => true,
);
curl_setopt_array($ch, $curlConfig);
$result = curl_exec($ch);
curl_close($ch);
$decodeData = json_decode($result);
print_r($decodeData);
Please try out the above code

Why I can't return a proper json structure?

I'm facing an issue regarding the json structure.
I have this:
function loadActiveTrackers($host_l, $username_l, $password_l, $dbName_l, $companyId_l){
$trackerId = 0;
$trackerName = "";
$trackerCreator = "";
$projectName = "";
$dataArray = [];
$trackerIdsArray = [];
$trackerNamesArray = [];
$trackerCreatorsArray = [];
$projectNamesArray = [];
$mysqli = new mysqli($host_l, $username_l, $password_l, $dbName_l);
$getActiveTrackersQuery = "SELECT tracker_id, tracker_name, tracker_creator, project_name FROM trackers WHERE "
. "company_id = ? AND is_active=1 ORDER BY tracker_creation_date";
if($stmt = $mysqli->prepare($getActiveTrackersQuery)){
$stmt->bind_param('s',$companyId_l);
$stmt->execute();
/* Store the result (to get properties) */
$stmt->store_result();
/* Bind the result to variables */
$stmt->bind_result($trackerId, $trackerName, $trackerCreator, $projectName);
while ($stmt->fetch()) {
$trackerIdsArray[] = $trackerId;
$trackerNamesArray[] = $trackerName;
$trackerCreatorsArray[] = $trackerCreator;
$projectNamesArray[] = $projectName;
}
$dataArray['ids'] = $trackerIdsArray;
$dataArray['names'] = $trackerNamesArray;
$dataArray['creators'] = $trackerCreatorsArray;
$dataArray['projectNames'] = $projectNamesArray;
// print_r($trackerIdsArray);
/* free results */
$stmt->free_result();
/* close statement */
$stmt->close();
}
/* close connection */
$mysqli->close();
echo json_encode($dataArray);
}
The above code works ok, but the structure is not valid.
What I mean is that it returns:
{
"ids": [1,2,3,4],
"names": ["1","2","test tracker","test1"],
"creators": ["1","test","test","test"],
"projectNames": ["1","1","test project","test"]
}
But it is supposed to return:
[
{"id": 1, "name": "1", "creator": "1", "projectName": "1"},
{"id": 2, "name": "2", "creator": "test", "projectName": "1"},
{"id": 3, "name": "test tracker", "creator": "test", "projectName": "test project"},
{"id": 4, "name": "test1", "creator": "test", "projectName": "test"}
]
Can you guide me trough it? I know that it's something really small, but I'm not able to spot it as a php newbie. In java the json library is pretty strong and with a single push() it can be achieved, but here I really can't find the way.
The current code creates arrays of the ids, names, creators, and project names.
So, instead of this code:
while ($stmt->fetch()) {
$trackerIdsArray[] = $trackerId;
$trackerNamesArray[] = $trackerName;
$trackerCreatorsArray[] = $trackerCreator;
$projectNamesArray[] = $projectName;
}
$dataArray['ids'] = $trackerIdsArray;
$dataArray['names'] = $trackerNamesArray;
$dataArray['creators'] = $trackerCreatorsArray;
$dataArray['projectNames'] = $projectNamesArray;
Change your structure to be like so:
while ($stmt->fetch()) {
$dataArray[] = array( 'id' => $trackerId,
'name' => $trackerName,
'creator' => $trackerCreator,
'projectName' => $projectName
);
}
echo json_encode($dataArray);
This will return the structure you desire, which is arrays of the ids, names, creators, and project names.

Categories