PHP - SPLessons

PHP Delete Data From MySQL

Home > Lesson > Chapter 38
SPLessons 5 Steps, 3 Clicks
5 Steps - 3 Clicks

PHP Delete Data From MySQL

PHP Delete Data From MySQL

shape Description

PHP Delete Data From MySQL shows how to delete data from database. To remove data/records from a single or multiple database tables, MySQL DELETE statement is used.

shape Syntax

DELETE FROM table [WHERE conditions] [ORDER BY ...] [LIMIT rows]
  • DELETE FROM clause selects the table in which the records to be deleted.
  • WHERE clause denotes the rows that has to be deleted.If WHERE condition is satisfied, record is deleted from the table permanently otherwise, all the table records will be deleted.
  • ROW_COUNT() function is returned by DELETE statement which indicates the number of rows deleted.

shape Examples

MySQLi (Object-oriented) [php] <html> <body> <?php $HostName = "localhost"; $UserName = "root"; $Password = "password"; $dbname="accounts"; // Create connection $connection = new mysqli($HostName, $UserName, $Password, $dbname); // Check connection if ($connection->connect_error) { die("Connection failed: " . $connection->connect_error); } // sql to delete a record $sql = "DELETE FROM users2 WHERE id=2"; if ($connection->query($sql) === TRUE) { echo "Record deleted successfully"; } else { echo "Error deleting record: " . $connection->error; } $connection->close(); ?> </body> </html> [/php] The output will be "Record deleted successfully" and in phpmyadmin, the output will be like below. MySQLi (Procedural) [php] <html> <body> <?php $servername = "localhost"; $username = "username"; $password = "password"; $dbname = "accounts"; // Create connection $connection = mysqli_connect($servername, $username, $password, $dbname); // Check connection if (!$connection) { die("Connection failed: " . mysqli_connect_error()); } // sql to delete a record $sql = "DELETE FROM users2 WHERE id=2"; if (mysqli_query($connection, $sql)) { echo "Record deleted successfully"; } else { echo "Error deleting record: " . mysqli_error($connection); } mysqli_close($connection); ?> </body> </html> [/php]

Summary

shape Key Points

  • MySQL deletes the records from a single table or multiple tables.
  • To delete the record, it uses the statement DELETE FROM.