OOP CRUD Operation using AJAX/jQuery in PHP

June 17, 2020
PHP
oop crud in php

Getting Started

Please take note that CSS and jQuery used in this tutorial are hosted, so you need an internet connection for them to work.

Creating a Database

The first step is to create our database.

1. Open phpMyAdmin.

2. Click databases, create a database and name it as crud_oop.

3. After creating a database, click the SQL and paste the below codes. See image below for detailed instruction.

CREATE TABLE `member` (
  `memberid` INT(11) NOT NULL AUTO_INCREMENT,
  `firstname` VARCHAR(50) NOT NULL,
  `lastname` VARCHAR(50) NOT NULL,
PRIMARY KEY(`memberid`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

oop crud in php

Creating a Connection

Next, we create our connection to our database. This will serve as the bridge between our forms and database. We name this as conn.php.

<?php
 
$conn = new mysqli("localhost", "root", "", "crud_oop");
 
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}
 
?>

index.php

We create our index that contains our table.

<!DOCTYPE html>
<html>
<head>
    <title>PHP - OOP CRUD Operation using AJAX/jQuery</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
    <body>
<div class="container">
    <div style="height:50px;"></div>
    <div class="well" style="margin-left:auto; margin-right:auto; padding:auto; width:70%;">
        <span style="font-size:25px; color:blue"><strong>PHP - OOP CRUD Operation using AJAX/jQuery</strong></span>	
        <span class="pull-right"><a id="add" style="cursor:pointer;" class="btn btn-primary"><span class="glyphicon glyphicon-plus"></span> Add New</a></span>
        <div style="height:15px;"></div>
        <div id="table"></div>
        <div id="alert" class="alert alert-success" style="display:none;">
            <center><span id="alerttext"></span></center>
        </div>
    </div>
    <?php include('modal.php'); ?>
    <script src="custom.js"></script>
</div>
</body>
</html>

custom.js

This contains our AJAX and jQuery codes.

$(document).ready(function(){
    showTable();
 
    //add
    $('#add').click(function(){
        $('#addnew').modal('show');
        $('#addForm')[0].reset();
    });
 
    $('#addbutton').click(function(){
        var first = $('#firstname').val();
        var last = $('#lastname').val();
        if(first!='' && last!==''){
            var addForm = $('#addForm').serialize();
            $.ajax({
                type: 'POST',
                url: 'add.php',
                data: addForm,
                success:function(){
                    $('#addnew').modal('hide');
                    $('#addForm')[0].reset();
                    showTable();
                    $('#alert').slideDown();
                    $('#alerttext').text('Member Added Successfully');
                }
            });
        }
        else{
            alert('Please input both Fields')
        }
 
    });
    //
    //edit
    $(document).on('click', '.edit', function(){
        var memid = $(this).data('id');
        var first = $('#first'+memid).text();
        var last = $('#last'+memid).text();
        $('#editmem').modal('show');
        $('#efirstname').val(first);
        $('#elastname').val(last);
        $('#editbutton').val(memid);
    });
 
    $('#editbutton').click(function(){
        var memid = $(this).val();
        var editForm = $('#editForm').serialize();
        $.ajax({
            type: 'POST',
            url: 'edit.php',
            data: editForm + "&memid="+memid,
            success:function(){
                $('#editmem').modal('hide');
                $('#editForm')[0].reset();
                showTable();
                $('#alert').slideDown();
                $('#alerttext').text('Member Updated Successfully');
            }
        });
    });
    //
    //delete
    $(document).on('click', '.delete', function(){
        var memid = $(this).data('id');
        var first = $('#first'+memid).text();
        $('#delmem').modal('show');
        $('#dfirstname').text(first);
        $('#delbutton').val(memid);
    });
 
    $('#delbutton').click(function(){
        var memid = $(this).val();
        $.ajax({
            type: 'POST',
            url: 'delete.php',
            data: {
                memid: memid,
            },
            success:function(){
                $('#delmem').modal('hide');
                showTable();
                $('#alert').slideDown();
                $('#alerttext').text('Member Deleted Successfully');
            }
        });
    });
 
});
 
function showTable(){
    $.ajax({
        type: 'POST',
        url: 'fetch.php',
        data: {
            fetch: 1
        },
        success:function(data){
            $('#table').html(data);
        }
    });
}

fetch.php

This is our code in fetching table data from our database.

<?php
    include('conn.php');
    if(isset($_POST['fetch'])){
        ?>
        <table class="table table-striped table-bordered table-hover">
            <thead>
                <th>Firstname</th>
                <th>Lastname</th>
                <th>Action</th>
            </thead>
            <tbody>
            <?php
                $query=$conn->query("select * from `member`");
                while($row=$query->fetch_array()){
                    ?>
                    <tr>
                        <td><span id="first<?php echo $row['memberid']; ?>"><?php echo $row['firstname']; ?></span></td>
                        <td><span id="last<?php echo $row['memberid']; ?>"><?php echo $row['lastname']; ?></span></td>
                        <td>
                            <a style="cursor:pointer;" class="btn btn-warning edit" data-id="<?php echo $row['memberid']; ?>"><span class="glyphicon glyphicon-edit"></span> Edit</a> || 
                            <a style="cursor:pointer;" class="btn btn-danger delete" data-id="<?php echo $row['memberid']; ?>"><span class="glyphicon glyphicon-trash"></span> Delete</a>
                        </td>
                    </tr>
                    <?php
                }
 
            ?>
            </tbody>
        </table>
        <?php
    }
?>

modal.php

This contains our add, edit and delete modal.

<!-- Add New -->
    <div class="modal fade" id="addnew" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
                    <center><h4 class="modal-title" id="myModalLabel">Add New Member</h4></center>
                </div>
                <div class="modal-body">
                <div class="container-fluid">
                <form id="addForm">
                    <div class="row">
                        <div class="col-md-2">
                            <label class="control-label" style="position:relative; top:7px;">Firstname:</label>
                        </div>
                        <div class="col-md-10">
                            <input type="text" class="form-control" name="firstname" id="firstname">
                        </div>
                    </div>
                    <div style="height:10px;"></div>
                    <div class="row">
                        <div class="col-md-2">
                            <label class="control-label" style="position:relative; top:7px;">Lastname:</label>
                        </div>
                        <div class="col-md-10">
                            <input type="text" class="form-control" name="lastname" id="lastname">
                        </div>
                    </div>
                </div> 
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal"><span class="glyphicon glyphicon-remove"></span> Cancel</button>
                    <button type="button" id="addbutton" class="btn btn-primary"><span class="glyphicon glyphicon-floppy-disk"></span> Save</a>
                </form>
                </div>
 
            </div>
        </div>
    </div>
 
<!-- Edit -->
    <div class="modal fade" id="editmem" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
                    <center><h4 class="modal-title" id="myModalLabel">Edit Member</h4></center>
                </div>
                <div class="modal-body">
                <div class="container-fluid">
                <form id="editForm">
                    <div class="row">
                        <div class="col-md-2">
                            <label class="control-label" style="position:relative; top:7px;">Firstname:</label>
                        </div>
                        <div class="col-md-10">
                            <input type="text" class="form-control" name="efirstname" id="efirstname">
                        </div>
                    </div>
                    <div style="height:10px;"></div>
                    <div class="row">
                        <div class="col-md-2">
                            <label class="control-label" style="position:relative; top:7px;">Lastname:</label>
                        </div>
                        <div class="col-md-10">
                            <input type="text" class="form-control" name="elastname" id="elastname">
                        </div>
                    </div>
                </div> 
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal"><span class="glyphicon glyphicon-remove"></span> Cancel</button>
                    <button type="button" id="editbutton" class="btn btn-warning"><span class="glyphicon glyphicon-check"></span> Update</a>
                </form>
                </div>
 
            </div>
        </div>
    </div>
 
<!-- Delete -->
    <div class="modal fade" id="delmem" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
                    <center><h4 class="modal-title" id="myModalLabel">Delete Member</h4></center>
                </div>
                <div class="modal-body">
                <div class="container-fluid">
                    <h5><center>Firstname: <strong><span id="dfirstname"></span></strong></center></h5> 
                </div> 
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal"><span class="glyphicon glyphicon-remove"></span> Cancel</button>
                    <button type="button" id="delbutton" class="btn btn-danger"><span class="glyphicon glyphicon-trash"></span> Delete</button>
                </div>
 
            </div>
        </div>
    </div>

add.php

This is our code in adding data to our database.

<?php
    include('conn.php');
    if(isset($_POST['firstname'])){
        $firstname=$_POST['firstname'];
        $lastname=$_POST['lastname'];
 
        $conn->query("insert into member (firstname, lastname) values ('$firstname', '$lastname')");
    }
 
?>

edit.php

This is our code in updating existing row in our database.

<?php
    include('conn.php');
    if(isset($_POST['efirstname'])){
        $firstname=$_POST['efirstname'];
        $lastname=$_POST['elastname'];
        $memid=$_POST['memid'];
 
        $conn->query("update member set firstname='$firstname', lastname='$lastname' where memberid='$memid'");
    }
?>

delete.php

Lastly, our code in deleting rows.

<?php
    include('conn.php');
    if(isset($_POST['memid'])){
        $memid=$_POST['memid'];
 
        $conn->query("delete from member where memberid='$memid'");
    }
?>

That ends this tutorial. If you have any comment, suggestion or question, feel free to write it below or message me. Happy Coding!

Download Code

Leave a Reply

Your email address will not be published. Required fields are marked *