PHP: CRUD (Add, Edit, Delete, View) Application using OOP (Object Oriented Programming) and MYSQL

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.

Following file Structure

  • customers.php
  • add.php
  • edit.php

Create MySQL Database Table

-- Table structure for table `customers`
--
CREATE TABLE `customers` (
`id` int(100) NOT NULL,
`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

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

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>

Display Customer list functionality

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>

Update customer Record functionality

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>

PHP: CRUD (Add, Edit, Delete, View) Application using OOP (Object Oriented Programming) and MYSQL

Originally published at https://www.webscodex.com on October 4, 2020.

Webs Codex is programming and web development blog