Insert an Array of Data in SQL using PHP

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 Insert an Array of Data in SQL using PHP.

How to Insert an Array of Data in SQL using PHP

In PHP, we need to follow given mandatory steps before we start with any SQL operation:

  1. Define database details
    We need to initialize a database connection and for that we will need its detail. The prerequisite for this will include setup of a database in myphpadmin (if we are using local server). There we will have to create a database and tables.
    In case you have done setup of database and tables in local server: https://localhost/phpmyadmin/

Then, following will be the database details written in PHP

$servername = "localhost";
$username = "root";
$dbname = "<your_database_name>";

 

  1. Create connection
    Once the required connection details are mentioned, we will try to create a connection to database using below query:

    $conn = new mysqli($servername, $username,"", $dbname);
  2. Check connection
    Now the connection setup is done, we need to perform a check to confirm the same using below query:
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

 

  1. Perform Query
    This is the part where we write SQL query to insert data in PHP. In the below query, firstly we check if the data coming from frontend is an array or not using is_array function. If it is an array, then we create our own local array in a variable $DataArr[] with a format we want. Once we have our array, then we pass the array to our SQL query using function implode. Then this SQL query with connection is passed to mysqli_query function. If the resulted query is successful then we echo (i.e. send back to frontend) the success message, else we return a message ‘Insertion failed’:
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);
    }
}

 

  1. Close Connection
    Once we are done with our operation, then it is a good practise to close the database connection using this simple query:
$conn->close();

 

Full code:

function onCreateTransaction(){
$servername = "localhost";
$username = "root";
$dbname = "<your_database_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 Insert an Array of Data in SQL from frontend

In above steps we have connected to SQL, fetched data and sent in response. The above function is only triggered once the UI calls it. In UI, we write given code to perform the required operation:

// Insert Array in Transaction Table
var http = "http://";
var uri = http + "localhost/<location_of_your_php_file/name_of_your_php_file>";
            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.");
                    }
                    else{
MessageBox.success(results[1]);
                    }
                },
                error: function (request, error) {
                    MessageBox.error(error);
                }
            });

 

Leave a comment

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