CRUD Operation with REST API in PHP

 <?php


$servername = "localhost";
$username = "root";
$password = "";
$database = "test";

//Create Connection
$conn = new mysqli($servername, $username, $password, $database);

//Check Connection
if ($conn->connect_error) {
    die("Connection Failed: " . $conn->connect_error);
}
Above File is mysqli_conn.php which is included in below Files.







Below File is index.html File.
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>PHP REST API CRUD</title>
    <link rel="stylesheet" href="css/style.css">
</head>

<body>
    <table id="main" border="0" cellspacing="0">
        <tr>
            <td id="header">
                <h1>PHP REST API CRUD</h1>

                <div id="search-bar">
                    <label>Search :</label>
                    <input type="text" id="search" autocomplete="off">
                </div>
            </td>
        </tr>
        <tr>
            <td id="table-form">
                <form id="addForm">
                    Name: <input type="text" name="sname" id="sname">
                    Age: <input type="text" name="sage" id="sage">
                    City: <input type="text" name="scity" id="scity">
                    <input type="submit" id="save-button" value="Save">
                </form>
            </td>
        </tr>
        <tr>
            <td id="table-data">
                <table width="100%" cellpadding="10px">
                    <tr>
                        <th width="40px">Id</th>
                        <th>Name</th>
                        <th width="50px">Age</th>
                        <th width="150px">City</th>
                        <th width="60px">Edit</th>
                        <th width="70px">Delete</th>
                    </tr>
                    <tbody id="load-table">
                        <!--<tr>
                            <td class="center">1</td>
                            <td>Name 1</td>
                            <td>25</td>
                            <td>Delhi</td>
                            <td class="center"><button class="edit-btn" data-eid="">Edit</button></td>
                            <td class="center"><button class="delete-btn" data-eid="">Delete</button></td>
                        </tr>
                        <tr>
                            <td class="center">2</td>
                            <td>Name 2</td>
                            <td>23</td>
                            <td>Agra</td>
                            <td class="center"><button class="edit-btn" data-eid="">Edit</button></td>
                            <td class="center"><button class="delete-btn" data-eid="">Delete</button></td>
                        </tr>-->
                    </tbody>
                </table>
            </td>
        </tr>
    </table>

    <div id="error-message" class="messages"></div>
    <div id="success-message" class="messages"></div>

    <!-- Popup Modal Box for Update the records -->
    <div id="modal">
        <div id="modal-form">
            <h2>Edit Form</h2>
            <form action="" id="edit-form">
                <table cellpadding="10px" width="100%">
                    <tr>
                        <td>First Name</td>
                        <td><input type="text" name="sname" id="edit-name">
                            <input type="text" name="sid" id="edit-id" hidden="">
                        </td>
                    </tr>
                    <tr>
                        <td>Age</td>
                        <td><input type="number" name="sage" id="edit-age"></td>
                    </tr>
                    <tr>
                        <td>City</td>
                        <td><input type="text" name="scity" id="edit-city"></td>
                    </tr>
                    <tr>
                        <td></td>
                        <td><input type="button" id="edit-submit" value="Update"></td>
                    </tr>
                </table>
            </form>
            <div id="close-btn">X</div>
        </div>
    </div>

    <script type="text/javascript" src="js/jquery.js"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            //Fetch All Records
            function loadTable() {
                $("#load-table").html("");
                $.ajax({
                    url: "http://localhost/Rest_Api_Read_Data_PHP/api-fetch-all.php",
                    type: "GET",
                    error: function (textStatus, errorThrown) {
                        console.log("AJAX Request Failed:");
                        console.log("Status:", textStatus);
                        console.log("Error:", errorThrown);
                    },
                    success: function (data) {
                        if (data.status == false) {
                            $("#load-table").append("<tr><td colspan='6'><h2>" + data.message + "</h2></td></tr>");
                        }
                        else {
                            $.each(data, function (key, value) {
                                $("#load-table").append("<tr>"
                                    + "<td>" + value.id + "</td>" +
                                    "<td>" + value.student_name + "</td>" +
                                    "<td>" + value.age + "</td>" +
                                    "<td>" + value.city + "</td>" +
                                    "<td><button class='edit-btn' data-eid='" + value.id + "'>Edit</button></td>" +
                                    "<td><button class='delete-btn' data-did='" + value.id + "'>Delete</button></td>" +
                                    "</tr>");
                            });
                        }
                    }
                });
            }
            loadTable();

            //Show Success OR Error Messages
            function message(message, status) {
                if (status == true) {
                    $("#success-message").html(message).slideDown();
                    $("#error-message").slideUp();
                    setTimeout(function () {
                        $("#success-message").slideUp();
                    }, 4000);
                }
                else if (status == false) {
                    $("#error-message").html(message).slideDown();
                    $("#success-message").slideUp();
                    setTimeout(function () {
                        $("#error-message").slideUp();
                    }, 4000);
                }
            }

            //Function for form Data to JSON Object
            function jsonData(targetForm) {
                var arr = $(targetForm).serializeArray();

                var obj = {};
                for (var a = 0; a < arr.length; a++) {
                    if (arr[a].value == "") {
                        return false;
                    }
                    obj[arr[a].name] = arr[a].value;
                }
                var json_string = JSON.stringify(obj);
                return json_string;
            }

            //Insert New Record
            $("#save-button").on("click", function (e) {
                e.preventDefault();

                var jsonObject = jsonData("#addForm");

                if (jsonObject == false) {
                    message("All Fields are required.", false);
                }
                else {
                    $.ajax({
                        url: "http://localhost/Rest_Api_Read_Data_PHP/api-insert.php",
                        type: "POST",
                        data: jsonObject,
                        error: function (textStatus, errorThrown) {
                            console.log("AJAX Request Failed:");
                            console.log("Status:", textStatus);
                            console.log("Error:", errorThrown);
                        },
                        success: function (data) {
                            message(data.message, data.status);

                            if (data.status == true) {
                                loadTable();
                                $("#addForm").trigger("reset");
                            }
                        }
                    });
                }
            });

            //Delete Record
            $(document).on("click", ".delete-btn", function () {
                if (confirm("Do you really want to delete this record ?")) {
                    var studentId = $(this).data("did");
                    var obj = { sid: studentId };     //Converting to Object
                    //JSON.stringify() function is used to convert JavaScript Object to JSON
                    var myJSON = JSON.stringify(obj);   //Converting to JSON

                    var row = this;

                    $.ajax({
                        url: "http://localhost/Rest_Api_Read_Data_PHP/api-delete.php",
                        type: "POST",
                        data: myJSON,
                        error: function (textStatus, errorThrown) {
                            console.log("AJAX Request Failed:");
                            console.log("Status:", textStatus);
                            console.log("Error:", errorThrown);
                        },
                        success: function (data) {
                            message(data.message, data.status);

                            if (data.status == true) {
                                loadTable();
                                $(row).closest("tr").fadeOut();
                            }
                        }
                    });
                }
            });

            //Fetch Single Record : Show in Modal Box
            $(document).on("click", ".edit-btn", function () {
                $("#modal").show();
                var studentId = $(this).data("eid");
                var obj = { sid: studentId };   //Converting to Object
                //JSON.stringify() function is used to convert JavaScript Object to JSON
                var myJSON = JSON.stringify(obj);   //Converting to JSON

                $.ajax({
                    url: "http://localhost/Rest_Api_Read_Data_PHP/api-fetch-single.php",
                    type: "POST",
                    data: myJSON,
                    error: function (textStatus, errorThrown) {
                        console.log("AJAX Request Failed:");
                        console.log("Status:", textStatus);
                        console.log("Error:", errorThrown);
                    },
                    success: function (data) {
                        $("#edit-id").val(data[0].id);
                        $("#edit-name").val(data[0].student_name);
                        $("#edit-age").val(data[0].age);
                        $("#edit-city").val(data[0].city);
                    }
                });
            });

            //Hide Modal Box
            $("#close-btn").on("click", function () {
                $("#modal").hide();
            });

            //Update Record
            $("#edit-submit").on("click", function (e) {
                e.preventDefault();

                var jsonObject = jsonData("#edit-form");

                if (jsonObject == false) {
                    message("All Fields are required.", false);
                }
                else {
                    $.ajax({
                        url: "http://localhost/Rest_Api_Read_Data_PHP/api-update.php",
                        type: "POST",
                        data: jsonObject,
                        error: function (textStatus, errorThrown) {
                            console.log("AJAX Request Failed:");
                            console.log("Status:", textStatus);
                            console.log("Error:", errorThrown);
                        },
                        success: function (data) {
                            message(data.message, data.status);

                            if (data.status == true) {
                                $("#modal").hide();
                                loadTable();
                            }
                        }
                    });
                }
            });

            //Live Search Record
            $("#search").on("keyup", function () {
                var search_term = $(this).val();

                $("#load-table").html("");

                $.ajax({
                    url: "http://localhost/Rest_Api_Read_Data_PHP/api-search.php?search=" + search_term,
                    type: "GET",
                    error: function (textStatus, errorThrown) {
                        console.log("AJAX Request Failed:");
                        console.log("Status:", textStatus);
                        console.log("Error:", errorThrown);
                    },
                    success: function (data) {
                        if (data.status == false) {
                            $("#load-table").append("<tr><td colspan='6'><h2>" + data.message + "</h2></td></tr>");
                        }
                        else {
                            $.each(data, function (key, value) {
                                $("#load-table").append("<tr>" +
                                    "<td>" + value.id + "</td>" +
                                    "<td>" + value.student_name + "</td>" +
                                    "<td>" + value.age + "</td>" +
                                    "<td>" + value.city + "</td>" +
                                    "<td><button class='edit-btn' data-eid='" + value.id + "'>Edit</button></td>" +
                                    "<td><button class='delete-btn' data-did='" + value.id + "'>Delete</button></td>" +
                                    "</tr>"
                                );
                            });
                        }
                    }
                });
            });
        });
    </script>
</body>

</html>








Below File is api-delete.php File.
<?php

header("Content-Type: application/json");
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: DELETE");
header("Access-Control-Allow-Headers: Access-Control-Allow-Headers, Content-Type, Access-Control-Allow-Methods, Authorization, X-Requested-With");
//Above "X-Requested-With" means Whatever values comes for insert in database must with Ajax

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

$id = $data["sid"];

include("mysqli_conn.php");

$sql = "DELETE FROM students WHERE id = '{$id}'";

if ($conn->query($sql) == TRUE) {
    echo json_encode(array(
        "message" => "Student Record Deleted.",
        "status" => true
    ));
} else {
    echo json_encode(array(
        "message" => "Student Record Not Deleted.",
        "status" => false
    ));
}







Below File is api-fetch-all.php File.
<?php

header("Content-Type: application/json");
header("Access-Control-Allow-Origin: *");

include("mysqli_conn.php");

$sql = "SELECT * FROM students";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
    //The fetch_all() / mysqli_fetch_all() function fetches all result rows and returns the result-set as an associative array, a numeric array, or both.
    $output = $result->fetch_all(MYSQLI_ASSOC); //Fetch all rows and return the result-set as an associative array
    echo json_encode($output);
} else {
    echo json_encode(array(
        "message" => "No Record Found.",
        "status" => false
    ));
}







Below File is api-fetch-single.php File.
<?php

header("Content-Type: application/json");
header("Access-Control-Allow-Origin: *");

//Search through JSON Data as shown below:
$data = json_decode(file_get_contents("php://input"), true);

$student_id = $data["sid"];

//Search through URL as shown below :
// $student_id = isset($_GET["sid"]) ? $_GET["sid"] : die();

include("mysqli_conn.php");

$sql = "SELECT * FROM students WHERE id = {$student_id}";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
    //The fetch_all() / mysqli_fetch_all() function fetches all result rows and returns the result-set as an associative array, a numeric array, or both.
    $output = $result->fetch_all(MYSQLI_ASSOC); //Fetch all rows and return the result-set as an associative array
    echo json_encode($output);
} else {
    echo json_encode(array(
        "message" => "No Record Found.",
        "status" => false
    ));
}







Below File is api-insert.php File.
<?php

header("Content-Type: application/json");
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: POST");
header("Access-Control-Allow-Headers: Access-Control-Allow-Headers, Content-Type, Access-Control-Allow-Methods, Authorization, X-Requested-With");
//Above "X-Requested-With" means Whatever values comes for insert in database must with Ajax

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

$name = $data["sname"];
$age = $data["sage"];
$city = $data["scity"];

include("mysqli_conn.php");

$sql = "INSERT INTO students(student_name, age, city) VALUES('{$name}','{$age}','{$city}')";

if ($conn->query($sql) == TRUE) {
    echo json_encode(array(
        "message" => "Student Record Inserted.",
        "status" => true
    ));
} else {
    echo json_encode(array(
        "message" => "Student Record Not Inserted.",
        "status" => false
    ));
}








Below File is api-search.php File.
<?php

header("Content-Type: application/json");
header("Access-Control-Allow-Origin: *");

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

// $search_value = $data["search"];

//Search through URL as shown below :
$search_value = isset($_GET["search"]) ? $_GET["search"] : die();

include("mysqli_conn.php");

$sql = "SELECT * FROM students WHERE student_name LIKE '%{$search_value}%'";

$result = $conn->query($sql);

if ($result->num_rows > 0) {
    $output = $result->fetch_all(MYSQLI_ASSOC);
    echo json_encode($output);
} else {
    echo json_encode(array(
        "message" => "No Search Found.",
        "status" => false
    ));
}







Below File is api-update.php File.
<?php

header("Content-Type: application/json");
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: PUT");
header("Access-Control-Allow-Headers: Access-Control-Allow-Headers, Content-Type, Access-Control-Allow-Methods, Authorization, X-Requested-With");
//Above "X-Requested-With" means Whatever values comes for insert in database must with Ajax

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

$id = $data["sid"];
$name = $data["sname"];
$age = $data["sage"];
$city = $data["scity"];

include("mysqli_conn.php");

$sql = "UPDATE students SET student_name = '{$name}', age = '{$age}', city = '{$city}' WHERE id = '{$id}'";

if ($conn->query($sql) == TRUE) {
    echo json_encode(array(
        "message" => "Student Record Updated.",
        "status" => true
    ));
} else {
    echo json_encode(array(
        "message" => "Student Record Not Updated.",
        "status" => false
    ));
}








Below File is css/style.css File.
body {
    font-family: arial;
    background: #b2bec3;
    padding: 0;
    margin: 0;
}

.center {
    text-align: center;
}

#main {
    width: 800px;
    margin: 0 auto;
    background: #ffffff;
    font-size: 19px;
}

#header {
    background: #5D3F6A;
    color: #ffffff;
}

h1 {
    float: left;
    margin: 15px;
}

#search-bar {
    padding: 10px 20px 0;
    float: right;
}

#search-bar label {
    font-size: 16px;
    font-weight: bold;
    display: block;
}

#search-bar input {
    width: 250px;
    height: 25px;
    font-size: 18px;
    letter-spacing: 0.8px;
    padding: 3px 10px;
    border-radius: 4px;
    border: 1px solid #ffffff;
}

#search-bar input:focus {
    outline: 0;
}

#table-form {
    background: #FFB3A7;
    padding: 20px 10px;
}

#table-form input[type="text"] {
    height: 25px;
    font-size: 18px;
    padding: 3px 10px;
    margin-right: 17px;
    border-radius: 4px;
    border: 1px solid #5D3F6A;
    outline: 0;
}

#sage {
    width: 40px;
    padding: 3px 0 3px 10px;
}

#scity {
    width: 120px;
}

#save-button,
#edit-submit {
    background: #2c3e50;
    color: #ffffff;
    font-size: 18px;
    border: 0;
    padding: 8px 30px;
    margin-left: 7px;
    border-radius: 3px;
    cursor: pointer;
}

#save-button:focus,
#edit-submit:focus {
    outline: 0;
}

#table-data {
    padding: 15px;
    height: 500px;
    vertical-align: top;
}

#table-data th {
    background: #C93756;
    color: #ffffff;
}

#table-data tr:nth-child(odd) {
    background: #ecf0f1;
}

#table-data h2 {
    text-align: center;
}

#success-message,
#error-message {
    background: #DEF1D8;
    color: green;
    font-size: 30px;
    padding: 10px;
    margin: 10px;
    display: none;
    position: fixed;
    right: 15px;
    top: 15px;
    z-index: 20;
}

#error-message {
    background: #EFDCDD;
    color: red;
}

.delete-btn {
    background: #e74c3c;
    color: #ffffff;
    border: 0;
    padding: 4px 10px;
    border-radius: 3px;
    cursor: pointer;
}

.edit-btn {
    background: #27ae60;
    color: #ffffff;
    border: 0;
    padding: 4px 10px;
    border-radius: 3px;
    cursor: pointer;
}

#modal {
    background: rgba(0, 0, 0, 0.7);
    position: fixed;
    left: 0;
    top: 0;
    width: 100%;
    height: 100%;
    z-index: 10;
    display: none;
}

#modal-form {
    background: #ffffff;
    width: 30%;
    position: relative;
    top: 20%;
    left: calc(50% - 15%);
    padding: 15px;
    border-radius: 4px;
}

#modal-form h2 {
    margin: 0 0 15px;
    padding-bottom: 10px;
    border-bottom: 1px solid #000000;
}

#modal-form input[type="text"],
#modal-form input[type="number"] {
    width: 90%;
    height: 25px;
    font-size: 18px;
    padding: 3px 10px;
    margin-right: 17px;
    border-radius: 4px;
    border: 1px solid #5D3F6A;
    outline: 0;
}

#close-btn {
    background: #f90202;
    color: #ffffff;
    width: 30px;
    height: 30px;
    line-height: 30px;
    text-align: center;
    border-radius: 50%;
    position: absolute;
    top: -15px;
    right: -15px;
    cursor: pointer;
}
















Comments

Popular posts from this blog

GROUP BY Clause and HAVING Clause in PHP

Method Overriding in Traits in PHP

Mysqli database Connection and Display Table Data from Database