Latest web development tutorials

MySQL DELETE statement

You can delete the MySQL data records in the table using the SQL DELETE FROM command.

You can mysql> command prompt or PHP scripts execute the command.

grammar

The following is the SQL DELETE statement to delete data from the MySQL data sheet general syntax:

DELETE FROM table_name [WHERE Clause]
  • If you do not specify a WHERE clause, MySQL table all records will be deleted.
  • You can specify any condition in the WHERE clause
  • You can erase recorded in a single table.

When you want to delete the data record specified in the table when the WHERE clause is very useful.


Delete data from the command line

Here, we will delete MySQL data tables w3big_tbl selected data using the WHERE clause in the SQL DELETE command.

Examples

The following example will delete w3big_tbl table w3big_id record 3:

root@host# mysql -u root -p password;
Enter password:*******
mysql> use w3big;
Database changed
mysql> DELETE FROM w3big_tbl WHERE w3big_id=3;
Query OK, 1 row affected (0.23 sec)

mysql>

Use PHP script to delete data

PHP using the mysql_query () function to execute SQL statements, you can use or not use the WHERE clause in the SQL DELETE command.

This function mysql> command symbol execute SQL commands the effect is the same.

Examples

The following examples will delete PHP w3big_tbl table w3big_id record 3:

<?php
$dbhost = 'localhost:3036';
$dbuser = 'root';
$dbpass = 'rootpassword';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn )
{
  die('Could not connect: ' . mysql_error());
}
$sql = 'DELETE FROM w3big_tbl
        WHERE w3big_id=3';

mysql_select_db('w3big');
$retval = mysql_query( $sql, $conn );
if(! $retval )
{
  die('Could not delete data: ' . mysql_error());
}
echo "Deleted data successfully\n";
mysql_close($conn);
?>