How to Created PHP CRUD using OOPS with MYSQLi in MVC

PHP: CRUD (create, read, update, and delete) with databases is a common function of web applications. In this tutorial, you will learn how to develop CRUD operations with PHP and MySQL using the OOP (Object Oriented Programming) technique.

The tutorial is explained in easy steps handle of creating, reading, updating, and deleting functions in the customers data MySQL database using PHP OOP. You can also download the complete source code.

Because we cover this tutorial with download the complete source code of creating CRUD operations with PHP and MySQL using the Object Oriented Programming Technique (OOP) and the file structure for it.

Create MySQL Database and Table

In this tutorial, we will learn CRUD operation on customers data, so first we create customers Table on database.

--
-- Table structure for table `customers`
--

CREATE TABLE `customers` (
  `id` int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY,
  `name` varchar(100) NOT NULL,
  `email` varchar(100) NOT NULL,
  `username` varchar(100) NOT NULL,
  `password` varchar(100) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

Create Customer Class with CRUD method

We will now create class for MySQL database connections and CRUD operations, like Select, insert, update and delete with MySQL database. We’ll have a displayData() method for selecting customer records, an insertData() method for inserting customer records, an updateRecord() method for updating customer data, and a deleteRecord() method for deleting customer records. and displayRecordById() method for fetch single record. Here is a complete Customers class with all its methods. All you need to do is change the MySQL database connection details while it is running on your server.

customers.php

<?php

  class Customers
  {
    private $servername = "localhost";
    private $username   = "root";
    private $password   = "";
    private $database   = "blog_database";
    public  $con;


    // Database Connection 
    public function __construct()
    {
        $this->con = new mysqli($this->servername, $this->username,$this->password,$this->database);
        if(mysqli_connect_error()) {
       trigger_error("Failed to connect to MySQL: " . mysqli_connect_error());
        }else{
      return $this->con;
        }
    }

    // Insert customer data into customer table
    public function insertData($post)
    {
      $name = $this->con->real_escape_string($_POST['name']);
      $email = $this->con->real_escape_string($_POST['email']);
      $username = $this->con->real_escape_string($_POST['username']);
      $password = $this->con->real_escape_string(md5($_POST['password']));
      $query="INSERT INTO customers(name,email,username,password) VALUES('$name','$email','$username','$password')";
      $sql = $this->con->query($query);
      if ($sql==true) {
          header("Location:index.php?msg1=insert");
      }else{
          echo "Registration failed try again!";
      }
    }

    // Fetch customer records for show listing
    public function displayData()
    {
        $query = "SELECT * FROM customers";
        $result = $this->con->query($query);
    if ($result->num_rows > 0) {
        $data = array();
        while ($row = $result->fetch_assoc()) {
               $data[] = $row;
        }
       return $data;
        }else{
       echo "No found records";
        }
    }

    // Fetch single data for edit from customer table
    public function displyaRecordById($id)
    {
        $query = "SELECT * FROM customers WHERE id = '$id'";
        $result = $this->con->query($query);
    if ($result->num_rows > 0) {
          $row = $result->fetch_assoc();
            return $row;
        }else{
            echo "Record not found";
        }
    }

    // Update customer data into customer table
    public function updateRecord($postData)
    {
          $name = $this->con->real_escape_string($_POST['uname']);
          $email = $this->con->real_escape_string($_POST['uemail']);
          $username = $this->con->real_escape_string($_POST['upname']);
          $id = $this->con->real_escape_string($_POST['id']);
    if (!empty($id) && !empty($postData)) {
          $query = "UPDATE customers SET name = '$name', email = '$email', username = '$username' WHERE id = '$id'";
          $sql = $this->con->query($query);
          if ($sql==true) {
              header("Location:index.php?msg2=update");
          }else{
              echo "Registration updated failed try again!";
          }
        }
      
    }


    // Delete customer data from customer table
   public function deleteRecord($id)
   {
      $query = "DELETE FROM customers WHERE id = '$id'";
      $sql = $this->con->query($query);
      if ($sql==true) {
          header("Location:index.php?msg3=delete");
      }else{
          echo "Record does not delete try again";
      }
    }

}

?>

Insert Customer Record functionality

Now we will insert customer record using insertData() method from customers Class. For this, we will design a customer HTML Form in add.php file.

add.php

<?php

  // Include database file
  include 'customers.php';

  $customerObj = new Customers();

  // Insert Record in customer table
  if(isset($_POST['submit'])) {
    $customerObj->insertData($_POST);
  }

?>
<!DOCTYPE html>
<html lang="en">
<head>
  <title>PHP: CRUD (Add, Edit, Delete, View) Application using OOP (Object Oriented Programming) and MYSQL</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
  <link rel="stylesheet" href="https://pro.fontawesome.com/releases/v5.10.0/css/all.css"/>
</head>
<body>

<div class="card text-center" style="padding:15px;">
  <h4>PHP: CRUD (Add, Edit, Delete, View) Application using OOP (Object Oriented Programming) and MYSQL</h4>
</div><br> 

<div class="container">
  <form action="add.php" method="POST">
    <div class="form-group">
      <label for="name">Name:</label>
      <input type="text" class="form-control" name="name" placeholder="Enter name" required="">
    </div>
    <div class="form-group">
      <label for="email">Email address:</label>
      <input type="email" class="form-control" name="email" placeholder="Enter email" required="">
    </div>
    <div class="form-group">
      <label for="username">Username:</label>
      <input type="text" class="form-control" name="username" placeholder="Enter username" required="">
    </div>
    <div class="form-group">
      <label for="password">Password:</label>
      <input type="password" class="form-control" name="password" placeholder="Enter password" required="">
    </div>
    <input type="submit" name="submit" class="btn btn-primary" style="float:right;" value="Submit">
  </form>
</div>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
</body>
</html>

Output

How to Created PHP CRUD using OOPS with MYSQLi in MVC

Display Customer list functionality

Now we will display customer records using displyaData() method from customers Class. First we will create customer index using Bootstrap 4 table to show customer listing and font awesome icon to edit and delete icon.

index.php

<?php
  
  // Include database file
  include 'customers.php';

  $customerObj = new Customers();

  // Delete record from table
  if(isset($_GET['deleteId']) && !empty($_GET['deleteId'])) {
      $deleteId = $_GET['deleteId'];
      $customerObj->deleteRecord($deleteId);
  }
     
?> 
<!DOCTYPE html>
<html lang="en">
<head>
  <title>PHP: CRUD (Add, Edit, Delete, View) Application using OOP (Object Oriented Programming) and MYSQL</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
  <link rel="stylesheet" href="https://pro.fontawesome.com/releases/v5.10.0/css/all.css"/>
</head>
<body>

<div class="card text-center" style="padding:15px;">
  <h4>PHP: CRUD (Add, Edit, Delete, View) Application using OOP (Object Oriented Programming) and MYSQL</h4>
</div><br><br> 

<div class="container">
  <?php
    if (isset($_GET['msg1']) == "insert") {
      echo "<div class='alert alert-success alert-dismissible'>
              <button type='button' class='close' data-dismiss='alert'>&times;</button>
              Your Registration added successfully
            </div>";
      } 
    if (isset($_GET['msg2']) == "update") {
      echo "<div class='alert alert-success alert-dismissible'>
              <button type='button' class='close' data-dismiss='alert'>&times;</button>
              Your Registration updated successfully
            </div>";
    }
    if (isset($_GET['msg3']) == "delete") {
      echo "<div class='alert alert-success alert-dismissible'>
              <button type='button' class='close' data-dismiss='alert'>&times;</button>
              Record deleted successfully
            </div>";
    }
  ?>
  <h2>View Records
    <a href="add.php" class="btn btn-primary" style="float:right;">Add New Record</a>
  </h2>
  <table class="table table-hover">
    <thead>
      <tr>
        <th>Id</th>
        <th>Name</th>
        <th>Email</th>
        <th>Username</th>
        <th>Action</th>
      </tr>
    </thead>
    <tbody>
        <?php 
          $customers = $customerObj->displayData(); 
          foreach ($customers as $customer) {
        ?>
        <tr>
          <td><?php echo $customer['id'] ?></td>
          <td><?php echo $customer['name'] ?></td>
          <td><?php echo $customer['email'] ?></td>
          <td><?php echo $customer['username'] ?></td>
          <td>
            <a href="edit.php?editId=<?php echo $customer['id'] ?>" style="color:green">
              <i class="fa fa-pencil" aria-hidden="true"></i></a>&nbsp
            <a href="index.php?deleteId=<?php echo $customer['id'] ?>" style="color:red" onclick="confirm('Are you sure want to delete this record')">
              <i class="fa fa-trash" aria-hidden="true"></i>
            </a>
          </td>
        </tr>
      <?php } ?>
    </tbody>
  </table>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
</body>
</html>

Output

How to Created PHP CRUD using OOPS with MYSQLi in MVC

Update customer Record functionality

Now we will handle functionality to update and edit customer in file edit.php. first we will create customer edit HTML Form.

edit.php

<?php
  
  // Include database file
  include 'customers.php';

  $customerObj = new Customers();

  // Edit customer record
  if(isset($_GET['editId']) && !empty($_GET['editId'])) {
    $editId = $_GET['editId'];
    $customer = $customerObj->displyaRecordById($editId);
  }

  // Update Record in customer table
  if(isset($_POST['update'])) {
    $customerObj->updateRecord($_POST);
  }  
    
?>
<!DOCTYPE html>
<html lang="en">
<head>
  <title>PHP: CRUD (Add, Edit, Delete, View) Application using OOP (Object Oriented Programming) and MYSQL</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
  <link rel="stylesheet" href="https://pro.fontawesome.com/releases/v5.10.0/css/all.css"/>
</head>
<body>

<div class="card text-center" style="padding:15px;">
  <h4>PHP: CRUD (Add, Edit, Delete, View) Application using OOP (Object Oriented Programming) and MYSQL</h4>
</div><br> 

<div class="container">
  <form action="edit.php" method="POST">
    <div class="form-group">
      <label for="name">Name:</label>
      <input type="text" class="form-control" name="uname" value="<?php echo $customer['name']; ?>" required="">
    </div>
    <div class="form-group">
      <label for="email">Email address:</label>
      <input type="email" class="form-control" name="uemail" value="<?php echo $customer['email']; ?>" required="">
    </div>
    <div class="form-group">
      <label for="username">Username:</label>
      <input type="text" class="form-control" name="upname" value="<?php echo $customer['username']; ?>" required="">
    </div>
    <div class="form-group">
      <input type="hidden" name="id" value="<?php echo $customer['id']; ?>">
      <input type="submit" name="update" class="btn btn-primary" style="float:right;" value="Update">
    </div>
  </form>
</div>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
</body>
</html>

You can always support by sharing on social media or recommending my blog to your friends and colleagues. If you have any suggestions / problems about this tutorial, please comment on the form below.😊

8 Comments

Leave a Reply

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

  1. This is one of the better CRUD examples out there AND it works first time! Thanks!

    Too bad though you didn't separate all this into MVC. With everything MVC today, it would be great to have this wonderful tutorial using MVC.

    I hope you'll consider/do it.

  2. THANK YOU SO MUCH.. I TRIED 3 PHP CRUD FROM YOUTUBE BUT I ENCOUNTERED DIFFERENT PROBLEMS BUT WHEN I TRIED YOURS IT REALLY WORKS. THANK YOU SO MUCH FOR SAVING ME.