PHP : MySQL DELETE Statement

The MySQL DELETE statement is used to delete existing records from a database table. We can delete records based on some conditions.

Syntax:

The following is the generic syntax of the DELETE command to delete data from a MySQL table.
DELETE FROM table_name WHERE condition;

  • The WHERE clause is very useful when you want to delete selected records in a table. If the WHERE clause is not specified, then all the records will be deleted from the MySQL table.
  • We can specify any condition using the WHERE clause.
  • We can delete records from a single table at a time.
<?php
/**
 * Create Database Connection
 */
 
$database_server = 'localhost';
$database_username = 'root';
$database_password = '';
$database_name = 'student';
 
// Create connection using mysqli_connect()
$conn = mysqli_connect($database_server, $database_username, $database_password, $database_name);
 
// If $conn is false, connection is failed
if (!$conn ) {
  die("Failed to connect to MySQL: " . mysqli_connect_error());
}
 
echo "Database Connected Successfully. <br />";
 
?>
<?php
/**
 * Delete data from a Table
 */
 
require_once('db-connection.php');
 
// Mysql query to delete record from table
$mysql_query_statement = "DELETE FROM users WHERE id=3";
 
if ($conn->query($mysql_query_statement) === TRUE) {
	echo "Record deleted successfully.";
}
else {
	echo "Error deleting record: " . $conn->error;
}
 
// Connection Close
mysqli_close($conn);
?>

Congratulations! Chapter Finished. Learn more about the similar topics:
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.