How to delete records from a database using PDO in PHP?

To delete records from a database using PDO in PHP, you can follow these steps:

  1. Establish a connection to the database using PDO by providing the appropriate database credentials. For example:
$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(); }
  1. Prepare a DELETE query by using the 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);
  1. Execute the query using the execute() method on the statement object:
$stmt->execute();
  1. Optionally, you can check the number of affected rows to verify if any record got deleted:
$affected_rows = $stmt->rowCount(); echo "Deleted $affected_rows row(s).";
  1. Close the database connection:
$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.