Deleting Data From MySQL Table via PHP Script

The last article focused on updating existing records in MySQL table. In this article, we shall study how to delete rows of data from MySQL table. For deleting data in MySQL, DELETE query is used. The syntax of DELETE query is as follows:

DELETE FROM table
WHERE condition(s)

Deleting records from MySQL table via Object Oriented MySQLi

To delete records from tables via MySQLi, pass the query for deleting rows to the query function of the mysqli object. Have a look at the following example.




Using DElETE clause in MySQLi



connect_error) {
    die("Connection not established: " . $connection->connect_error);
} 
    
$query = "Use Hospital;";
$connection->query($query);
    
// Implementing DELETE query

$query = "DELETE FROM Patient ".
    "WHERE patient_age < 30";
if ($connection->query($query) === TRUE) {
    echo "Record DELETED successfuly.";
} else {
    echo "Unable to DELETE record " . $connection->error;
}

$connection->close();
?>  
    



Download the code

The above DELETE query will delete all the records in the Patient table where age is less than 30. Now if you select and view the table contents, you shall see that there should be no patient with age less than 30.

Delete Table data via Procedural MySQLi

Deleting table data via procedural MySQLi is straight forward. Just replace mysqli object with mysqli_connect function. The following example demonstrates this concept.




Using DElETE clause in MySQLi



connect_error) {
    die("Connection not established: " . $connection->connect_error);
} 
    
$query = "Use Hospital;";
$connection->query($query);
    
// Implementing DELETE query

$query = "DELETE FROM Patient ".
    "WHERE patient_age = 27";
if ($connection->query($query) === TRUE) {
    echo "Record DELETED successfuly.";
} else {
    echo "Unable to DELETE record " . $connection->error;
}

$connection->close();
?>
        



Download the code

Copyright 2005-2016 KnowledgeHills. Privacy Policy. Contact .