How to read incoming array data in a PHP file

Introduction

Whatever we see on our website, it is either saved within HTML or being fetched from a table. The HTML has a script file attached with it which calls backend, where SQL codes are written. These SQL codes interact with database. In this article we will learn how to read incoming array of data in a PHP file.

Syntax

$obj = json_decode($_POST["data"]); // data is the object that was sent from the frontend
$records = $obj->arrayData; // arrayData is a variable which was used to store array of data in frontend

How to read incoming array data in a PHP file

Suppose there is a use case where you need to upload an array of data in a table, and for that you need to send array of objects from frontend (JavaScript) to backend (PHP).
The array sent from frontend should be in the form of a JSON. Then this JSON is decoded in PHP and thereafter individual array rows are accessed as shown below:

$obj = json_decode($_POST["data"]);
$records = $obj->arrayData;
if(is_array($records)){
$DataArr = array();
foreach($records as $row){
    $Date = $row->Date;
    $Type = $row->Type;
    $Reference = $row->Reference;
    $Received = $row->Received;
    $ReceivedDate = $row->ReceivedDate;
    $Mode = $row->Mode;
    $Staff = $row->Staff;
    $guid = $row->guid;
    if(isset($row->ChequeNo)){
    $ChequeNo = $row->ChequeNo;
    }
    else{
        $ChequeNo = '';
    }
    $DataArr[] = "('$Date', '$Type', '$Reference','$Received', '$ReceivedDate', '$Mode','$ChequeNo', '$Staff', '$guid')";
}

 

Now this newly created Array can be used to perform array implode i.e. Upload or any other operations. Here we have created a local array as it was required to change the order of columns as per table. In case the incoming data is in same sequence then it can be directly inserted.

Full Code:

function onCreateTransaction(){
$servername = "localhost";
$username = "root";
$dbname = "<your DB Name>";
// Create connection
$conn = new mysqli($servername, $username,"", $dbname);
// Check connection
    if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
    }
    $obj = json_decode($_POST["data"]);
    $records = $obj->arrayData;
    $checkDate = $records[0]->Date;
        // Perform query to check for existing data
    if ($result = $conn -> query("SELECT * FROM transactions WHERE ReceivedDate = '{$checkDate}'")) {
        if($result->num_rows > 0) {
    $dataArray[0] = 'Data already exists!';
    echo json_encode($dataArray);
    }
    else{
    if(is_array($records)){
    $DataArr = array();
    foreach($records as $row){
        $Date = $row->Date;
        $Type = $row->Type;
        $Reference = $row->Reference;
        $Received = $row->Received;
        $ReceivedDate = $row->ReceivedDate;
        $Mode = $row->Mode;
        $Staff = $row->Staff;
        $guid = $row->guid;
        if(isset($row->ChequeNo)){
        $ChequeNo = $row->ChequeNo;
        }
        else{
            $ChequeNo = '';
        }
        $DataArr[] = "('$Date', '$Type', '$Reference','$Received', '$ReceivedDate', '$Mode','$ChequeNo', '$Staff', '$guid')";
    }
    
    $sql = "INSERT INTO transactions(Date, Type, Reference, Received, ReceivedDate, Mode, ChequeNo, Staff, guid) values ";
    $sql .= implode(',', $DataArr); 
    if(mysqli_query($conn, $sql)){
    $dataArray[0] = 'Insertion successful';
    echo json_encode($dataArray);
    }
    else{
    $dataArray[0] = 'Insertion failed';
    echo json_encode($dataArray);
    }
}
    }
}
}

 

Calling PHP to read incoming array data from frontend

In UI, we need to create an object and pass that object in the form of JSON using a function call as shown below:

// Update Transaction Table
var data = {
    arrayData: excelRows
};
$.ajax({
    url: uri,
    type: "POST",
    data: {
        method: "onCreateTransaction",
        data: JSON.stringify(data)
    },
    dataType: "json",
    success: function (results) {
        if(results[0] == "Data already exists!"){
            MessageBox.error("Data already exits for the date:" + excelRows[0].Date + ". Kindly upload the right file.");
        }
    },
    error: function (request, error) {
        MessageBox.error(error);
    }
});

 

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.