How to delete data from database using oop in php mysql

How to delete data from database using oop in php mysql.

In this post, you will be learning how to delete data from database by id using oop concept in php mysql.

We are using bootstrap v5 to design the html form/user interface.

Let's get started with delete data in php mysql using oops.

Step 1: Add a Delete button in your fetched data from database (eg: student-view.php) as follows.

<td>
    <form action="student-code.php" method="POST">
        <button type="submit" name="deleteStudent" value="<?= $row['id'] ?>" class="btn btn-danger">Delete</button>
    </form>
</td>


Step 2: Create a student-code.php file and paste the below code:

<?php
include('dbconn.php');
include_once('StudentController.php');

if(isset($_POST['deleteStudent']))
{
    $id = mysqli_real_escape_string($db->conn, $_POST['deleteStudent']);
    $student = new StudentController;
    $result = $student->delete($id);
    if($result)
{
        $_SESSION['message'] = "Student Added Successfully";
        header("Location: student-view.php");
        exit(0);
    }
else
{
        $_SESSION['message'] = "Student Not Added";
        header("Location: student-view.php");
        exit(0);
    }
}
?>


Step 3: Create a StudentController.php file and paste the below code:

<?php

class StudentController
{
    public function __construct()
    {
        $db = new DatabaseConnection;
        $this->conn = $db->conn;
    }

    public function delete($id)
    {
        $student_id = mysqli_real_escape_string($this->conn,$id);
        $studentDeleteQuery = "DELETE FROM students WHERE id='$student_id' LIMIT 1";
        $result = $this->conn->query($studentDeleteQuery);
        if($result){
            return true;
        }else{
            return false;
        }
    }
}
?>


Thank for reading.