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.

READ :  AngularJS Multiple File Upload example using Web API

readData();
?>



<title>Read and Display Card-Like List View</title>









    <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">
    
    </div>


    <!-- Modal -->
    <div class="modal fade" id="edit-modal" role="dialog">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close">
                        <span>×</span>
                    </button>
                </div>
                <div class="modal-body">
                    <form id="frmEdit">
                        <div class="gst form-group">
                            <div class="row">
                                <label>Title</label> 
                            </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> 
                            </div>
                        </div>

                        <div class="gst form-group">
                            <div class="row">
                                <label>Member Type</label> 
                            </div>
                        </div>

                        <div class="gst form-group">
                            <div class="row">
                                
                            </div>
                        </div>


                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary">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" role="dialog">
        <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">
                        <span>×</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">Close</button>
                </div>
            </div>
        </div>
    </div>
    <!-- Modal ends here -->


Create New Record

add.php

add($_POST);
    header("Location: index.php");
}
?>


<title>PHP CRUD - Create New Record</title>









    <div class="row">

        <div class="form-container">
            <form method="POST">
                <div class="gst form-group">
                    <div class="row">
                        <label>Title</label> 
                    </div>
                </div>

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

                <div class="gst form-group">
                    <div class="row">
                        <label>URL</label> 
                    </div>
                </div>

                <div class="gst form-group">
                    <div class="row">
                        <label>Member Type</label> 
                    </div>
                </div>


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

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



PHP Delete Data record

delete.php

delete($_POST["id"]);
    print_r(json_encode("Records deleted successfully"));
}
?>

PHP UPDATE Data record

edit.php

edit($_POST);
    print_r(json_encode("Records edited successfully"));
}
?>

Display Card-Like List View

list.php

 $v) {
        ?>
<div class="box-container">
    <div class="title">
        <a href=""></a>
    </div>
    <div class="memberinfo">...</div>
    <div class="membertype"></div>
    <div class="operation">
        <button class="btn-operation bn-edit"
            id="">Edit</button>
        <button class="btn-operation bn-delete"
            id="">Delete</button>
    </div>
</div>

Read Card-Like List View

read.php

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

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

 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 :  Vue js Add active class to current Navigation Menu

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 :  simple file upload component using VueJs

Leave a Reply

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