Tutorial's structure includes three files:
- index.php (with a list of record you want to delete)
- delete.php (PHP code to delete records into your database)
- prototype.js (to enable Ajax)
Step 1: include prototype.js
Download prototype.js and create a new page (index.php). Add this line of code in the tag on index.php to include prototype framework:
>
Step 2: HTML code
Image to have the following code in index.php:
...a simple list with names and a link to delete the user from the DB. Each link call a JavaScript function deleteUser() with argument the ID (primary key) of the user you want to delete. Database table USER has some attributes and a primary key (id_user_pk). You can generate dinamically this list using a for example a code like this:
<?php
/* Database connection */
include('config.php');
$getUser_sql = 'SELECT * FROM USER';
$getUser = mysql_query($getUser_sql);
?>
while ($row = mysql_fetch_array($getUser)) {?>
<?php echo $row['name']; ?> "#" onClick="deleteUser(<?phpecho $row['id_user_pk']; ?>)">delete
} ?>
<>
Step 3: delete.php
Create a new page (delete.php). This page contains a query PHP to delete the record passed in argument from javascript function deleteUser(id):
<?php
/* Database connection */
include('config.php');
if(isset($_POST['user_id'])){
$userID = $_POST['user_id'];
$sql = 'DELETE FROM USER where id_user_pk ="'.$userID.'"';
mysql_query($sql);
} else { echo '0'; }
?>
Step 4: Javascript function deleteUser(id)
This function pass with the method POST to the page delete.php the id of the user you want to delete from the table. Add the following lines of code below the code in step 2:
It's all. I hope it's clear :