Delete Data From MySQL Using PHP - Tutorial makcode.in
For deleting data from MySQL the DELETE statement is used. We can delete data from specific column or all column of a table.
For delete selected column data from database the SQL query is
DELETE FROM table_name WHERE some_column=column_value;
The SQL query for delete all the column data from a table
DELETE FROM table_name;
or
DELETE * FROM table_name;
- database.php- To connecting database
- delete.php- For getting data from database with delete option
- delete-process.php- For remove data from database or from your table
database.php
<?php
$url='localhost';
$username='root';
$password='';
$conn=mysqli_connect($url,$username,$password,"user_details");
if(!$conn){
die('Could not Connect My Sql:' .mysql_error());
}
?>
delete.php
<?php
include_once 'database.php';
$result = mysqli_query($conn,"SELECT * FROM details");
?>
<!DOCTYPE html>
<html>
<head>
<title>Delete user details</title>
</head>
<body>
<table>
<tr>
<td>Id</td>
<td>First Name</td>
<td>Last Name</td>
<td>City</td>
<td>Email id</td>
<td>Action</td>
</tr>
<?php
$i=0;
while($row = mysqli_fetch_array($result)) {
?>
<tr class="<?php if(isset($classname)) echo $classname;?>">
<td><?php echo $row["id"]; ?></td>
<td><?php echo $row["firstname"]; ?></td>
<td><?php echo $row["lastname"]; ?></td>
<td><?php echo $row["city"]; ?></td>
<td><?php echo $row["email"]; ?></td>
<td><a href="delete-process.php?id=<?php echo $row["id"]; ?>">Delete</a></td>
</tr>
<?php
$i++;
}
?>
</table>
</body>
</html>
delete-process.php
<?php
include_once 'database.php';
$sql = "DELETE FROM details WHERE id='" . $_GET["id"] . "'";
if (mysqli_query($conn, $sql)) {
echo "Record deleted successfully";
} else {
echo "Error deleting record: " . mysqli_error($conn);
}
mysqli_close($conn);
?>