PHP Database Connectivity


PHP Database Connectivity Interview with follow-up questions

1. What is PHP Database Connectivity?

PHP database connectivity refers to the ability of PHP scripts to connect to relational databases, execute queries, retrieve data, and manage transactions. PHP provides two primary APIs for this:

1. PDO (PHP Data Objects) — recommended for new projects

  • Database-agnostic abstraction layer supporting MySQL, PostgreSQL, SQLite, SQL Server, and others
  • Object-oriented interface
  • Named (:name) and positional (?) placeholders for prepared statements
  • Throws PDOException on errors (when error mode is set appropriately)
$pdo = new PDO(
    'mysql:host=localhost;dbname=app;charset=utf8mb4',
    $username,
    $password,
    [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]
);

2. MySQLi (MySQL Improved) — MySQL-specific, supports some MySQL-only features

  • Procedural and object-oriented interfaces
  • Useful for applications that need MySQL-specific features (e.g., multiple result sets)
$mysqli = new mysqli('localhost', $user, $pass, 'app');

Common operations:

  • SELECT: Prepared statement → execute()fetchAll(PDO::FETCH_ASSOC)
  • INSERT/UPDATE/DELETE: Prepared statement → bind parameters → execute()
  • Transactions: beginTransaction() → operations → commit() or rollBack()

ORM / Query builders: In production PHP applications, direct PDO is often wrapped by an ORM (Eloquent in Laravel, Doctrine ORM) or query builder (Laravel's DB::table(...), Doctrine DBAL), which handle connection pooling, relationship loading, and query construction.

The legacy mysql_* functions (e.g., mysql_connect()) were removed in PHP 7.0 and must not be used.

↑ Back to top

Follow-up 1

What are the different ways to connect to a database in PHP?

There are several ways to connect to a database in PHP:

  1. MySQLi extension: This extension provides an object-oriented interface for interacting with MySQL databases.

  2. PDO (PHP Data Objects): PDO is a database abstraction layer that provides a consistent API for accessing different databases, such as MySQL, PostgreSQL, SQLite, etc.

  3. Deprecated MySQL extension: This extension is deprecated as of PHP 5.5.0 and should not be used in new projects.

  4. Other database-specific extensions: PHP also provides extensions for specific databases, such as PostgreSQL, SQLite, Oracle, etc.

Follow-up 2

What is PDO in PHP?

PDO (PHP Data Objects) is a PHP extension that provides a consistent API for accessing different databases. It allows developers to write database-agnostic code by providing a common set of methods for interacting with databases, regardless of the underlying database system. PDO supports multiple database drivers, including MySQL, PostgreSQL, SQLite, Oracle, etc.

Follow-up 3

What is the difference between MySQLi and PDO?

The main differences between MySQLi and PDO are:

  1. API Style: MySQLi provides both procedural and object-oriented APIs, while PDO only provides an object-oriented API.

  2. Database Support: MySQLi is designed specifically for MySQL databases, while PDO supports multiple database drivers.

  3. Prepared Statements: PDO supports prepared statements, which can improve performance and security by allowing the database to cache and reuse query execution plans. MySQLi also supports prepared statements, but with some limitations.

  4. Error Handling: PDO provides a consistent error handling mechanism using exceptions, while MySQLi uses both exceptions and procedural error handling.

  5. Code Portability: PDO allows developers to write database-agnostic code, making it easier to switch between different databases. MySQLi is more tightly coupled with MySQL and may require more changes when switching databases.

Follow-up 4

Can you explain how to use PDO to connect to a MySQL database?

To use PDO to connect to a MySQL database, you can follow these steps:

  1. Create a new PDO object by specifying the database driver, host, database name, username, and password:
$dsn = 'mysql:host=localhost;dbname=mydatabase;charset=utf8';
$username = 'myusername';
$password = 'mypassword';

$pdo = new PDO($dsn, $username, $password);
  1. Optionally, you can set additional PDO attributes, such as error mode and fetch mode:
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
  1. You can now use the PDO object to execute SQL queries and interact with the database. For example, to fetch all rows from a table:
$query = 'SELECT * FROM users';
$statement = $pdo->query($query);
$users = $statement->fetchAll();
  1. Remember to properly handle exceptions and close the database connection when you're done:
$pdo = null; // Close the connection

2. How do you handle database errors in PHP?

Database errors should be handled structurally so they are logged, don't expose internal details, and allow the application to respond gracefully.

PDO — exception-based error handling (recommended):

$pdo = new PDO($dsn, $user, $pass, [
    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, // throw PDOException on error
]);

try {
    $stmt = $pdo->prepare('SELECT * FROM users WHERE id = ?');
    $stmt->execute([$userId]);
    $user = $stmt->fetch(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    // Log the real error internally
    error_log('DB error: ' . $e->getMessage());
    // Show a generic message to the user — never expose query details
    throw new RuntimeException('Database operation failed', 500, $e);
}

MySQLi — check return values:

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

$stmt = $mysqli->prepare('SELECT * FROM orders WHERE id = ?');
if (!$stmt) {
    throw new RuntimeException('Prepare failed: ' . $mysqli->error);
}

Production best practices:

  • Always use PDO::ERRMODE_EXCEPTION — never ERRMODE_SILENT (silently ignores errors)
  • Log exceptions with full context (query, parameters — but redact sensitive values) to your logging system
  • Never display raw PDOException messages to users — they can reveal table structure, column names, and query logic
  • Wrap PDO calls in repository or service classes so error handling is centralized
  • Use transactions for multi-step operations and roll back on any failure
↑ Back to top

Follow-up 1

What is the role of try/catch blocks in handling database errors?

The try/catch blocks in PHP are used to catch and handle exceptions that occur during the execution of code. In the context of handling database errors, the try block contains the code that may cause a database error, such as executing a query. If an error occurs, it will throw an exception which can be caught by the catch block. Inside the catch block, you can handle the error by logging it, displaying an error message, or taking any other necessary action.

Follow-up 2

How do you log database errors in PHP?

To log database errors in PHP, you can use the error_log() function. Inside the catch block, you can call the error_log() function and pass the error message as a parameter. This will log the error message to the PHP error log file, which can be useful for debugging and troubleshooting. Additionally, you can also log the error to a custom log file or a database table, depending on your application's requirements.

Follow-up 3

What is the difference between die() and exit() functions in PHP when handling database errors?

Both die() and exit() functions in PHP can be used to terminate the execution of a script. However, there is a subtle difference between them when it comes to handling database errors. The die() function is a language construct that prints a message and terminates the script immediately. It is commonly used for displaying error messages and stopping the script execution. On the other hand, the exit() function is a regular function that terminates the script without printing any message. It can be used to exit the script gracefully without displaying any error message. When handling database errors, it is generally recommended to use the die() function to display an error message and stop the script execution, as it provides more information to the user or developer about the error that occurred.

3. What is a prepared statement in PHP?

A prepared statement is a two-phase query execution model that separates the SQL structure from the data values:

  1. Prepare: The SQL template with placeholders is sent to the database, which parses and compiles the query.
  2. Execute: The actual data values are bound to the placeholders and the pre-compiled query is run.
// PDO prepared statement
$stmt = $pdo->prepare('SELECT * FROM users WHERE email = ? AND status = ?');
$stmt->execute([$email, 'active']);
$user = $stmt->fetch(PDO::FETCH_ASSOC);

// Named placeholders (more readable)
$stmt = $pdo->prepare('INSERT INTO products (name, price) VALUES (:name, :price)');
$stmt->execute([':name' => $productName, ':price' => $price]);

Why prepared statements matter:

Security — SQL injection prevention: User-supplied values are transmitted to the database separately from the query structure. The database engine treats the bound values as pure data — no matter what they contain, they cannot alter the query's structure. This completely prevents SQL injection.

// UNSAFE — never do this
$query = "SELECT * FROM users WHERE name = '$userInput'"; // injectable

// SAFE — prepared statement
$stmt = $pdo->prepare('SELECT * FROM users WHERE name = ?');
$stmt->execute([$userInput]);

Performance — repeated execution: The same prepared statement can be executed many times with different values. The parsing/compilation step happens only once:

$stmt = $pdo->prepare('INSERT INTO log (event, ts) VALUES (?, ?)');
foreach ($events as $event) {
    $stmt->execute([$event, time()]); // compiled once, executed many times
}
↑ Back to top

Follow-up 1

Why are prepared statements important?

Prepared statements are important for several reasons:

  1. Security: Prepared statements help prevent SQL injection attacks by separating the SQL code from the data being used in the query. This makes it harder for attackers to manipulate the query and inject malicious code.

  2. Performance: Prepared statements can improve performance by allowing the database server to prepare the query once and then execute it multiple times with different parameter values. This reduces the overhead of parsing and optimizing the query each time it is executed.

  3. Reusability: Prepared statements can be reused with different parameter values, which can save development time and improve code maintainability.

Follow-up 2

How do you use prepared statements in PHP?

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

  1. Prepare the statement: Use the prepare() method of the PDO or mysqli class to create a prepared statement. This method takes the SQL query as a parameter and returns a statement object.

  2. Bind parameters: Use the bind_param() method of the statement object to bind the parameters to the placeholders in the query. This method takes the parameter types and values as parameters.

  3. Execute the statement: Use the execute() method of the statement object to execute the prepared statement.

  4. Fetch the results: If the query returns any results, use the appropriate method (fetch(), fetchAll(), etc.) of the statement object to retrieve the results.

  5. Close the statement: Use the close() method of the statement object to close the prepared statement.

Follow-up 3

What is the difference between a prepared statement and a regular SQL query in PHP?

The main difference between a prepared statement and a regular SQL query in PHP is that a prepared statement uses placeholders for parameters, while a regular SQL query directly includes the values in the query string.

With a prepared statement, the SQL code and the data are kept separate, which helps prevent SQL injection attacks. The data is bound to the placeholders when the statement is executed.

In a regular SQL query, the values are directly included in the query string, which can make the code more vulnerable to SQL injection attacks if the values are not properly sanitized.

Prepared statements also offer performance benefits by allowing the database server to prepare the query once and then execute it multiple times with different parameter values, reducing the overhead of parsing and optimizing the query each time it is executed.

4. How do you retrieve data from a database in PHP?

To retrieve data from a database in PHP, use a prepared statement with PDO (preferred) or MySQLi.

PDO — fetching a single row:

$stmt = $pdo->prepare('SELECT id, name, email FROM users WHERE id = ?');
$stmt->execute([$userId]);
$user = $stmt->fetch(PDO::FETCH_ASSOC); // returns one row as an associative array, or false

PDO — fetching all rows:

$stmt = $pdo->prepare('SELECT * FROM products WHERE category = ?');
$stmt->execute([$category]);
$products = $stmt->fetchAll(PDO::FETCH_ASSOC); // returns array of rows

Fetch modes:

PDO::FETCH_ASSOC   // associative array (column names as keys) — most common
PDO::FETCH_OBJ     // stdClass object
PDO::FETCH_CLASS   // populates a specific class: $stmt->fetchAll(PDO::FETCH_CLASS, User::class)
PDO::FETCH_COLUMN  // single column: $stmt->fetchAll(PDO::FETCH_COLUMN, 0) → ['Alice','Bob',...]

Memory-efficient fetching — iterate row by row:

$stmt = $pdo->query('SELECT * FROM large_table');
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
    process($row); // one row in memory at a time
}

MySQLi equivalent:

$stmt = $mysqli->prepare('SELECT name, email FROM users WHERE active = ?');
$stmt->bind_param('i', $active);
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
    echo $row['name'];
}

Interview note: In Laravel, Eloquent ORM wraps these patterns: User::find($id), User::where('active', true)->get(). In Symfony, Doctrine provides $em->find(User::class, $id). Understanding the underlying PDO patterns is important for debugging and for contexts without an ORM.

↑ Back to top

Follow-up 1

What is the difference between fetch() and fetchAll() in PHP?

In PHP, the fetch() method is used to retrieve a single row from a result set, while the fetchAll() method is used to retrieve all rows from a result set. Here is an example:

// Using fetch()
$row = $statement->fetch(PDO::FETCH_ASSOC);

// Using fetchAll()
$rows = $statement->fetchAll(PDO::FETCH_ASSOC);

Follow-up 2

How do you use a while loop to fetch data from a database in PHP?

To use a while loop to fetch data from a database in PHP, you can use the fetch() method in a loop. Here is an example:

// Prepare and execute a SELECT statement
$statement = $pdo->prepare('SELECT * FROM users');
$statement->execute();

// Fetch the first row
while ($row = $statement->fetch(PDO::FETCH_ASSOC)) {
    // Access the columns by their names
    $id = $row['id'];
    $name = $row['name'];
    // Do something with the data
}

Follow-up 3

Can you explain how to use a foreach loop to fetch data from a database in PHP?

To use a foreach loop to fetch data from a database in PHP, you first need to fetch all rows using the fetchAll() method. Then, you can iterate over the rows using the foreach loop. Here is an example:

// Prepare and execute a SELECT statement
$statement = $pdo->prepare('SELECT * FROM users');
$statement->execute();

// Fetch all rows
$rows = $statement->fetchAll(PDO::FETCH_ASSOC);

// Loop through the rows
foreach ($rows as $row) {
    // Access the columns by their names
    $id = $row['id'];
    $name = $row['name'];
    // Do something with the data
}

5. How do you close a database connection in PHP?

To close a database connection in PHP, the approach depends on which extension you are using:

PDO — set to null:

$pdo = new PDO($dsn, $user, $pass);
// ... operations ...
$pdo = null; // connection is closed when no references remain

PDO does not have an explicit close() method. Setting the variable to null removes the last reference, and PHP's garbage collector closes the underlying connection.

MySQLi — call close():

$mysqli = new mysqli('localhost', $user, $pass, 'db');
// ... operations ...
$mysqli->close();

// Procedural style
$conn = mysqli_connect('localhost', $user, $pass, 'db');
mysqli_close($conn);

Persistent connections — closing behavior: Persistent connections (created with pconnect or PDO's PDO::ATTR_PERSISTENT => true) are not truly closed by calling close() or setting to null. They are returned to the connection pool and reused by the next request.

Interview note: In practice, PHP automatically closes database connections at the end of each script execution. Explicitly closing a connection is useful when a long-running script (CLI, queue worker) opens multiple connections in sequence and you want to release resources proactively. For web requests, it is optional — the connection closes when the script finishes regardless.

↑ Back to top

Follow-up 1

Why is it important to close a database connection?

It is important to close a database connection in PHP to free up resources and prevent memory leaks. When a database connection is opened, it consumes server resources such as memory and network connections. If you don't close the connection after you are done using it, these resources will not be released and can lead to performance issues, especially if you have a large number of connections open at the same time.

Closing the database connection also ensures that any pending transactions are committed or rolled back, and any locks held by the connection are released. This helps to maintain data integrity and prevent conflicts with other database operations.

Follow-up 2

What happens if you don't close a database connection in PHP?

If you don't close a database connection in PHP, it can lead to various issues:

  1. Resource exhaustion: Each open database connection consumes server resources such as memory and network connections. If you don't close the connection, these resources will not be released and can lead to resource exhaustion, especially if you have a large number of connections open at the same time.

  2. Performance degradation: Keeping unnecessary connections open can degrade the performance of your application. Opening and closing connections as needed helps to optimize resource usage and improve overall performance.

  3. Locks and transactions: If you don't close the connection, any locks held by the connection will not be released, which can cause conflicts with other database operations. Additionally, any pending transactions will not be committed or rolled back, which can result in data integrity issues.

It is therefore important to always close the database connection after you are done using it.

Follow-up 3

Can you explain the difference between close() and null in PHP when closing a database connection?

In PHP, there is a difference between using the close() method and setting the database object to null when closing a database connection.

When you call the close() method provided by the database extension, it explicitly closes the connection and releases any associated resources. This ensures that any pending transactions are committed or rolled back, and any locks held by the connection are released.

On the other hand, setting the database object to null only removes the reference to the object, but it does not explicitly close the connection or release any resources. The connection will be closed automatically by PHP's garbage collector when the object is no longer referenced and eligible for garbage collection.

It is generally recommended to use the close() method to explicitly close the connection, as it provides more control and ensures that resources are released in a timely manner. Setting the object to null should be used as a fallback option if you are unable to call the close() method for some reason.

Live mock interview

Mock interview: PHP Database Connectivity

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.