JSON Decode elements in file - php

Hi I am currently working on stripping out a json file and putting the elements into a database there are 26 entries in the json file using the following code I have been able to map the majority of the entries but am now in a position whereby certain elements in the json only occur in certain entries eg tags in the first 2 entries has a Name and cirrushq_id field but from the 3rd entry down has only a aws:autoscaling:groupName not present in the first 2 entries so my question really is how to modify the php such that it takes into account the fact that there may not be a Name or id for every entry and not subsequently break ?
here is the php
<?php
$con=mysqli_connect("localhost","root","","json_map");
$response = array();
$res=array();
$json = file_get_contents('C:\Users\Richard\Desktop\test.json');
if($json!=null){
$decoded=json_decode($json,true);
//$decode= var_dump($decoded);
//$ss=$decode["array"];
//echo $decoded['number'];
if(is_array($decoded["configurationItems"]))
{
foreach($decoded["configurationItems"] as $configurationItems)
//for($i=0;$i>sizeof($decoded["configurationItems"]);$i++)
{
$Name=$configurationItems["tags"]["Name"];
echo "Name:",$Name,"<br />";
$cirrushq_id=$configurationItems["tags"]["cirrushq_id"];
echo "cirrushq_id:",$cirrushq_id,"<br />";
$awsautoscalinggroupName= $configurationItems["tags"]["aws:autoscaling:groupName"];
echo "aws:autoscaling:groupName:",$awsautoscalinggroupName,"<br />";
$result = mysqli_query($con, "INSERT INTO tag(name, cirrushq_id, aws_autoscaling_group_name)
VALUES('$Name','$cirrushq_id', '$awsautoscalinggroupName')")or die("Insert Failed ".((is_object($con)) ? mysqli_error($con) : (($___mysqli_res = mysqli_connect_error()) ? $___mysqli_res : false)));;
}// check if row inserted or not
if ($result) {
// successfully inserted into database
$response["code"] = 1;
$response["message"] = "successfully stored tags ";
// echoing JSON response
echo json_encode($response);
} else {
// failed to insert row
$response["code"] = 2;
$response["message"] = "Oops! An error occurred.";
// echoing JSON response
echo json_encode($response);
}
}
}
?>
and the json
{
"fileVersion":"1.0",
"configurationItems":[
{
"configurationItemVersion":"1.0",
"configurationItemCaptureTime":"2014-12-05T10:22:51.751Z",
"configurationStateId":1,
"relatedEvents":[ ],
"awsAccountId":"",
"configurationItemStatus":"ResourceDiscovered",
"resourceId":"",
"ARN":"",
"awsRegion":"us-east-1",
"availabilityZone":"us-east-1b",
"configurationStateMd5Hash":"",
"resourceType":"AWS::EC2::Instance",
"resourceCreationTime":"2014-01-06T10:37:37.000Z",
"tags":{
"Name":"dbn.prod-us.wordeo.com",
"cirrushq_id":"instance_20"
},
as above for 2nd entry
3rd entry the same down to tags as follows
"tags":{
"aws:autoscaling:groupName":"ES-PROD-US-03-01-14"
},
using isset method as per answer
<?php
$con=mysqli_connect("localhost","root","","json_map");
$response = array();
$res=array();
$json = file_get_contents('C:\Users\Richard\Desktop\test.json');
if($json!=null){
$decoded=json_decode($json,true);
//$decode= var_dump($decoded);
//$ss=$decode["array"];
//echo $decoded['number'];
if(is_array($decoded["configurationItems"]))
{
foreach($decoded["configurationItems"] as $configurationItems)
//for($i=0;$i>sizeof($decoded["configurationItems"]);$i++)
$tags=$configurationItems["tags"];
if(isset($tags["Name"]) && isset($tags["cirrushq_id"])){
$Name=$tags["Name"];
echo "Name:",$Name,"<br />";
$cirrushq_id=$tags["cirrushq_id"];
echo "cirrushq_id:",$cirrushq_id,"<br />";
$awsautoscalinggroupName= isset($tags["aws:autoscaling:groupName"]) ?
$tags["aws:autoscaling:groupName"] : '';
echo "aws:autoscaling:groupName:",$awsautoscalinggroupName,"<br />";
$result = mysqli_query($con, "INSERT INTO tag(name, cirrushq_id, aws_autoscaling_group_name)
VALUES('$Name','$cirrushq_id', '$awsautoscalinggroupName')");
}// check if row inserted or not
if ($result) {
// successfully inserted into database
$response["code"] = 1;
$response["message"] = "successfully stored tags ";
// echoing JSON response
echo json_encode($response);
} else {
// failed to insert row
$response["code"] = 2;
$response["message"] = "Oops! An error occurred.";
// echoing JSON response
echo json_encode($response);
}
}
}
?>

Use isset() to check the name or id exists or not.
Change the php foreach loop code like,
$tags=$configurationItems["tags"];
if(isset($tags["Name"]) && isset($tags["cirrushq_id"])){
$Name=$tags["Name"];
echo "Name:",$Name,"<br />";
$cirrushq_id=$tags["cirrushq_id"];
echo "cirrushq_id:",$cirrushq_id,"<br />";
$awsautoscalinggroupName= isset($tags["aws:autoscaling:groupName"]) ?
$tags["aws:autoscaling:groupName"] : '';
echo "aws:autoscaling:groupName:",$awsautoscalinggroupName,"<br />";
// remove the die if there is any error then it will go forward
$result = mysqli_query($con, "INSERT INTO tag(name, cirrushq_id, aws_autoscaling_group_name)
VALUES('$Name','$cirrushq_id', '$awsautoscalinggroupName')");

Related

PHP: Looping data with JSON response

I'm trying to get my data from database and I can get it but there is an error I'm getting two copies of those records. I don't understand why my looping is not working. You can find the code below. I didn't initiate a php code so it would not be a SQL injection. Please Guide.
if( mysqli_num_rows( $result ) > 0 ) {
while($row = mysqli_fetch_array($result))
{
$flag[checkdate]=$row[checkdate];
$flag[checkno]=$row[checkno];
$flag[datepaid]=$row[datepaid];
$flag[clientname]=$row[clientname];
$flag[bank]=$row[bank];
$flag[amount]=$row[amount];
$flag[status]=$row[status];
array_push($info, $flag);
}
$response["success"] = true;
$response["message"] = $info;
echo json_encode($response);
}
else
{
$response["success"] = 0;
$response["message"] = "No entries yet";
echo json_encode($response);
}

PHP Array doesn't show all database items

I fixed now my PHP file and finally I have an output of my array. But the problem is, that I have three entry of textes in my database, but my array only shows two of them.
Function.php
public function listQuestion(){
$result = mysql_query("SELECT text FROM `questions`");
if(!$result)
{
echo "Database query failed: " . mysql_error();
}
$temp_array = array();
while ($row = mysql_fetch_array($result)) {
$temp_array[] = $row;
}
return $temp_array;
}
Index.php
else if ($tag == "question"){
// Request type is question
// list questions
$question = $db->listQuestion();
if ($question != false) {
// questions found
// echo json with success = 1
$response["success"] = 1;
$response["question"] = $question;
// $userlog = array();
// $userlog["question"]["text"] = $question["text"];
// array_push($response["question"], $userlog);
echo json_encode($response);
//echo json_encode(array("question"=>$question));
} else {
// questions not found
// echo json with error = 1
$response["error"] = 1;
$response["error_msg"] = "Questions were not found!";
echo json_encode($response);
}
}
The output
{"tag":"question","success":1,"error":0,"question":
[{"0":"Ich lese gerne technische Zeitschriften.","text":"Ich lese gerne technische Zeitschriften."},
{"0":"Ich habe Angst im Dunkeln.","text":"Ich habe Angst im Dunkeln."},
{"0":null,"text":null}]} -> here should be 'Manchmal fühle ich mich hungrig.'
Any suggestions?
Roman

Undefined index: ___mysqli_ston [duplicate]

This question already has answers here:
what is $GLOBALS["___mysqli_ston"] in mysqli
(2 answers)
Closed 1 year ago.
I am trying to parse some json data, into a mysql database, from a file. My original code was as follows:
<?php
$response = array();
$res=array();
$json = file_get_contents('C:\Users\Richard\Desktop\test.json');
if($json!=null){
$decoded=json_decode($json,true);
//$decode= var_dump($decoded);
//$ss=$decode["array"];
//echo $decoded['number'];
if(is_array($decoded["configurationItems"]))
{
foreach($decoded["configurationItems"] as $configurationItems)
//for($i=0;$i>sizeof($decoded["configurationItems"]);$i++)
{
$configurationItemVersion=$configurationItems["configurationItemVersion"];
echo "<br />","configurationItemVersion:",$configurationItemVersion,"<br />";
$configurationItemCaptureTime=$configurationItems["configurationItemCaptureTime"];
echo "configurationItemCaptureTime:",$configurationItemCaptureTime,"<br />";
$configurationStateId=$configurationItems["configurationStateId"];
echo "configurationStateId:",$configurationStateId,"<br />";
$result = mysql_query("INSERT INTO configuration_item(configurationItemVersion,configurationItemCaptureTime,configurationStateId)
VALUES('$configurationItemVersion','$configurationItemCaptureTime','$configurationStateId')")or die("Insert Failed ".mysql_error());;
}// check if row inserted or not
if ($result) {
// successfully inserted into database
$response["code"] = 1;
$response["message"] = "successfully stored";
// echoing JSON response
echo json_encode($response);
} else {
// failed to insert row
$response["code"] = 2;
$response["message"] = "Oops! An error occurred.";
// echoing JSON response
echo json_encode($response);
}
}
}
?>
which failed due to being depricated; so rather than altering the error handler to ignore this (really bad practice), I opted to convert to mysqli using a handy conversion tool sourced here : https://github.com/philip/MySQLConverterTool
I ran the converter on the aforementioned code and it generated the following:
<?php
$response = array();
$res=array();
$json = file_get_contents('C:\Users\Richard\Desktop\test.json');
if($json!=null){
$decoded=json_decode($json,true);
//$decode= var_dump($decoded);
//$ss=$decode["array"];
//echo $decoded['number'];
if(is_array($decoded["configurationItems"]))
{
foreach($decoded["configurationItems"] as $configurationItems)
//for($i=0;$i>sizeof($decoded["configurationItems"]);$i++)
{
$configurationItemVersion=$configurationItems["configurationItemVersion"];
echo "<br />","configurationItemVersion:",$configurationItemVersion,"<br />";
$configurationItemCaptureTime=$configurationItems["configurationItemCaptureTime"];
echo "configurationItemCaptureTime:",$configurationItemCaptureTime,"<br />";
$configurationStateId=$configurationItems["configurationStateId"];
echo "configurationStateId:",$configurationStateId,"<br />";
$result = mysqli_query($GLOBALS["___mysqli_ston"], "INSERT INTO configuration_item(configurationItemVersion,configurationItemCaptureTime,configurationStateId)
VALUES('$configurationItemVersion','$configurationItemCaptureTime','$configurationStateId')")or die("Insert Failed ".((is_object($GLOBALS["___mysqli_ston"])) ? mysqli_error(
"]) : (($___mysqli_res = mysqli_connect_error()) ? $___mysqli_res : false)));;
}// check if row inserted or not
if ($result) {
// successfully inserted into database
$response["code"] = 1;
$response["message"] = "successfully stored";
// echoing JSON response
echo json_encode($response);
} else {
// failed to insert row
$response["code"] = 2;
$response["message"] = "Oops! An error occurred.";
// echoing JSON response
echo json_encode($response);
}
}
}
?>
upon running this code I get the error message in the title (Undefined index: ___mysqli_ston) and have no idea how to fix it, any help would be much appreciated.
ps I am using the laravel framework if that makes a difference or opens up other solutions.
I now know that the error relates to the fact that I have no database connection string ie $GLOBALS["___mysqli_ston is generated by the generator.
it was my understanding that laravel took care of defining the database connection in its mvc architecture and therefore this does not need to be redefined. with that in mind what would my code look like ?
you must have connected to mysql using something like this
$con=mysqli_connect("localhost","my_user","my_password","my_db");
replace your this line
$result = mysqli_query($GLOBALS["___mysqli_ston"], "INSERT INTO configuration_item(configurationItemVersion,configurationItemCaptureTime,configurationStateId)
with this
$result = mysqli_query($con, "INSERT INTO configuration_item(configurationItemVersion,configurationItemCaptureTime,configurationStateId)

json decoding in php and insert into mysql DB

this is my json data, i am try to decode this json and store the data in mysql database.
i am try json decoding in php. In my php server side json data are not decoded and not stored in mysql database. please help me to solve this problem.
JSON DATA
{
"code":"0",
"message":"Success",
"events":[
{
"id":1,
"name":"test event",
"description":"test desc",
"date":"2014-06-22 00:00:00",
"location":"keelapalur",
"type":1,
"passcode":"123456",
"created":{
"date":"2014-06-08 17:05:12",
"timezone_type":3,
"timezone":"UTC"
},
"updated":{
"date":"2014-06-08 17:05:12",
"timezone_type":3,
"timezone":"UTC"
}
},
{
"id":2,
"name":"rtyr",
"description":"rtyr",
"date":"2014-06-22 00:00:00",
"location":"try",
"type":1,
"passcode":"123456",
"created":{
"date":"2014-06-12 09:26:31",
"timezone_type":3,
"timezone":"UTC"
},
"updated":{
"date":"2014-06-12 09:26:31",
"timezone_type":3,
"timezone":"UTC"
}
}
]
}
PHP code
<?php
$response = array();
$res=array();
require_once __DIR__ . '/db_connect.php';
$json = file_get_contents('/insert.json');
if($json!=null){
$decoded=json_decode($json,true);
//$decode= var_dump($decoded);
//$ss=$decode["array"];
//echo $decoded['number'];
if(sizeof($decoded["events"])>0)
{
for($i=0;$i>sizeof($decoded["events"]);$i++)
{
$id=$decoded["events"]["id"];
$name=$decoded["events"]["name"];
$date=$decoded["events"]["date"];
$desc=$decoded["events"]["description"];
$location=$decoded["events"]["location"];
$type=$decoded["events"]["type"];
$passcode=$decoded["events"]["passcode"];
$cdate=$decoded["events"]["created"]["date"];
$ctimzonety= $decoded["events"]["created"]["timezone_type"];
$ctimz=$decoded["events"]["created"]["timezone"];
$udate=$decoded["events"]["updated"]["date"];
$utimzonety= $decoded["events"]["updated"]["timezone_type"];
$utimz=$decoded["events"]["updated"]["timezone"];
$result = mysql_query("INSERT INTO events(userid,name,desc,date,loc,type,passcode,cdate,ctimezone_type,ctimezone,udate,utimezone_type,utimezone)
VALUES('$id,'$name','$desc','$date','$loc','$type','$passcode','$cdate','$ctimzonety','$ctimz','$udate','$utimzonety','$utimz')");
// check if row inserted or not
if ($result) {
// successfully inserted into database
$response["code"] = 1;
$response["message"] = "successfully stored";
// echoing JSON response
echo json_encode($response);
} else {
// failed to insert row
$response["code"] = 2;
$response["message"] = "Oops! An error occurred.";
// echoing JSON response
echo json_encode($response);
}
}
}
}
?>
Make ensure your database connectivity..Try this code 100% it's working...
<?php
$response = array();
$res=array();
$json = file_get_contents('C:\Users\Devunne3\Desktop\insert.json');
if($json!=null){
$decoded=json_decode($json,true);
//$decode= var_dump($decoded);
//$ss=$decode["array"];
//echo $decoded['number'];
if(is_array($decoded["events"]))
{
foreach($decoded["events"] as $events)
//for($i=0;$i>sizeof($decoded["events"]);$i++)
{
$id=$events["id"];
echo "<br />","userid:",$id,"<br />";
$name=$events["name"];
echo "name:",$name,"<br />";
$date=$events["date"];
echo "date:",$date,"<br />";
$desc=$events["description"];
echo "desc:",$desc,"<br />";
$location=$events["location"];
echo "loc:",$location,"<br />";
$type=$events["type"];
echo "type:",$type,"<br />";
$passcode=$events["passcode"];
echo "passcode:",$passcode,"<br />";
$cdate=$events["created"]["date"];
echo "cdate:",$cdate,"<br />";
$ctimzonety=$events["created"]["timezone_type"];
echo "ctimezone_type:",$ctimzonety,"<br />";
$ctimz=$events["created"]["timezone"];
echo "ctimezone:",$ctimz,"<br />";
$udate=$events["updated"]["date"];
echo "udate:",$udate,"<br />";
$utimzonety=$events["updated"]["timezone_type"];
echo "utimezone_type:",$utimzonety,"<br />";
$utimz=$events["updated"]["timezone"];
echo "utimezone",$utimz,"<br />";
echo"------------------------------------------------","<br />";
require_once __DIR__ . '/db_connect.php';
$db = new DB_CONNECT();
$result = mysql_query("INSERT INTO events(userid,name,desc,date,loc,type,passcode,cdate,ctimezone_type,ctimezone,udate,utimezone_type,utimezone)
VALUES('$id','$name','$desc','$date','$location','$type','$passcode','$cdate','$ctimzonety','$ctimz','$udate','$utimzonety','$utimz')")or die("Insert Failed ".mysql_error());;
}// check if row inserted or not
if ($result) {
// successfully inserted into database
$response["code"] = 1;
$response["message"] = "successfully stored";
// echoing JSON response
echo json_encode($response);
} else {
// failed to insert row
$response["code"] = 2;
$response["message"] = "Oops! An error occurred.";
// echoing JSON response
echo json_encode($response);
}
}
}
?>

mysql query and encoding it in json format

I'm using this simple php code to encode the MySql query result in json format.
But Don't know why it is not giving me the desirable output.
I'm actually trying to get the employee details by entering their 'employee_number'.
<?php
require('DB_Connect.php');
require('config.php');
// check for post data
/*
if (isset($_POST["employee_number"])) {
$employee_name = $_POST['employee_number'];
*/
//get a employee from employee_info table
$result = mysql_query("SELECT *FROM employee_info WHERE employee_number =9876543210");
if (!empty($result)) {
// check for empty result
if (mysql_num_rows($result) > 0) {
$result = mysql_fetch_array($result);
echo("Success !! Yoo");
$employee = array();
$employee["employee_number"] = $result["employee_number"];
$employee["employee_name"] = $result["employee_name"];
$employee["flag"]=$result["flag"];
// success
$response["success"] = 1;
// user node
$response["employee"] = array();
array_push($response["employee"], $employee);
// echoing JSON response
echo json_encode($response);
} else {
// no employee found
$response["success"] = 0;
$response["message"] = "No employee found";
// echo no users JSON
echo json_encode($response);
}
}else {
// no employee found
$response["success"] = 0;
$response["message"] = "No employee found";
// echo no users JSON
echo json_encode($response);
}
/*} else {
// required field is missing
$response["success"] = 0;
$response["message"] = "Required field(s) is missing";
*/
// echoing JSON response
echo json_encode($response);
?>
mysql_query is deprecated. Use mysqli or PDO instead.
make sure you format your query properly *note the spaces
$result = mysql_query("SELECT * FROM employee_info WHERE employee_number = 9876543210");
you could also just echo the $result as your employee array doesn't seem to do anything.
echo json_encode($result);

Categories