How to Delete data from database using pdo in php

How to Delete data from database using pdo in php


In this post, you will be learning how to delete data from mysql database using pdo in php mysql.

Where we will be deleting the data from database using POST Method with its selected ID using pdo in php.


Step 1: Connect your Database using PDO.

<?php

$servername = "localhost";
$username = "root";
$password = "";
$database = "phptutorials";

try {

    $conn = new PDO("mysql:host=$servername;dbname=$database", $username, $password);
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // set the PDO error mode to exception
    // echo "Connected Successfully";
   
} catch(PDOException $e) {

    echo "Connection Failed" .$e->getMessage();
}

?>


Step 2: Add a DELETE Button in Html <table> of your fetch data as given below - (eg in: index.php) 

<td>
    <form action="code.php" method="POST">
        <button type="submit" name="delete_student" value="<?=$row->id;?>" class="btn btn-danger">Delete</button>
    </form>
</td>

Once you click on Delete button, it submits the form to the action code.php file.

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

<?php
session_start();
include('dbcon.php');

if(isset($_POST['delete_student']))
{
    $student_id = $_POST['delete_student'];

    try {

        $query = "DELETE FROM students WHERE id=:stud_id";
        $statement = $conn->prepare($query);
        $data = [
            ':stud_id' => $student_id
        ];
        $query_execute = $statement->execute($data);

        if($query_execute)
        {
            $_SESSION['message'] = "Deleted Successfully";
            header('Location: index.php');
            exit(0);
        }
        else
        {
            $_SESSION['message'] = "Not Deleted";
            header('Location: index.php');
            exit(0);
        }

    } catch(PDOException $e){
        echo $e->getMessage();
    }
}

?>


| To show the message, paste the below code in your required file:

<?php
session_start();
?>


<?php if(isset($_SESSION['message'])) : ?>
    <h5 class="alert alert-success"><?= $_SESSION['message']; ?></h5>
<?php
    unset($_SESSION['message']);
    endif;
?>


Thank you.