Deleting Records In PHP and MYSQL Deleting rows of data in PHP is a similar to updating process.
mysql > DELETE FROM fruit WHERE id = 2;
Query OK, 1 row affected
To delete rows using PHP, pass a DELETE statement directly via PDO::query() , or create the statement using PDO::prepare() with placeholders, passing in values (such as the criteria for the WHERE clause) with PDOStatement::bindValue() and running the query with PDOStatement::execute() .
This script deletes the member record with the ID of 8 from the members table:
<?php
$dsn = “mysql:dbname=mydatabase”;
$username = “root”;
$password = “mypass”;
try {
$conn = new PDO( $dsn, $username, $password );
$conn- > setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
} catch ( PDOException $e ) {
echo “Connection failed: “ . $e- > getMessage();
}
$id = 8;
$sql = “DELETE FROM members WHERE id = :id”;
try {
$st = $conn- > prepare( $sql );
$st- > bindValue( “:id”, $id, PDO::PARAM_INT );
$st- > execute();
} catch ( PDOException $e ) {
echo “Query failed: “ . $e- > getMessage();
}
?>
Incidentally, rather than binding the value of a variable to a placeholder with PDOStatement:: bindValue() , use PDOStatement::bindParam() to bind the variable itself. then change the value of the variable after the call to bindParam() , the placeholder value is automatically updated to the new value.