Create single entry 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 to create or insert single entry in table using SQL in PHP.

Syntax

INSERT INTO <table name>(<field name 1>,<field name 2>) VALUES ('<local variable 1>','<local variable 2>')

How to read Data from 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 create data in PHP. In the below query, we pass the query via a function called mysqli_query with which we pass connection query and sql query as arguments. The function is called within if condition, and if it is successful, we send a success response else we send back a failure response.
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 onCreateLog(){
$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"]);
    $file = $obj->file;
    $date = $obj->date;
    $sql = "INSERT INTO log(file,date) VALUES ('$file','$date')";
    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 all data 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:

// Update Log Table
var http = "http://";
var uri = http + "localhost/<location_of_your_php_file/name_of_your_php_file>";
                    var log = {
                        file: fileName,
                        date: new Date()
                    };
                    $.ajax({
                        url: that.uri,
                        type: "POST",
                        data: {
                            method: "onCreateLog",
                            data: JSON.stringify(log)
                        },
                        dataType: "json",
                        success: function (dataClient) {
                            MessageBox.success("Log uploaded successfully!");
                        },
                        error: function (request, error) {
                            MessageBox.error(error);
                        }
                    });

 

Leave a comment

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