HOW TO DELETE DATA IN MYSQL USING PHP - CULT CODE


 

 

 

 

 

 

In this tutorial, we will learn how to DELETE data in MYSQL using PHP.

1. Create a table name user.

 Use the code below to create a table:
 
CREATE TABLE `user` (
  `id` int(11) NOT NULL,
  `username` varchar(251) NOT NULL,
  `email` varchar(251) NOT NULL,
  `password` varchar(251) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

 

 

 

 

 

 

2. Now create a file connect.php:

This file will help us to connect PHP to Mysql.
<?php
 
 $connect = mysqli_connect("localhost", "root", "password", "demo"); 
 
?>
 

3. Now create a file index.php:

In this file, we will create an HTML form and fetch data using PHP.

<?php

include('connect.php');

include('delete.php');

$data_query = "SELECT * FROM user LIMIT 1";

$data_result = mysqli_query($connect, $data_query);

if(mysqli_num_rows($data_result) > 0) {
	
	while($row = mysqli_fetch_array($data_result)){
		
		?>
		
		<h3>Delete Data</h3>
		
		<form method="POST" action="">
		
		<label style="margin-left:10px;margin-right:10px;">ID:</label>
		
		<input type="text" readonly name="id" value="<?php echo $row['id']; ?>" />
		
		
		<label style="margin-left:10px;margin-right:10px;">Name:</label>
		
		<input type="text" readonly name="username" value="<?php echo $row['username']; ?>" />
		
		
		<label style="margin-left:10px;margin-right:10px;">Email:</label>
		
		<input type="text" readonly name="email" value="<?php echo $row['email']; ?>" />
		
		<input type="submit" name="delete" value="Delete"></input>
		
		</form>
		
		<?php
		
	}
	
}else{
	echo '<h3>No any data found!</h3>';
}
?>
 

4. Now create a file delete.php:

This file will help us to DELETE existing data in MySQL using PHP.

<?php

if(isset($_POST['delete']))
	
	{
		include('connect.php');
		
		$id = mysqli_real_escape_string($connect, $_POST['id']);
		
		$sql = "DELETE FROM user WHERE id='$id'";
		
		if(mysqli_query($connect, $sql)){
			
			echo '<script>alert("Data Removed!")</script>';
			
		}else{
			
			echo '<script>alert("Something Went Wrong!")</script>';
			
		}
	}
	
	?>
 

5. Run your Project:

Step  1 : 

Click on Delete Button.

Step 2:


Step 3: 


Check Database:




 

Comments

Popular posts from this blog

HOW TO UPDATE+FETCH DATA IN PHP - CULT CODE

LOGIN/SIGNUP FORM WITH SESSION IN PHP MYSQL - CULT CODE

HOW TO FETCH DATA FROM MYSQL WITH WHERE CONDITION USING PHP - CULT CODE