What is the difference between mysqli and PDO in PHP?

Both MySQLi and PDO (PHP Data Objects) are used to connect PHP with a database. Both support prepared statements, so both can protect from SQL injection.

FeatureMySQLiPDO
Databases supportedMySQL and MariaDB only12 different databases (MySQL, PostgreSQL, SQLite and more)
StyleProcedural and object orientedObject oriented only
Named parameters (:email)No, only ?Yes, and also ?
Switching database laterNeed to rewrite the codeMostly change only the connection string
Error handlingExceptions (default from PHP 8.1)Exceptions (when you set the error mode)
<?php
$pdo = new PDO("mysql:host=localhost;dbname=student;charset=utf8mb4", "root", "");
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

$stmt = $pdo->prepare("SELECT name FROM users WHERE email = :email");
$stmt->execute(["email" => "ram@example.com"]);

echo $stmt->fetchColumn();
?>

Output:

Suppose the users table has this record

Ram

Use PDO if you may change the database in future, or you like named parameters. Use MySQLi if you work only with MySQL and want its extra features. See MySQLi prepared statements and MySQLi procedural vs object oriented.


Learn more about the similar topics:
Tutorials
PHP MySQL Tutorial
PHP : MySQL Database
PHP : MySQL Connect
PHP : MySQL Create Database
PHP : MySQL Create Table
PHP : MySQL INSERT Statement
PHP : MySQL Select Data
Exercises & Assignments
Display MySQL data in an HTML table using mysqli_fetch_array()
Interview Questions & Answers
What is the difference between mysqli_fetch_array() and mysqli_fetch_object()?
How to Fix Incorrect format parameter error when importing large database in PHPMyAdmin?
In how many ways can we fetch data from a MySQL result set in PHP?
How to encrypt and decrypt data stored in a MySQL table?
What is the difference between mysqli and PDO in PHP?