How can one improve the security and efficiency of database operations in PHP by using PDO or mysqli?

When working with databases in PHP, it is essential to prioritize security and efficiency. One way to achieve this is by using either PDO (PHP Data Objects) or mysqli (MySQL Improved) extensions, which provide prepared statements to prevent SQL injection attacks and enhance performance by reusing query execution plans.

// Using PDO for secure and efficient database operations
try {
    $pdo = new PDO("mysql:host=localhost;dbname=mydatabase", "username", "password");
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    $stmt = $pdo->prepare("SELECT * FROM users WHERE id = :id");
    $stmt->bindParam(':id', $userId, PDO::PARAM_INT);
    $stmt->execute();

    $result = $stmt->fetchAll(PDO::FETCH_ASSOC);
    // Process the results
} catch (PDOException $e) {
    echo "Error: " . $e->getMessage();
}