MySQLi and PDO


MySQLi and PDO Interview with follow-up questions

1. What is MySQLi and PDO in PHP?

MySQLi and PDO are the two PHP extensions for database access that replaced the deprecated (and removed) mysql_* functions.

MySQLi (MySQL Improved) Designed specifically for MySQL/MariaDB. Provides both procedural and object-oriented interfaces.

// Object-oriented style
$mysqli = new mysqli('localhost', 'user', 'pass', 'dbname');
if ($mysqli->connect_error) {
    throw new RuntimeException('Connection failed: ' . $mysqli->connect_error);
}

$stmt = $mysqli->prepare('SELECT id, name FROM users WHERE active = ?');
$stmt->bind_param('i', $active); // i = integer, s = string, d = double, b = blob
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
    echo $row['name'];
}
$mysqli->close();

PDO (PHP Data Objects) A database abstraction layer supporting MySQL, PostgreSQL, SQLite, SQL Server, Oracle, and more. Object-oriented only.

$pdo = new PDO('pgsql:host=localhost;dbname=shop', $user, $pass, [
    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
]);

$stmt = $pdo->prepare('SELECT id, name FROM users WHERE active = :active');
$stmt->execute([':active' => 1]);
$users = $stmt->fetchAll(PDO::FETCH_ASSOC);

Key differences:

Feature MySQLi PDO
Database support MySQL/MariaDB only Multiple databases
API style Procedural + OO OO only
Named placeholders No (? only) Yes (:name and ?)
Error mode Manual checking or exceptions Configurable

Recommendation: PDO is preferred for new projects.

↑ Back to top

Follow-up 1

What are the advantages of using MySQLi over PDO?

There are a few advantages of using MySQLi over PDO:

  1. MySQLi is specifically designed for MySQL databases, so it provides some MySQL-specific features that are not available in PDO.
  2. MySQLi supports multiple statements in a single query, which can be useful in certain scenarios.
  3. MySQLi has a procedural style of programming in addition to the object-oriented style, which can be more familiar to some developers.
  4. MySQLi has better performance compared to PDO in some cases, especially when dealing with large datasets.

However, it's worth noting that PDO is more versatile as it supports multiple databases, whereas MySQLi is limited to MySQL.

Follow-up 2

Can you explain how to establish a database connection using PDO?

To establish a database connection using PDO, you need to follow these steps:

  1. Create a new instance of the PDO class, passing the database connection details as parameters.
  2. The parameters include the database driver (e.g., 'mysql'), the host name, the database name, the username, and the password.
  3. If the connection is successful, the PDO object is created, and you can use it to interact with the database.

Here's an example of establishing a database connection using PDO:

getMessage();
}
?>

Follow-up 3

What are the main differences between MySQLi and PDO?

The main differences between MySQLi and PDO are as follows:

  1. Database Support: MySQLi is designed specifically for MySQL databases, whereas PDO supports multiple databases, including MySQL, PostgreSQL, SQLite, and more.
  2. Programming Style: MySQLi offers both procedural and object-oriented programming styles, while PDO primarily uses an object-oriented approach.
  3. Prepared Statements: Both MySQLi and PDO support prepared statements, but the syntax and usage differ slightly.
  4. Multiple Statements: MySQLi allows executing multiple statements in a single query, whereas PDO does not support this feature.
  5. Error Handling: PDO has a consistent error handling mechanism using exceptions, while MySQLi provides both procedural and object-oriented error handling options.

The choice between MySQLi and PDO depends on the specific requirements of your project and the database you are working with.

Follow-up 4

How do you handle errors in PDO and MySQLi?

In PDO, errors are handled using exceptions. When an error occurs, PDO throws a PDOException, which you can catch and handle using try-catch blocks. Here's an example:

getMessage();
}
?>

In MySQLi, errors can be handled in both procedural and object-oriented styles. In the procedural style, you can use the mysqli_error() function to get the error message. In the object-oriented style, you can use the mysqli->error property. Here's an example:

connect_error) {
    echo 'Error: ' . $mysqli->connect_error;
}
?>

It's important to handle errors properly to ensure the security and stability of your application.

2. How do you execute a query using MySQLi?

With MySQLi, queries are best executed using prepared statements to prevent SQL injection.

Object-oriented style (recommended):

$mysqli = new mysqli('localhost', 'user', 'pass', 'dbname');

// Prepared SELECT with parameter binding
$stmt = $mysqli->prepare('SELECT id, name, email FROM users WHERE status = ? AND role = ?');
$stmt->bind_param('ss', $status, $role); // s = string
$status = 'active';
$role   = 'admin';
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
    echo $row['name'];
}
$stmt->close();

// Prepared INSERT
$stmt = $mysqli->prepare('INSERT INTO users (name, email) VALUES (?, ?)');
$stmt->bind_param('ss', $name, $email);
$name  = 'Alice';
$email = '[email protected]';
$stmt->execute();
echo "Inserted ID: " . $mysqli->insert_id;
$stmt->close();
$mysqli->close();

bind_param type codes:

  • i — integer
  • d — double (float)
  • s — string
  • b — blob (binary)

Direct (non-parameterized) query — only for queries with no user input:

$result = $mysqli->query('SELECT COUNT(*) AS total FROM users');
$row = $result->fetch_assoc();
echo $row['total'];

Comparison with PDO: PDO's execute([...]) is often simpler — no need for bind_param with type codes; PDO infers types or uses explicit bindValue. This is one reason PDO is preferred for new development.

↑ Back to top

Follow-up 1

What is the role of the prepare statement in MySQLi?

The prepare statement in MySQLi is used to create a prepared statement, which allows you to execute the same SQL statement repeatedly with different parameters. It helps improve performance and security by separating the query logic from the data. The prepare statement also helps prevent SQL injection attacks by automatically escaping special characters in the parameters.

Follow-up 2

How do you bind parameters in a MySQLi statement?

To bind parameters in a MySQLi statement, you need to follow these steps:

  1. Create a prepared statement using the mysqli_prepare() function.

  2. Use the mysqli_stmt_bind_param() function to bind the parameters to the prepared statement. This function takes as arguments the prepared statement, a string representing the data types of the parameters, and the values of the parameters.

  3. Execute the prepared statement using the mysqli_stmt_execute() function.

Note: The number of parameters and their data types must match the placeholders in the SQL statement.

Follow-up 3

Can you explain how to fetch data from a MySQLi query?

To fetch data from a MySQLi query, you need to follow these steps:

  1. Execute the query using the mysqli_query() function. This function returns a result set.

  2. Use the mysqli_fetch_assoc() function to fetch the next row from the result set as an associative array. This function returns null if there are no more rows.

  3. Process the fetched data as needed.

  4. Repeat steps 2 and 3 until all rows have been fetched.

  5. Free the memory associated with the result set using the mysqli_free_result() function.

Note: There are other fetch functions available in MySQLi, such as mysqli_fetch_row() and mysqli_fetch_object(), which fetch the data in different formats.

3. What are prepared statements in PDO and why are they important?

Prepared statements in PDO are the primary defense against SQL injection and also improve performance when running the same query multiple times.

How they work:

  1. Prepare: Send the SQL template with ? or :name placeholders to the database. The DB parses and compiles the query.
  2. Bind and execute: Supply actual values; the DB substitutes them as data — they can never alter the query's SQL structure.
// Positional placeholder
$stmt = $pdo->prepare('SELECT * FROM users WHERE email = ? AND active = ?');
$stmt->execute([$email, 1]);
$user = $stmt->fetch(PDO::FETCH_ASSOC);

// Named placeholder (more readable for multiple params)
$stmt = $pdo->prepare('INSERT INTO orders (user_id, total, status) VALUES (:user_id, :total, :status)');
$stmt->execute([
    ':user_id' => $userId,
    ':total'   => $total,
    ':status'  => 'pending',
]);

Why prepared statements are important:

  • SQL injection prevention: User input is sent as data, not as SQL. Even '; DROP TABLE users; -- becomes harmless — it's just a string value, not a SQL command.
  • Performance: The database compiles the query once; executing the same statement multiple times (e.g., bulk inserts in a loop) skips re-parsing on each call.
  • Code clarity: Separating the query structure from its values makes SQL easier to read and maintain.
  • Type handling: PDO can be configured (PDO::ATTR_EMULATE_PREPARES => false) to use native database-level prepared statements, which are even more secure.
↑ Back to top

Follow-up 1

How do you use prepared statements in PDO?

To use prepared statements in PDO, you need to follow these steps:

  1. Prepare the statement: Use the prepare() method of the PDO object to create a prepared statement. Pass the SQL query with placeholders as the parameter.

  2. Bind the parameters: Use the bindParam() or bindValue() method of the prepared statement object to bind the parameters to specific values. You can bind parameters by position or by name.

  3. Execute the statement: Use the execute() method of the prepared statement object to execute the statement. If the statement has placeholders, you can pass an array of values as the parameter to the execute() method.

Here's an example of using prepared statements in PDO:

// Step 1: Prepare the statement
$stmt = $pdo->prepare('SELECT * FROM users WHERE username = :username');

// Step 2: Bind the parameters
$stmt->bindParam(':username', $username);

// Step 3: Execute the statement
$stmt->execute();

Follow-up 2

What are the benefits of using prepared statements in PDO?

There are several benefits of using prepared statements in PDO:

  1. Security: Prepared statements help prevent SQL injection attacks by separating the query logic from the data. This means that user input is treated as data and not as part of the query structure.

  2. Performance: Prepared statements can be prepared once and executed multiple times with different parameter values. This can improve performance by reducing the overhead of parsing and optimizing the query each time it is executed.

  3. Readability and maintainability: Prepared statements make the code more readable and maintainable by separating the SQL query from the data values.

  4. Database compatibility: Prepared statements are supported by most database systems, making the code more portable.

Follow-up 3

Can you explain how to bind parameters in a PDO statement?

To bind parameters in a PDO statement, you can use the bindParam() or bindValue() method of the prepared statement object. These methods allow you to bind parameters to specific values.

Here's how you can bind parameters in a PDO statement:

  • bindParam(): This method binds a parameter to a variable. You can bind parameters by position or by name. If you bind a parameter by position, the variable will be bound by reference, meaning that any changes to the variable will be reflected in the bound parameter. If you bind a parameter by name, the variable will be bound by value, meaning that the value of the variable at the time of binding will be used.

  • bindValue(): This method binds a parameter to a specific value. You can bind parameters by position or by name. The value is bound by value, meaning that the value at the time of binding will be used.

Here's an example of binding parameters in a PDO statement:

// Bind parameter by position
$stmt->bindParam(1, $username);

// Bind parameter by name
$stmt->bindParam(':username', $username);

// Bind value
$stmt->bindValue(':username', $username);

4. How do you handle transactions in PDO?

PDO transactions group multiple database operations into a single atomic unit — either all succeed (COMMIT) or all are rolled back (ROLLBACK) if an error occurs.

try {
    $pdo->beginTransaction();

    // Deduct from sender
    $stmt = $pdo->prepare('UPDATE accounts SET balance = balance - ? WHERE id = ?');
    $stmt->execute([$amount, $senderId]);

    // Credit receiver
    $stmt = $pdo->prepare('UPDATE accounts SET balance = balance + ? WHERE id = ?');
    $stmt->execute([$amount, $receiverId]);

    // Record transaction
    $stmt = $pdo->prepare('INSERT INTO transfers (from_id, to_id, amount) VALUES (?, ?, ?)');
    $stmt->execute([$senderId, $receiverId, $amount]);

    $pdo->commit();  // All three operations succeed → commit
} catch (\Throwable $e) {
    $pdo->rollBack(); // Any failure → roll back all three
    error_log('Transfer failed: ' . $e->getMessage());
    throw $e;
}

PDO transaction methods:

  • $pdo->beginTransaction() — starts the transaction; auto-commit is disabled
  • $pdo->commit() — persists all changes since beginTransaction()
  • $pdo->rollBack() — undoes all changes since beginTransaction()
  • $pdo->inTransaction() — returns true if a transaction is currently active

Savepoints (nested transactions via SQL): PDO does not natively support nested beginTransaction() calls, but you can use SQL savepoints for partial rollbacks:

$pdo->exec('SAVEPOINT sp1');
// ... operations ...
$pdo->exec('ROLLBACK TO SAVEPOINT sp1');

Doctrine and Laravel wrap transactions in helpers: $em->transactional(fn() => ...) and DB::transaction(fn() => ...).

↑ Back to top

Follow-up 1

What are the benefits of using transactions in PDO?

Using transactions in PDO provides several benefits:

  1. Atomicity: Transactions ensure that a series of database operations either all succeed or all fail. If any operation within the transaction fails, the entire transaction can be rolled back, ensuring data consistency.

  2. Consistency: Transactions allow you to maintain data consistency by ensuring that all changes made within a transaction are committed together.

  3. Isolation: Transactions provide isolation between concurrent database operations. Changes made within a transaction are not visible to other transactions until the transaction is committed.

  4. Durability: Once a transaction is committed, the changes made within the transaction are permanent and will survive system failures.

Overall, using transactions helps maintain data integrity and reliability in database operations.

Follow-up 2

Can you explain how to rollback a transaction in PDO?

To rollback a transaction in PDO, you can use the rollback() method. If an exception occurs within the transaction, you can catch the exception and call the rollback() method to undo any changes made within the transaction.

Here is an example of how to rollback a transaction in PDO:

try {
    $pdo->beginTransaction();

    // Perform database operations
    // ...

    $pdo->commit();
} catch (PDOException $e) {
    $pdo->rollback();
    throw $e;
}

Follow-up 3

What is the role of the commit function in PDO transactions?

The commit() function in PDO transactions is used to permanently save the changes made within a transaction to the database. Once the commit() function is called, all the changes made within the transaction are made permanent and visible to other transactions.

Here is an example of how to use the commit() function in PDO transactions:

try {
    $pdo->beginTransaction();

    // Perform database operations
    // ...

    $pdo->commit();
} catch (PDOException $e) {
    $pdo->rollback();
    throw $e;
}

5. What is the role of exception handling in PDO?

PDO's exception-based error handling makes it the cleaner, safer choice compared to checking return values manually. When PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION is set, PDO throws a PDOException whenever a database operation fails.

$pdo = new PDO($dsn, $user, $pass, [
    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
]);

try {
    $pdo->beginTransaction();

    $stmt = $pdo->prepare('INSERT INTO orders (user_id, total) VALUES (?, ?)');
    $stmt->execute([$userId, $total]); // throws PDOException if it fails

    $pdo->commit();
} catch (PDOException $e) {
    $pdo->rollBack();
    // Log detailed error internally
    error_log('Order insert failed: ' . $e->getMessage() . ' | Code: ' . $e->getCode());
    // Surface a safe message
    throw new OrderException('Failed to create order', previous: $e);
}

Error modes:

Mode Behavior
PDO::ERRMODE_SILENT (default) No exception; check $stmt->errorInfo() manually
PDO::ERRMODE_WARNING Emits E_WARNING; script continues
PDO::ERRMODE_EXCEPTION Throws PDOException; recommended

PDOException properties:

  • getMessage() — human-readable description
  • getCode() — SQLSTATE error code (5-char string)
  • errorInfo()[$sqlstate, $driverCode, $driverMessage]

Always use ERRMODE_EXCEPTION. ERRMODE_SILENT silently ignores database errors — a common source of hard-to-debug data corruption bugs.

↑ Back to top

Follow-up 1

Can you explain how to set the error mode to exception in PDO?

To set the error mode to exception in PDO, you can use the setAttribute() method with the PDO::ATTR_ERRMODE attribute. Here's an example:

// Create a new PDO instance
$pdo = new PDO('mysql:host=localhost;dbname=mydatabase', 'username', 'password');

// Set the error mode to exception
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

Follow-up 2

How do you handle exceptions in PDO?

To handle exceptions in PDO, you can use try-catch blocks. Inside the try block, you can write the code that may throw an exception. If an exception is thrown, it can be caught in the catch block where you can handle the exception by displaying an error message or taking any necessary actions.

Here's an example:

try {
    // PDO code that may throw an exception
} catch (PDOException $e) {
    // Handle the exception
    echo 'Error: ' . $e->getMessage();
}

Follow-up 3

What is the benefit of using exceptions in PDO?

Using exceptions in PDO provides several benefits:

  1. Error handling: Exceptions allow you to handle errors in a structured and consistent way. You can catch specific types of exceptions and handle them accordingly.

  2. Code readability: Exception handling makes the code more readable and maintainable. It separates the error handling logic from the main code, making it easier to understand and debug.

  3. Transaction management: Exceptions can be used to handle transaction management. If an exception occurs during a transaction, you can catch it and roll back the transaction to maintain data integrity.

  4. Error reporting: Exceptions provide detailed error information, including the error message, code, and stack trace. This information can be logged or displayed to the user for troubleshooting purposes.

Live mock interview

Mock interview: MySQLi and PDO

Intermediate ~5 min Your own free AI key

Your voice and your AI key never touch our servers; the key stays in this browser and is sent only to Google. Only your round scores are saved to track progress.