PHP MySQL: How to Delete Data from a Table (original) (raw)

Skip to content

Summary: in this tutorial, you will learn how to delete data from a MySQL database table using PHP PDO.

To delete data from a table, you follow these steps:

Deleting a row from a table

The following script deletes the task with the id 3 from the tasks table:

`<?php require_once 'config.php';

try { conn=newPDO("mysql:host=conn = new PDO("mysql:host=conn=newPDO("mysql:host=host;dbname=$dbname", username,username, username,password); $sql = 'delete from tasks where id =:id'; stmt=stmt = stmt=conn->prepare($sql); $stmt->execute([':id' => 3]); } catch (PDOException $e) { die($e); }`Code language: HTML, XML (xml)

Verify the delete

The following statement retrieves all rows from the tasks table:

select * from tasks;Code language: JavaScript (javascript)

Output:

+----+-------------------------+-----------+ | id | title | completed | +----+-------------------------+-----------+ | 1 | Learn PHP MySQL | 0 | | 2 | Build a Web Application | 0 | +----+-------------------------+-----------+ 2 rows in set (0.00 sec)Code language: JavaScript (javascript)

Deleting all rows from a table

There are two ways you can delete all rows from a table:

To execute the DELETE or TRUNCATE TABLE statement, you can call the exec() method of the PDO object.

The following script deletes all rows from the tasks table using the DELETE statement:

`<?php require_once 'config.php';

try { conn=newPDO("mysql:host=conn = new PDO("mysql:host=conn=newPDO("mysql:host=host;dbname=$dbname", username,username, username,password); $sql = 'delete from tasks'; stmt=stmt = stmt=conn->exec($sql); } catch (PDOException $e) { die($e); }`Code language: HTML, XML (xml)

The following script deletes all rows from the tasks table using the TRUNCATE statement:

`<?php require_once 'config.php';

try { conn=newPDO("mysql:host=conn = new PDO("mysql:host=conn=newPDO("mysql:host=host;dbname=$dbname", username,username, username,password); $sql = 'trunate table tasks'; stmt=stmt = stmt=conn->exec($sql); } catch (PDOException $e) { die($e); } `Code language: PHP (php)

Summary

Was this tutorial helpful?