To delete records from a database using PDO in PHP, you can follow these steps:
$servername = "localhost";
$dbname = "your_database";
$username = "your_username";
$password = "your_password";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// Rest of the code...
} catch(PDOException $e) {
echo "Connection failed: " . $e->getMessage();
exit();
}
prepare()
method on the database connection object. In the query, specify the table name and the condition based on which you want to delete the records. For example, to delete a record with a specific ID:$id = 5;
$stmt = $conn->prepare("DELETE FROM your_table WHERE id = :id");
$stmt->bindParam(':id', $id);
execute()
method on the statement object:$stmt->execute();
$affected_rows = $stmt->rowCount();
echo "Deleted $affected_rows row(s).";
$conn = null;
By following these steps, you can delete records from a database using PDO in PHP. Remember to adapt the code to your specific database and table structure.