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
No Content Found.
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.