PHP MySQL DELETE Query



In this source code example, you'll learn how to delete records from a MySQL table using PHP.

PHP MySQL DELETE Query

<?php
/* Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
$host= "localhost";
$username= "root";
$password = "";

$db_name = "demo_db";

$mysql_connection = mysqli_connect($host, $username, $password, $db_name);
 
// Check connection
if ($mysql_connection->connect_errno) {
    printf("connection failed: %s\n", $mysql_connection->connect_error());
    exit();
}
 
// Attempt delete query execution
$sql = "DELETE FROM students WHERE first_name='John'";

if(mysqli_query($mysql_connection, $sql)){
    echo "Records were deleted successfully.";
} else{
    echo "ERROR: Could not able to execute $sql. " . mysqli_error($mysql_connection);
}
 
// Close connection
mysqli_close($mysql_connection);
?>
Let's understand the above PHP script.

The mysqli_connect() function opens a new connection to the MySQL server:
$host= "localhost";
$username= "root";
$password = "";

$db_name = "demo_db";

$mysql_connection = mysqli_connect($host, $username, $password, $db_name);

DELETE SQL query:

// Attempt delete query execution
$sql = "DELETE FROM students WHERE first_name='John'";

The mysqli_query() function performs a query against a database:

if(mysqli_query($mysql_connection, $sql)){
    echo "Records were deleted successfully.";
} else{
    echo "ERROR: Could not able to execute $sql. " . mysqli_error($mysql_connection);
}

Closing MySQL server connection:

// Close connection
mysqli_close($mysql_connection);

Comments