Multiple Delete Data Using PHP/MySQL and PDO Query
Submitted by argie on Wednesday, December 4, 2013 - 18:16.
This tutorial will teach you on how to create an application in PHP/MySQL using PDO query that delete multiple data using checkbox as selector. I used checkbox as a selector in every row that u want to delete from database table. To understand more about this tutorial, fallow the steps bellow.
That's it, you've been successfully created a multiple delete data from database table using PHP/MySQL and PDO query.
Creating Our Database
First we are going to create our database which stores our data. To create a database: 1. Open phpmyadmin 2. Then create database and name it as "pdo_ret". 3. After creating a database name, click the SQL and paste the following code.- CREATE TABLE IF NOT EXISTS `members` (
- `id` int(11) NOT NULL AUTO_INCREMENT,
- `fname` varchar(100) NOT NULL,
- `lname` varchar(100) NOT NULL,
- `age` int(5) NOT NULL,
- ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
Creating our Database Connection
Next step is to create a database connection and save it as "connect.php". In this Step, we will write our connection script in PDO format.- <?php
- /* Database config */
- $db_host = 'localhost';
- $db_user = 'root';
- $db_pass = '';
- $db_database = 'pdo_ret';
- /* End config */
- $db = new PDO('mysql:host='.$db_host.';dbname='.$db_database, $db_user, $db_pass);
- $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
- ?>
Creting our Display Page
In this steps we will write our script that retrieve our data from database table and display the data with selectbox as a selector. Save this page as "index.php".- <form action="delete.php" method="post">
- <table border="1" cellspacing="0" cellpadding="2" >
- <thead>
- <tr>
- <th> </th>
- <th> First Name </th>
- <th> Last Name </th>
- <th> Age </th>
- </tr>
- </thead>
- <tbody>
- <?php
- include('connect.php');
- $result = $db->prepare("SELECT * FROM members ORDER BY id DESC");
- $result->execute();
- for($i=0; $row = $result->fetch(); $i++){
- ?>
- <tr class="record">
- <td><input name="selector[]" type="checkbox" value="<?php echo $row['id']; ?>"></td>
- <td><?php echo $row['fname']; ?></td>
- <td><?php echo $row['lname']; ?></td>
- <td><?php echo $row['age']; ?></td>
- </tr>
- <?php
- }
- ?>
- </tbody>
- </table>
- <input type="submit" value="delete" />
- </form>
Writing Our Multiple Delete Script
The code bellow will delete multiple data from database table. Copy the code bellow and save it as "delete.php".- <?php
- include('connect.php');
- $edittable=$_POST['selector'];
- for($i=0; $i < $N; $i++)
- {
- $result = $db->prepare("DELETE FROM members WHERE id= :memid");
- $result->bindParam(':memid', $edittable[$i]);
- $result->execute();
- }
- ?>
Add new comment
- 786 views