Search code examples
phpmysqlipdo

What is the difference between PDO and MySQLi prepared statements?


What is the difference between these two prepared statements?

1

$stmt = $pdo->prepare('SELECT * FROM employees WHERE name = :name');

$stmt->execute(array('name' => $name));

foreach ($stmt as $row) {
    // do something with $row
}

2

$stmt = $dbConnection->prepare('SELECT * FROM employees WHERE name = ?');
$stmt->bind_param('s', $name);

$stmt->execute();

$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
    // do something with $row
}

i checked many courses about prepared statements but the only one i understood was the 2nd way, since it could be written in procedural, Isn't it the same as PDO? since both of them are Prepared statements? Is there any speed difference or ease of use between them? I learnt the 2nd way because i thought PreparedStatment = PDO but i was shocked when i knew that it is not PDO, using

mysqli_prepare
mysqli_stmt_bind_param
mysqli_stmt_execute
mysqli_stmt_bind_result

Solution

  • The difference is below:-

    1. Mysqli is only for the MySQL database. PDO supports other database using the same functions.

    2. Mysqli can be used in either an object-oriented style or a procedural style. PDO is always object-oriented.

    3. Mysqli supports prepared statements with ? placeholders for parameters. PDO supports both ? placeholders and also named placeholders, like :columnName.

    4. For older PHP versions Mysqli only allowed explicit binding. Nowadays both PDO and Mysqli allow to simply pass an array of parameter values as you execute the prepared statement. Besides, since 8.2 Mysqli has a handy function to run prepare and execute in one go.