How can PDO be utilized for database operations in PHP instead of mixing it with MySQLi?

When using PDO for database operations in PHP instead of mixing it with MySQLi, you can benefit from its flexibility and support for multiple database types. To do this, you need to create a PDO connection to the database and then use PDO prepared statements for executing queries securely.

// Create a PDO connection to the database
$dsn = 'mysql:host=localhost;dbname=mydatabase';
$username = 'username';
$password = 'password';

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

// Use PDO prepared statements for executing queries securely
$stmt = $pdo->prepare('SELECT * FROM users WHERE id = :id');
$stmt->bindParam(':id', $id, PDO::PARAM_INT);
$id = 1;
$stmt->execute();

while ($row = $stmt->fetch()) {
    // Process the fetched data
}