MySQLi Delete

Just as we have inserted records into tables in the previous post, we can delete records from a table using the DELETE statement. The MySQL DELETE keyword is used to delete table rows. Once the data is deleted, you cannot recover it. So always be careful while deleting the existing table.

Syntax

DELETE FROM Tablename [WHERE Clause]; 

These are the following ways to delete data from the 'employee' table -


Object Oriented PHP MySQLi Delete Data

The following code will delete the 'employee' data whose 'emp_id' is equal to 1 using PHP MySQLi object-oriented way.

<?php
$conn = new mysqli('hostname', 'username', 'password', 'databasename');
//Check for connection error
if($conn->connect_error){
  die("Error in DB connection: ".$conn->connect_errno." : ".$conn->connect_error);    
}
$delete = "DELETE FROM employee WHERE emp_id = '1' ";
if($conn->query($delete)){
 echo 'Data deleted successfully';
}
?>

The above example delete the employee row of emp_id = 1.





Procedural PHP MySQLi Delete Data

The following code will delete the 'employee' data whose 'emp_id' is equal to 3 using PHP MySQLi procedural way.

<?php
$conn = mysqli_connect('hostname', 'username', 'password', 'databasename');
//Check for connection error
if(mysqli_connect_error()){
  die("Error in DB connection: ".mysqli_connect_errno()." - ".mysqli_connect_error());
}
$delete = "DELETE FROM employee WHERE emp_id = '3' ";
if(mysqli_query($conn, $delete)){
  echo 'Data deleted successfully';
}
?>  
    

The above example delete the employee row of emp_id = 3.







Read more articles


General Knowledge



Learn Popular Language