MySQL DELETE statement

You can use the SQL DELETE FROM command to delete records in a MySQL data table.
The command can be executed from the mysql> command prompt or a PHP script.

The following is the general syntax of the SQL DELETE statement to delete data from a MySQL data table:

DELETE FROM table_name [WHERE Clause]
  • If no WHERE clause is specified, all records in the MySQL table will be deleted.
  • Any condition can be specified in the WHERE clause.
  • Records can be deleted all at once in a single table.
  • The WHERE clause is useful when deleting specified records in a data table.

Delete data from the command line

The following example deletes the record with runoob_id 3 in the runoob_tbl table:

MariaDB [(none)]> use RUNOOB
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A

Database changed
MariaDB [RUNOOB]> delete from runoob_tbl where runoob_id=3;
Query OK, 1 row affected (0.03 sec)

MariaDB [RUNOOB]>

Delete data using PHP script

PHP uses the mysql_query() function to execute SQL statements. You can use the WHERE clause with or without the SQL DELETE command.

This function has the same effect as the mysql> command to execute SQL commands.

The following PHP example will delete the record with runoob_id 3 in the runoob_tbl table:

  1. <?php
  2. $dbhost = 'localhost:3036';
  3. $dbuser = 'root';
  4. $dbpass = 'rootpassword';
  5. $conn = mysql_connect($dbhost, $dbuser, $dbpass);
  6. if(! $conn )
  7. {
  8. die('Could not connect: ' . mysql_error());
  9. }
  10. $sql = 'DELETE FROM runoob_tbl
  11. WHERE runoob_id=3';
  12. mysql_select_db('RUNOOB');
  13. $retval = mysql_query( $sql, $conn );
  14. if(! $retval )
  15. {
  16. die('Could not delete data: ' . mysql_error());
  17. }
  18. echo "Deleted data successfully\n";
  19. mysql_close($conn);
  20. ?>
operation result

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326464128&siteId=291194637