Jump to content

how to read json data from array


Abrar

Recommended Posts

<?php
ini_set('display_errors', 0);
function escapeArray($array)
{
        foreach ($array as $key => $val)
        {
			if(is_array($val)){
				$array[$key]=escapeArray($val);
			}
			else{
				$array[$key]=addslashes($val);
			}
        }

        return $array;
		
}





$request_type=$_SERVER['REQUEST_METHOD'];
$api_key=$_SERVER['HTTP_X_API_KEY'];
$res=array();
if($api_key!=="643256432"){
	$res['msg']="Failure:Invalid API KEY";
	echo json_encode($res);
	die;
}
// Connects to the orcl service (i.e. database) on the "localhost" machine
//$conn = oci_connect('SCOTT', 'admin123', 'localhost/orcl');

$conn = oci_connect('test', 'test', '192.168.10.43/test.test.com');

if (!$conn) {
    $e = oci_error();
    trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}

$request=file_get_contents("php://input");
$request=escapeArray(json_decode($request,true));

 print_r($request);
// die;
if($request_type=="POST"){//for creation of invoice


echo	$CONTACT_ID=isset($request['CONTACT_ID'])?$request['CONTACT_ID']:"";
	$INV_SERIAL_NO=isset($request['INV_SERIAL_NO'])?$request['INV_SERIAL_NO']:"";
	$NAME=isset($request['NAME'])?$request['NAME']:"";
	$INV_DATE=isset($request['INV_DATE'])?$request['INV_DATE']:"";
	$DUE_DATE=isset($request['DUE_DATE'])?$request['DUE_DATE']:"";
	$CURRENCY=isset($request['CURRENCY'])?$request['CURRENCY']:"";
	$SUBTOTAL=isset($request['SUBTOTAL'])?$request['SUBTOTAL']:"";
	$TAX_TOTAL=isset($request['TAX_TOTAL'])?$request['TAX_TOTAL']:"";

echo $SHIP_SERIAL_NO=isset($request['SHIP_SERIAL_NO'])?$request['SHIP_SERIAL_NO']:"";
	$MASTER_NO=isset($request['MASTER_NO'])?$request['MASTER_NO']:"";
	$HOUSE_NO=isset($request['HOUSE_NO'])?$request['HOUSE_NO']:"";
	$shipment_data=isset($request['shipment_data'])?$request['shipment_data']:"";

	if($CONTACT_ID==""){
		$res['msg']="CONTACT_ID is required";
	}
	else if($INV_SERIAL_NO==""){
		$res['msg']="INV_SERIAL_NO is required";
	}
	else if($NAME==""){
		$res['msg']="NAME is required";
	}
	else if($INV_DATE==""){
		$res['msg']="INV_DATE is required";
	}
	else if($DUE_DATE==""){
		$res['msg']="DUE_DATE is required";
	}
	else if($CURRENCY==""){
		$res['msg']="CURRENCY is required";
	}
	else if($SUBTOTAL==""){
		$res['msg']="SUBTOTAL is required";
	}
	else if($TAX_TOTAL==""){
		$res['msg']="TAX_TOTAL is required";
	}

	
	else if($MASTER_NO==""){
		$res['msg']="MASTER_NO is required";
	}
	else if($HOUSE_NO==""){
		$res['msg']="HOUSE_NO is required";
	}
	else if($SHIP_SERIAL_NO==""){
		$res['msg']="SHIP_SERIAL_NO is required";
	}



	

	else{
		$stid = oci_parse($conn, "Select * from FL_HDR_INVOICE where CONTACT_ID='$CONTACT_ID'");
		(oci_execute($stid));
		oci_fetch_all($stid, $out);
		
		

		if(count($out['CONTACT_ID'])==0){

			$stid = oci_parse($conn, "Insert into FL_HDR_INVOICE (CONTACT_ID,INV_SERIAL_NO,NAME,INV_DATE,DUE_DATE,CURRENCY,SUBTOTAL,TAX_TOTAL) Values ('$CONTACT_ID','$INV_SERIAL_NO','$NAME',TO_DATE('$INV_DATE','YYYY-MM-DD'),TO_DATE('$DUE_DATE','YYYY-MM-DD'),'$CURRENCY','$SUBTOTAL','$TAX_TOTAL')");
			oci_execute($stid);

			$stid_2 = oci_parse($conn, "Insert into FL_SHIPMENT_DATA (CONTACT_ID,INV_SERIAL_NO,SHIP_SERIAL_NO,MASTER_NO,HOUSE_NO) Values ('$CONTACT_ID','$INV_SERIAL_NO','$SHIP_SERIAL_NO','$MASTER_NO','$HOUSE_NO')");
			oci_execute($stid_2);



			if(oci_num_rows($stid)>0){
				$res['msg']="Invoice created successfully against this contact_id:".$CONTACT_ID;
			}
			else{
				$res['msg']="Something going wrong please try again later";
				
			}
		}
		else{
			$res['msg']="contact_id must be unique";
		}
	}
	echo json_encode($res);
	die;
}

I need to read json data inside an array. Please help correct my code.. i am trying to do an API.

Link to comment
Share on other sites

Yes, definitely needs to be cleaned up.

  • Do not directly insert user provided values in the DB but use prepared statements.
  • You don't want to use else if for all your validation but just an if since you are adding the errors to an array.
  • You could shorten the script which assigns values by using $CONTACT_ID=$request['CONTACT_ID']??null;
  • Break your code into several small functions.
Link to comment
Share on other sites

i also have another issue in inserting multiple arrays at the same call.

This is how my json data will look like,

image.png.6c6f01f4a7182f66814e9bb307b405cd.png.

 

Below is my code.But it is only storing array value at position [0] since i have hard coded here, How to loop and store all the values. Please guide me, Thank you in advance.

	$SHIP_SERIAL_NO=isset($request['shipment_data'][0]['SHIP_SERIAL_NO'])??null; 
	$MASTER_NO=isset($request['shipment_data'][0]['MASTER_NO'])??null; 
	$HOUSE_NO=isset($request['shipment_data'][0]['HOUSE_NO'])??null; 
	$shipment_data=isset($request['shipment_data'])?$request['shipment_data']:""; // this is ab array

 

Link to comment
Share on other sites

Run the following script and spend time to understand it.  If you don't understand <<<EOL, see https://www.php.net/manual/en/language.types.string.php#language.types.string.syntax.heredoc.  If you don't understand how the functions work, look them up on php.net.

<?php
ini_set('display_errors', 1);

$json = <<<EOL
{
    "CONCACT_ID": 123,
    "shipping_data": [{
            "SER_NO": 312,
            "BLA": 123
        }, {
            "SER_NO": 112,
            "BLA": 223
        }
    ]
}
EOL;
echo($json.PHP_EOL);

// Turn the JSON string into either an array or object (I use an array)
$arr = json_decode($json, true);
print_r($arr);
$obj = json_decode($json, false);
print_r($obj);

printf('array: %s object: %s'.PHP_EOL, $arr['CONCACT_ID'], $obj->CONCACT_ID);

foreach($arr['shipping_data'] as $item) {
    print_r($item);    
}

foreach($obj->shipping_data as $item) {
    print_r($item);    
}

 

Link to comment
Share on other sites

Thank you so much @NotionCommotion!

That was a helpful document.

 

Resolved with the below query

						foreach($request['shipment_data'] as $item) {
						$SHIP_SERIAL_NO= ($item['SHIP_SERIAL_NO']);    
						$MASTER_NO= ($item['MASTER_NO']);    
						$HOUSE_NO= ($item['HOUSE_NO']);   

			$stid_2 = oci_parse($conn, "Insert into FL_SHIPMENT_DATA (CONTACT_ID,INV_SERIAL_NO,SHIP_SERIAL_NO,MASTER_NO,HOUSE_NO) Values ('$CONTACT_ID','$INV_SERIAL_NO','$SHIP_SERIAL_NO','$MASTER_NO','$HOUSE_NO')");
			oci_execute($stid_2);
																	}

 

Link to comment
Share on other sites

9 hours ago, Abrar said:

How to loop and store all the values.

foreach() is good.

Have you considered PDO (an OCI driver is available)?

$curl_data = '{
       "CONTACT_ID": "1793",
       "INV_SERIAL_NO": "345",
       "shipment_data": [
           {
            "SHIP_SERIAL_NO": "11",
            "MASTER_NO": "11",
            "HOUSE_NO": "11"
           },
           {
            "SHIP_SERIAL_NO": "22",
            "MASTER_NO": "22"
           },
           {
            "SHIP_SERIAL_NO": "33",
            "HOUSE_NO": "33"
           }
       ]
}';

$request = json_decode($curl_data, 1);
$base = [     "CONTACT_ID" => $request['CONTACT_ID'],
              "INV_SERIAL_NO" => $request['INV_SERIAL_NO'],
              "SHIP_SERIAL_NO" => null,
              "MASTER_NO" => null,
              "HOUSE_NO" => null
            ];

$stmt = $db->prepare("INSERT INTO fl_shipment_data (contact_id, inv_serial_no, ship_serial_no, master_no, house_no)
                      VALUES (:CONTACT_ID, :INV_SERIAL_NO, :SHIP_SERIAL_NO, :MASTER_NO, :HOUSE_NO)
                     ");

foreach ($request['shipment_data'] as $ship) {
    $data = array_merge($base, $ship);
    $stmt->execute($data);
}

results

fl_shipment_data
+----------------+------------+---------------+----------------+-----------+----------+
| fl_shipment_id | contact_id | inv_serial_no | ship_serial_no | master_no | house_no |
+----------------+------------+---------------+----------------+-----------+----------+
|              1 |       1793 |           345 |             11 |        11 |       11 |
|              2 |       1793 |           345 |             22 |        22 |     NULL |
|              3 |       1793 |           345 |             33 |      NULL |       33 |
+----------------+------------+---------------+----------------+-----------+----------+

 

Link to comment
Share on other sites

Thank you so much for the suggestions. I am preparing this application for others so we need to consider the security parameters. i will follow Barand suggestion and will use PDO and prepared statements.

 

Thank you once again for your support..

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.