PHP creating Object-Oriented CRUD System using PDO

Today, We want to share with you PHP creating Object-Oriented CRUD System using PDO and MySQLi.
In this post we will show you CRUD with PDO in PHP-MySQLi, hear for PHP PDO CRUD with Ajax Jquery and Bootstrap we will give you demo and example for implement.
In this post, we will learn about Create CRUD Application in OOP PHP with an example.

PHP creating Object-Oriented CRUD System using PDO and MySQLi

There are the Following The simple About PHP creating Object-Oriented CRUD System using PDO and MySQLi Full Information With Example and source code.

As I will cover this Post with live Working example to develop CRUD with PDO and OOP PHP, so the some major files and Directory structures for this example is following below.

  • index.php
  • add.php
  • edit.php
  • delete.php
  • list.php
  • read.php
  • MemberController.php
  • DBconnect.php
  • memberEvent.js
  • style.css

Creating the Table

Table structure for table `tbl_members`

CREATE TABLE `tbl_members` (
  `id` int(10) NOT NULL,
  `title` varchar(100) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL,
  `memberinfo` varchar(255) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL,
  `url` varchar(255) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL,
  `membertype` varchar(100) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL,
  `create_at` timestamp(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6) ON UPDATE CURRENT_TIMESTAMP(6)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

PHP creating Object-Oriented CRUD System using PDO MySQLi

Creating The Interface

index.php

This is where I will make a simple HTML form and PHP server side source code for our web application. To make the forms simply all souce code copy and write it into your any text editor Like Notepad++, then save file it as index.php.

<?php
include_once 'MemberController.php';
$membercontroller = new MemberController();
$data_response = $membercontroller->readData();
?>

<html>
<head>
<title>Read and Display Card-Like List View</title>
<link rel="stylesheet"
    href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script
    src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>
<link rel="stylesheet" type="text/css" href="styles.css">
<script src="memberEvent.js"></script>

</head>
<body>

    <div class="row">
        <a href="add.php"><button class="btn btn-success btn-add">Add New Record</button></a>
    </div>

    <div class="row" id="container">
    <?php require_once "list.php" ?>
    </div>


    <!-- Modal -->
    <div class="modal fade" id="edit-modal" tabindex="-1" role="dialog"
        aria-labelledby="exampleModalLabel" aria-hidden="true">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close"
                        data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">×</span>
                    </button>
                </div>
                <div class="modal-body">
                    <form id="frmEdit">
                        <div class="gst form-group">
                            <div class="row">
                                <label>Title</label> <input type="text"
                                    name="title" id="title"
                                    class="form-control">
                            </div>
                        </div>

                        <div class="gst form-group">
                            <div class="row">
                                <label>Description</label>
                                <textarea class="form-control"
                                    id="memberinfo"
                                    name="memberinfo"></textarea>
                            </div>
                        </div>

                        <div class="gst form-group">
                            <div class="row">
                                <label>URL</label> <input type="text"
                                    name="url" id="url"
                                    class="form-control">
                            </div>
                        </div>

                        <div class="gst form-group">
                            <div class="row">
                                <label>Member Type</label> <input
                                    type="text" name="membertype"
                                    id="membertype"
                                    class="form-control">
                            </div>
                        </div>

                        <div class="gst form-group">
                            <div class="row">
                                <input type="text" name="id"
                                    id="id" class="form-control"
                                    hidden="true">
                            </div>
                        </div>


                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary"
                        data-dismiss="modal">Close</button>
                    <button type="button" class="btn btn-success"
                        id="update">Save changes</button>
                </div>
            </div>
        </div>
    </div>
    <!-- Modal ends here -->

    <!-- Modal for message-->
    <div class="modal fade" id="messageModal" tabindex="-1"
        role="dialog" data-backdrop="static"
        aria-labelledby="exampleModalLabel" aria-hidden="true">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="exampleModalLabel">Message</h5>
                    <button type="button" class="close"
                        data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">×</span>
                    </button>
                </div>
                <div class="modal-body">
                    <h4 class="text-center" id="msg"></h4>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary"
                        data-dismiss="modal">Close</button>
                </div>
            </div>
        </div>
    </div>
    <!-- Modal ends here -->
</body>
</html>

Create New Record

add.php

<?php
if (isset($_POST["add"])) {
    include_once 'MemberController.php';
    $membercontroller = new MemberController();
    $data_response = $membercontroller->add($_POST);
    header("Location: index.php");
}
?>
<html>
<head>
<title>PHP CRUD - Create New Record</title>
<link rel="stylesheet"
    href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script
    src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>
<link rel="stylesheet" type="text/css" href="styles.css">
<script src="memberEvent.js"></script>

</head>
<body>

    <div class="row">

        <div class="form-container">
            <form method="POST">
                <div class="gst form-group">
                    <div class="row">
                        <label>Title</label> <input type="text"
                            name="title" id="title" class="form-control"
                            required>
                    </div>
                </div>

                <div class="gst form-group">
                    <div class="row">
                        <label>Member Information</label>
                        <textarea class="form-control" id="memberinfo"
                            name="memberinfo" required></textarea>
                    </div>
                </div>

                <div class="gst form-group">
                    <div class="row">
                        <label>URL</label> <input type="text" name="url"
                            id="url" class="form-control" required>
                    </div>
                </div>

                <div class="gst form-group">
                    <div class="row">
                        <label>Member Type</label> <input type="text"
                            name="membertype" id="membertype"
                            class="form-control" required>
                    </div>
                </div>


                <div class="gst form-group">
                    <div class="row">
                        <button class="btn btn-success" name="add">Submit</button>
                    </div>
                </div>

            </form>
        </div>
    </div>

</body>
</html>

PHP Delete Data record

delete.php

<?php
if(isset($_POST["id"])) {
    include_once 'MemberController.php';
    $membercontroller = new MemberController();
    $data_response = $membercontroller->delete($_POST["id"]);
    print_r(json_encode("Records deleted successfully"));
}
?>

PHP UPDATE Data record

edit.php

<?php
if(isset($_POST["id"])) {
    include_once 'MemberController.php';
    $membercontroller = new MemberController();
    $data_response = $membercontroller->edit($_POST);
    print_r(json_encode("Records edited successfully"));
}
?>

Display Card-Like List View

list.php

<?php
if (! empty($data_response)) {
    foreach ($data_response as $k => $v) {
        ?>
<div class="box-container">
    <div class="title">
        <a href="<?php echo $data_response[$k]["url"]; ?>"><?php echo $data_response[$k]["title"]; ?></a>
    </div>
    <div class="memberinfo"><?php echo $data_response[$k]["memberinfo"]; ?>...</div>
    <div class="membertype"><?php echo $data_response[$k]["membertype"]; ?></div>
    <div class="operation">
        <button class="btn-operation bn-edit"
            id="<?php echo $data_response[$k]["id"]; ?>">Edit</button>
        <button class="btn-operation bn-delete"
            id="<?php echo $data_response[$k]["id"]; ?>">Delete</button>
    </div>
</div>
<?php
    }
}
?>

Read Card-Like List View

read.php

<?php
    include_once 'MemberController.php';
    $membercontroller = new MemberController();
    switch($_POST["type"]) {
    
        case "single":
            
            if(isset($_POST["id"])) {
                $data_response = $membercontroller->readSingle($_POST["id"]);
                if(!empty($data_response)) {
                    $data_data_responseArray["title"] = $data_response[0]["title"];
                    $data_data_responseArray["memberinfo"] = $data_response[0]["memberinfo"];
                    $data_data_responseArray["url"] = $data_response[0]["url"];
                    $data_data_responseArray["membertype"] = $data_response[0]["membertype"];
                    echo json_encode($data_data_responseArray);
                }
            }
            break;
        case "all":
            $data_response = $membercontroller->readData();
            require_once "list.php";
            break;
            
        default:
            break;
    }

?>

Object-Oriented CRUD Controller

MemberController.php in PHP creating Object-Oriented CRUD System

<?php
include_once 'DBconnect.php';

class MemberController
{

    /* Fetch All */
    public function readData()
    {
        try {
            
            $dao = new DBconnect();
            
            $conn = $dao->openConnection();
            
            $sql = "SELECT id,title,memberinfo, url, membertype FROM `tbl_members` ORDER BY id DESC";
            
            $resource = $conn->query($sql);
            
            $data_response = $resource->fetchAll(PDO::FETCH_ASSOC);
            
            $dao->closeConnection();
        } catch (PDOException $e) {
            
            echo "There is some problem in connection: " . $e->getMessage();
        }
        if (! empty($data_response)) {
            return $data_response;
        }
    }

    /* Fetch Single Record by Id */
    public function readSingle($id)
    {
        try {
            
            $dao = new DBconnect();
            
            $conn = $member_operation->openConnection();
            
            $sql = "SELECT id,title,memberinfo, url, membertype FROM `tbl_members` WHERE id=" . $id . " ORDER BY id DESC";
            
            $resource = $conn->query($sql);
            
            $data_response = $resource->fetchAll(PDO::FETCH_ASSOC);
            
            $member_operation->closeConnection();
        } catch (PDOException $e) {
            
            echo "There is some problem in connection: " . $e->getMessage();
        }
        if (! empty($data_response)) {
            return $data_response;
        }
    }

    /* Add New Record */
    public function add($formArray)
    {
        $title = $_POST['title'];
        $memberinfo = $_POST['memberinfo'];
        $url = $_POST['url'];
        $membertype = $_POST['membertype'];
        
        $member_operation = new DBconnect();
        
        $conn = $member_operation->openConnection();
        
        $sql = "INSERT INTO `tbl_members`(`title`, `memberinfo`, `url`, `membertype`) VALUES ('" . $title . "','" . $memberinfo . "','" . $url . "','" . $membertype . "')";
        $conn->query($sql);
        $member_operation->closeConnection();
    }

    /* Edit a Record */
    public function edit($formArray)
    {
        $id = $_POST['id'];
        $title = $_POST['title'];
        $memberinfo = $_POST['memberinfo'];
        $url = $_POST['url'];
        $membertype = $_POST['membertype'];
        
        $member_operation = new DBconnect();
        
        $conn = $member_operation->openConnection();
        
        $sql = "UPDATE tbl_members SET title = '" . $title . "' , memberinfo='" . $memberinfo . "', url='" . $url . "', membertype='" . $membertype . "' WHERE id=" . $id;
        
        $conn->query($sql);
        $member_operation->closeConnection();
    }

    /* PHP creating Object-Oriented CRUD System Delete a Record */
    public function delete($id)
    {
        $member_operation = new DBconnect();
        
        $conn = $member_operation->openConnection();
        
        $sql = "DELETE FROM `tbl_members` where id='$id'";
        
        $conn->query($sql);
        $member_operation->closeConnection();
    }
}

?>

Creating the database connection

DBconnect.php

<?php

class DBconnect
{

    private $server = "mysql:host=localhost;dbname=phpsamples";

    private $user = "root";

    private $pass = "[email protected]";

    private $options = array(
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
    );

    protected $con;

    /* Function for opening connection */
    public function openConnection()
    
    {
        try 
        {
            
            $this->con = new PDO($this->server, $this->user, $this->pass, $this->options);
            
            return $this->con;
        } 
        catch (PDOException $e) 
        {
            
            echo "There is some problem in connection: " . $e->getMessage();
        }
    }

    /* Function for closing connection */
    public function closeConnection()
    {
        $this->con = null;
    }
}
?>

PHP CURD Insert Update Delete jQuery AJAX function

memberEvent.js

$(document).ready(function(){

	$(document).on('click' , '.bn-edit' ,function(){
			var id = this.id;
			$.ajax({
				url: 'read.php',
				type: 'POST',
				dataType: 'JSON',
				data: {"id":id,"type":"single"},
				success:function(data_data_response){
					$("#edit-modal").modal('show');
					$('#title').val(data_data_response.title);
					$('#memberinfo').val(data_data_response.memberinfo);
					$('#url').val(data_data_response.url);
					$("#membertype").val(data_data_response.membertype);
					$("#id").val(id);
				}
			});
		});
	
	
	$(document).on('click' , '#update' ,function(){
			$.ajax({
					url: 'edit.php',
					type: 'POST',
					dataType: 'JSON',
					data: $("#frmEdit").serialize(),
					success:function(data_data_response){
						$("#messageModal").modal('show');
						$("#msg").html(data_data_response);
						$("#edit-modal").modal('hide');
						loadData();
					}
				});
		});
	
	$(document).on('click' , '.bn-delete' ,function(){
		if(confirm("Are you sure want to delete the record?")) {
			var id = this.id;
			$.ajax({
				url: 'delete.php',
				type: 'POST',
				dataType: 'JSON',
				data: {"id":id},
				success:function(data_data_response){
					loadData();
				}
			});
		}
	});
});
	
function loadData() {
	$.ajax({
		url: 'read.php',
		type: 'POST',
		data: {"type":"all"},
		success:function(data_data_response){
			$("#container").html(data_data_response);
		}
	});
}

Custom CSS Styles for PHP CRUD

PHP creating Object-Oriented CRUD System Custom Css styles.

READ :  AngularJS ui router nested views - AngularJS nested directive controller example

style.css

form {
    padding: 10px;
}

.btn-add {
    margin:20px;
}

.form-container {
    margin: 0 auto;
    width:50%;
    border: #e2e2e2 1px solid;
    padding: 20px 40px;
    border-radius: 5px;
}

.box-container {
    margin: 20px;
    border: #e2e2e2 1px solid;
    width:450px;
    height:300px;
    padding: 20px;
    border-radius: 5px;
}

.title {
    margin: 10px 0px 20px 0px;
}

.memberinfo {
    margin-bottom: 20px;
}

.membertype {
    padding: 5px 20px;
    float: left;
    display: inline;
    border: #d4d4d4 1px solid;
    border-radius: 5px;
    background-color: #e2e2e2;
}

.operation .btn-operation{
    background-color: #64afff;
    border: #5ea5f1 1px solid;
    padding: 5px 20px;
    color: #FFF;
    border-radius: 5px;
}

.operation {
    float: right;
}

jQuery 15 Powerful Tips and Tricks for Developers and Web Designer

Read :

Summary

You can also read about AngularJS, ASP.NET, VueJs, PHP.

I hope you get an idea about CRUD with PDO and OOP PHP.
I would like to have feedback on my Infinityknow.com blog.
Your valuable feedback, question, or comments about this article are always welcome.
If you enjoyed and liked this post, don’t forget to share.

READ :  Timepicker Angularjs Example - Timepicker Example angular-time-picker

Add a Comment

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