What are the recommended steps for establishing a connection to a database and executing a SQL query to delete user accounts in PHP?

To delete user accounts from a database using PHP, you need to establish a connection to the database and execute a SQL query to delete the desired user accounts. This can be achieved by using PHP's PDO (PHP Data Objects) extension to connect to the database and prepare and execute the delete query.

<?php

// Establish a connection to the database
$dsn = 'mysql:host=localhost;dbname=your_database';
$username = 'your_username';
$password = 'your_password';

try {
    $pdo = new PDO($dsn, $username, $password);
} catch (PDOException $e) {
    die("Could not connect to the database: " . $e->getMessage());
}

// Prepare and execute the SQL query to delete user accounts
$user_id = 123; // Example user ID to be deleted
$sql = "DELETE FROM users WHERE id = :user_id";

$stmt = $pdo->prepare($sql);
$stmt->bindParam(':user_id', $user_id, PDO::PARAM_INT);
$stmt->execute();

echo "User account with ID $user_id has been deleted.";

?>