Creating CRUD Operation using PHP OOP Approach and SQLite3 Database Tutorial
Introduction
In this tutorial, you will learn how to create a CRUD (Create, Read, Update, and Delete) Operation using PHP OOP Approach and SQLite3 Database. This tutorial aims to provide the IT/CS students or those who are new to PHP Language a reference to learn with for learning and enhancing their programming capabilities. Here, I will show you the basic way to write a CRUD Operation program in PHP and SQLite. Snippets and sample source codes are also available or provided in this tutorial.
What is PHP?
PHP stands for Hypertext Preprocessor language. It is an open-source server-side programming language. A lot of developers or programmers use this programming language for creating websites with dynamic content. In addition, it is a general-purpose language that you can employ to create a variety of tasks, such as Graphical User Interfaces (GUIs).
What is SQLite3?
You can quickly build and utilize a database with the small using the free SQLite3 database. Despite not having all the features of a full-featured database, SQLite3 supports a surprising amount of the SQL standard and is the best option for both developers who require a straightforward database engine to integrate into their applications and those just learning SQL. Because of this, SQLite has gained enormous popularity among mobile app developers.
Getting Started
Before we start the coding part of this tutorial, please make sure to download any virtual server software such as XAMPP/WAMP to run our PHP Scripts on your local machine. After the successful installation, enable the sqlite3 library in your php.ini file. Lastly, make sure to run your Apache/Nginx or any equivalent of your download virtual server. In XAMPP/WAMP, open the software's Control Panel and start the Apache.
Creating the Database Class
The following script is a PHP file. It is written using the OOP (Object-Orient Programming) Approach in PHP which contains the database class. The class extends the SQLite3 Library and contains the connection and query objects. In my case, I save the file as db-connect.php.
- <?php
- function my_udf_md5($string) {
- }
- Class Database extends SQLite3{
- private $allowed_field;
- function __construct(){
- $this->open(db_file);
- `ID` INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
- `fullname` INTEGER NOT NULL,
- `email` TEXT NOT NULL,
- `contact` TEXT NOT NULL,
- `address` TEXT NOT NULL,
- `created_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
- `updated_at` TIMESTAMP DEFAULT NULL
- )");
- $this->allowed_field = ['ID', 'fullname', 'email', 'contact', 'address'];
- BEGIN
- UPDATE `member_list` SET `updated_at` = CURRENT_TIMESTAMP where ID = ID;
- END
- ");
- }
- function __destruct(){
- $this->close();
- }
- function sanitize_string($string = ""){
- }
- return $string;
- }
- public function insert($data = []){
- return ['status' => 'failed', "error" => "Data must be an array."];
- }else{
- return ['status' => 'failed', "error" => "Data is empty"];
- $fields = "";
- $values = "";
- foreach($data as $k => $v){
- $v = $this->sanitize_string($v);
- $fields .= "`{$k}`";
- $values .= "'{$v}'";
- }
- }
- return ['status' => 'failed', "error" => "Given data fields are not allowed"];
- $sql = "INSERT INTO `member_list` ({$fields}) VALUES ({$values})";
- $save = $this->query($sql);
- if($save){
- return ['status' => 'success'];
- }else{
- return ['status' => 'failed', "error" => $this->lastErrorMsg()];
- }
- }
- }
- public function get_results(){
- $sql = "SELECT * FROM `member_list` order by ID asc";
- $query = $this->query($sql);
- $data = [];
- while($row = $query->fetchArray()){
- $data[] = $row;
- }
- }
- public function get_single_by_id($id){
- $id = $this->sanitize_string($id);
- $sql = "SELECT * FROM `member_list` where `ID` = '{$id}'";
- $query = $this->query($sql);
- return $query->fetchArray();
- }
- public function update($data=[]){
- return ['status' => 'failed', "error" => "Data must be an array."];
- }else{
- return ['status' => 'failed', "error" => "Data is empty"];
- $update_data = "";
- foreach($data as $k => $v){
- $v = $this->sanitize_string($v);
- $update_data .= "`{$k}`= '{$v}'";
- }
- }
- return ['status' => 'failed', "error" => "Given data fields are not allowed"];
- $id = $this->sanitize_string($data['id']);
- $sql = "UPDATE `member_list` set {$update_data} where ID = '{$id}'";
- $save = $this->query($sql);
- if($save){
- return ['status' => 'success'];
- }else{
- return ['status' => 'failed', "error" => $this->lastErrorMsg()];
- }
- }
- }
- public function delete($id=""){
- return ['status' => 'failed', "error" => "ID is required."];
- return ['status' => 'failed', "error" => "ID cannot be a string."];
- $sql = "DELETE FROM `member_list` where `ID` = '{$id}'";
- $delete = $this->query($sql);
- if($delete){
- return ['status' => 'success'];
- }else{
- return ['status' => 'failed', "error" => $this->lastErrorMsg()];
- }
- }
- }
- ?>
Creating the APIs
The following script is also a PHP file that holds the "Actions Class" and contains all the functions or objects needed for this sample CRUD Application. This class extends the Database Class to execute queries. I save this file as functions.php.
- <?php
- require_once('db-connect.php');
- Class Actions extends Database{
- function __construct(){
- parent::__construct();
- }
- function __destruct(){
- parent::__destruct();
- }
- public function insert_member(){
- $insert = $this->insert($_POST);
- if($insert['status'] == 'success'){
- $_SESSION['success_msg'] = "New member has been added successfully.";
- exit;
- $_SESSION['form_error_msg'] = $insert['error'];
- }else{
- $_SESSION['form_error_msg'] = "An error occurred while inserting data due to unknown reason";
- }
- $data = [];
- foreach($_POST as $k => $v){
- $data[$k] = $v;
- }
- }
- public function member_list(){
- return $this->get_results();
- }
- public function get_member_by_id($id){
- return $this->get_single_by_id($id);
- }
- public function update_member(){
- $update = $this->update($_POST);
- if($update['status'] == 'success'){
- $_SESSION['success_msg'] = "Member Details has been updated successfully.";
- exit;
- $_SESSION['form_error_msg'] = $update['error'];
- }else{
- $_SESSION['form_error_msg'] = "An error occurred while updating data due to unknown reason";
- }
- $data = [];
- foreach($_POST as $k => $v){
- $data[$k] = $v;
- }
- }
- public function delete_member($id){
- $delete = $this->delete($id);
- if($delete['status'] == 'success'){
- $_SESSION['success_msg'] = "Member has been deleted successfully.";
- exit;
- $_SESSION['error_msg'] = $delete['error'];
- }else{
- $_SESSION['error_msg'] = "An error occurred while deleting data due to unknown reason";
- }
- }
- }
- $action = new Actions();
- ?>
Creating the Interface and Form
The following file script consists of HTML and PHP scripts. It has the code for the elements needed for the form and the page interface of the sample site. It uses CDN for the external libraries for better user design such as the Bootstrap Framework. You will need to have an internet connection to run the page design properly or as intended. I save this file as index.php.
- <?php
- require_once("functions.php");
- if($_SERVER['REQUEST_METHOD'] == "POST"){
- if(empty($_POST['id'])){
- $action->insert_member();
- }else{
- $action->update_member();
- }
- }
- if(isset($_GET['action'])){
- switch($_GET['action']){
- case 'edit':
- $data = $action->get_member_by_id($_GET['id']);
- break;
- case 'delete':
- $data = $action->delete_member($_GET['id']);
- break;
- }
- }
- ?>
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <meta http-equiv="X-UA-Compatible" content="IE=edge">
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <!-- Fontawsome -->
- <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.0/css/all.min.css" integrity="sha512-xh6O/CkQoPOWDdYTDqeRdPCVd1SpvCA9XXcUnZS2FmJNp1coAFzvtCN9BmamE+4aHK8yyUHUSCcJHgXloTyT2A==" crossorigin="anonymous" referrerpolicy="no-referrer" />
- <!-- Bootstrap CSS -->
- <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" integrity="sha384-Zenh87qX5JnK2Jl0vWa8Ck2rdkQ2Bzep5IDxbcnCeuOxjzrPF/et3URy9Bv1WTRi" crossorigin="anonymous">
- <!-- jQuery -->
- <!-- Bootstrap Bundle JS -->
- <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-OERcA2EqjJCMA+/3y+gxIOqMEjwtxJY7qPCqsdltbNJuaOe923+mo//f6V8Qbsw3" crossorigin="anonymous"></script>
- <style>
- html,body{
- height:100%;
- width:100%;
- }
- </style>
- </head>
- <body>
- <main>
- <nav class="navbar navbar-expand-lg navbar-dark bg-primary bg-gradient">
- <div class="container">
- <a class="navbar-brand" href="#">
- CRUD using PHP and SQLite
- </a>
- <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
- </button>
- <div class="collapse navbar-collapse" id="navbarNav">
- <ul class="navbar-nav">
- <li class="nav-item">
- </li>
- </ul>
- </div>
- <div>
- </div>
- </div>
- </nav>
- <div class="container my-3 py-2">
- <div class="row">
- <div class="col-lg-5 col-md-6 col-sm-12">
- <div class="card rounded-0 shadow">
- <div class="card-header">
- </div>
- <div class="card-body rounded-0">
- <div class="container-fluid">
- <form id="sample-form" action="" method="POST">
- <?php if(isset($_SESSION['form_error_msg'])): ?>
- <div class="alert alert-danger rounded-0">
- <?= $_SESSION['form_error_msg'] ?>
- </div>
- <?php unset($_SESSION['form_error_msg']); ?>
- <?php endif; ?>
- <input type="hidden" name="id" value="<?= isset($data['ID']) ? $data['ID'] : '' ?>">
- <div class="mb-3">
- <input type="text" class="form-control rounded-0" id="fullname" name="fullname" value="<?= isset($data['fullname']) ? $data['fullname'] : '' ?>" required="required">
- </div>
- <div class="mb-3">
- <input type="email" class="form-control rounded-0" id="email" name="email" value="<?= isset($data['email']) ? $data['email'] : '' ?>" required="required">
- </div>
- <div class="mb-3">
- <input type="text" class="form-control rounded-0" id="contact" name="contact" value="<?= isset($data['contact']) ? $data['contact'] : '' ?>" required="required">
- </div>
- <div class="mb-3">
- </div>
- </form>
- </div>
- </div>
- <div class="card-header rounded-0 py-2">
- <div class="d-flex justify-content-center">
- </div>
- </div>
- </div>
- </div>
- <div class="col-lg-7 col-md-6 col-sm-12">
- <?php if(isset($_SESSION['success_msg'])): ?>
- <div class="alert alert-success rounded-0">
- <?= $_SESSION['success_msg'] ?>
- </div>
- <?php unset($_SESSION['success_msg']); ?>
- <?php endif; ?>
- <?php if(isset($_SESSION['error_msg'])): ?>
- <div class="alert alert-danger rounded-0">
- <?= $_SESSION['error_msg'] ?>
- </div>
- <?php unset($_SESSION['error_msg']); ?>
- <?php endif; ?>
- <div class="card shadow rounded-0">
- <div class="card-header">
- </div>
- <div class="card-body">
- <div class="container-fluid">
- <table class="table table-bordered table-hover table-striped">
- <colgroup>
- <col width="5%">
- <col width="20%">
- <col width="15%">
- <col width="15%">
- <col width="30%">
- <col width="15%">
- </colgroup>
- <thead>
- <tr class="bg-primary text-light">
- </tr>
- </thead>
- <tbody>
- <?php
- $members = $action->member_list();
- ?>
- <?php if($members['num_rows'] > 0): ?>
- <?php foreach($members['data'] as $row): ?>
- <tr>
- <td class="p-1 text-center">
- </td>
- </tr>
- <?php endforeach; ?>
- <?php else: ?>
- <tr>
- </tr>
- <?php endif; ?>
- </tbody>
- </table>
- </div>
- </div>
- </div>
- </div>
- </div>
- </div>
- </main>
- </body>
- <script>
- $(document).ready(function(){
- $('#reset-form').click(function(e){
- e.preventDefault()
- if($("[name='id']").val() !== ""){
- location.replace("./")
- }
- $('#sample-form')[0].reset()
- })
- })
- </script>
- </html>
Snapshot
Here's the sample snapshot of this sample web application with CRUD functionalities.
DEMO VIDEO
That's it! You can now test this sample web application on your local machine that demonstrates the CRUD Operation using PHP OOP Approach and SQLite3 Database. You can also download this sample application's complete source code on this website for free. The download button is located below this article. Feel free to download and modify it.
That's the end of this tutorial. I hope this will help you with what you are looking for and that you'll find this useful for your current and future PHP Projects.
Explore more on this website for more Tutorials and Free Source Codes.
Happy Coding :)
Add new comment
- 805 views