How to delete data using bindParam() function in php pdo
How to delete data using bindParam() in php pdo
In this post, you will be learning how to delete data using bindParam() function in php pdo.
Where we will be deleting the data from database using bindParam() function with POST Method with its selected ID in php pdo.
Step 1: Create a Database connection
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$database = "database_name";
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=? LIMIT 1";
$statement = $conn->prepare($query);
$statement->bindParam(1, $student_id, PDO::PARAM_INT);
$query_execute = $statement->execute();
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();
}
}
?>
Thank you.