In what scenarios would it be advisable to switch from MySQLi to PDO for database operations in PHP?

Switching from MySQLi to PDO for database operations in PHP is advisable in scenarios where you want to have a more flexible and secure way of interacting with databases. PDO allows for the use of multiple database drivers, making it easier to switch between different databases without changing much code. Additionally, PDO provides better error handling and prepared statements, which help prevent SQL injection attacks.

// Example code snippet using PDO instead of MySQLi for database operations

// Connect to the database using PDO
$dsn = 'mysql:host=localhost;dbname=mydatabase';
$username = 'username';
$password = 'password';

try {
    $pdo = new PDO($dsn, $username, $password);
} catch (PDOException $e) {
    echo 'Connection failed: ' . $e->getMessage();
}

// Perform a query using prepared statements
$stmt = $pdo->prepare('SELECT * FROM users WHERE id = :id');
$stmt->bindParam(':id', $id, PDO::PARAM_INT);
$id = 1;
$stmt->execute();

// Fetch results
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Loop through results
foreach ($results as $row) {
    echo $row['username'] . '<br>';
}