Bird
Raised Fist0
PHPprogramming~20 mins

PDO connection setup in PHP - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
PDO Connection Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
What is the output of this PDO connection code?

Consider the following PHP code that tries to connect to a MySQL database using PDO. What will it output if the connection is successful?

PHP
<?php
try {
  $pdo = new PDO('mysql:host=localhost;dbname=testdb', 'user', 'pass');
  echo 'Connected successfully';
} catch (PDOException $e) {
  echo 'Connection failed: ' . $e->getMessage();
}
?>
ANo output
BConnected successfully
CFatal error: Uncaught Error: Class 'PDO' not found
DConnection failed: SQLSTATE[HY000] [1045] Access denied for user 'user'@'localhost' (using password: YES)
Attempts:
2 left
💡 Hint

If the credentials and database exist and are correct, the try block runs without error.

❓ Predict Output
intermediate
2:00remaining
What error does this PDO connection code raise?

What error will this PHP code produce when trying to connect to a MySQL database with an invalid DSN string?

PHP
<?php
try {
  $pdo = new PDO('mysql:host=localhost;port=wrongport;dbname=testdb', 'user', 'pass');
  echo 'Connected';
} catch (PDOException $e) {
  echo $e->getMessage();
}
?>
ASQLSTATE[HY000] [2002] No such file or directory
BSQLSTATE[HY000] [1045] Access denied for user 'user'@'localhost' (using password: YES)
CFatal error: Uncaught PDOException: could not find driver
DConnected
Attempts:
2 left
💡 Hint

Using an invalid port in the DSN causes a connection failure related to the network or socket.

🔧 Debug
advanced
2:00remaining
Why does this PDO connection code cause a fatal error?

Examine this PHP code snippet. Why does it cause a fatal error?

PHP
<?php
$pdo = new PDO('mysql:host=localhost;dbname=testdb', 'user', 'pass');
echo $pdo->connect_error;
?>
APDO objects do not have a 'connect_error' property, causing a fatal error
BThe DSN string is invalid, causing a connection failure
CThe code is missing a try-catch block, causing a syntax error
DThe username or password is incorrect, causing an exception
Attempts:
2 left
💡 Hint

PDO does not use 'connect_error' like mysqli does.

📝 Syntax
advanced
2:00remaining
Which option correctly sets PDO to throw exceptions on error?

Which of the following code snippets correctly sets the PDO error mode to throw exceptions?

A$pdo->setErrorMode(PDO::ERRMODE_EXCEPTION);
B$pdo->setAttribute(PDO::ERRMODE_EXCEPTION, PDO::ATTR_ERRMODE);
C$pdo->setAttribute(PDO::ATTR_ERRMODE, 'PDO::ERRMODE_EXCEPTION');
D$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
Attempts:
2 left
💡 Hint

The method is setAttribute with the error mode constant as the second argument.

🚀 Application
expert
2:00remaining
How many items are in the resulting array after this PDO fetchAll call?

Given this PHP code connecting with PDO and fetching all rows, how many items will be in the $rows array?

PHP
<?php
$pdo = new PDO('mysql:host=localhost;dbname=testdb', 'user', 'pass');
$stmt = $pdo->query('SELECT * FROM users WHERE age > 30');
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
echo count($rows);
?>
A1, because fetchAll returns only the first row
B0, because fetchAll returns an empty array always
CThe number of users with age greater than 30 in the database
DAn error, because fetchAll requires a parameter
Attempts:
2 left
💡 Hint

fetchAll returns all rows matching the query as an array.

Practice

(1/5)
1. What is the main purpose of using PDO in PHP?
easy
A. To connect to databases securely and easily
B. To create HTML pages
C. To handle user sessions
D. To send emails

Solution

  1. Step 1: Understand PDO's role

    PDO is a PHP extension designed to connect to databases in a secure and consistent way.
  2. Step 2: Compare other options

    Other options like creating HTML, handling sessions, or sending emails are unrelated to PDO.
  3. Final Answer:

    To connect to databases securely and easily -> Option A
  4. Quick Check:

    PDO = Secure database connection [OK]
Hint: PDO is for database connections only [OK]
Common Mistakes:
  • Confusing PDO with HTML or session functions
  • Thinking PDO sends emails
  • Assuming PDO is for file handling
2. Which of the following is the correct way to create a new PDO connection to a MySQL database named 'testdb' on localhost with username 'user' and password 'pass'?
easy
A. $pdo = new PDO('host=localhost;dbname=testdb', 'user', 'pass');
B. $pdo = new PDO('mysql:localhost;dbname=testdb', 'user', 'pass');
C. $pdo = new PDO('mysql://localhost/testdb', 'user', 'pass');
D. $pdo = new PDO('mysql:host=localhost;dbname=testdb', 'user', 'pass');

Solution

  1. Step 1: Check DSN format for MySQL

    The correct DSN format is 'mysql:host=hostname;dbname=database_name'.
  2. Step 2: Verify options

    $pdo = new PDO('mysql:host=localhost;dbname=testdb', 'user', 'pass'); uses the correct DSN format with host and dbname separated by semicolon and includes username and password.
  3. Final Answer:

    $pdo = new PDO('mysql:host=localhost;dbname=testdb', 'user', 'pass'); -> Option D
  4. Quick Check:

    DSN format = 'mysql:host=...;dbname=...' [OK]
Hint: DSN must start with 'mysql:' and use semicolons [OK]
Common Mistakes:
  • Omitting 'mysql:' prefix
  • Using slashes instead of semicolons
  • Missing 'host=' keyword
3. What will be the output of this PHP code snippet?
$dsn = 'mysql:host=localhost;dbname=testdb';
try {
    $pdo = new PDO($dsn, 'user', 'wrongpass');
    echo 'Connected';
} catch (PDOException $e) {
    echo 'Connection failed: ' . $e->getMessage();
}
medium
A. Connected
B. Connection failed: SQLSTATE[HY000] [1045] Access denied for user 'user'@'localhost' (using password: YES)
C. Syntax error
D. No output

Solution

  1. Step 1: Analyze connection attempt

    The code tries to connect with username 'user' but a wrong password 'wrongpass'.
  2. Step 2: Understand error handling

    PDO throws a PDOException on failure, caught by catch block, which prints the error message.
  3. Final Answer:

    Connection failed: SQLSTATE[HY000] [1045] Access denied for user 'user'@'localhost' (using password: YES) -> Option B
  4. Quick Check:

    Wrong password triggers exception message [OK]
Hint: Wrong password triggers exception message [OK]
Common Mistakes:
  • Expecting 'Connected' despite wrong password
  • Ignoring try-catch block
  • Assuming no output on failure
4. Identify the error in this PDO connection code:
try {
    $pdo = new PDO('mysql:host=localhost;dbname=testdb', 'user', 'pass');
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
    echo 'Error: ' . $e->getMessage();
}
medium
A. Missing DSN string
B. Incorrect error mode constant
C. No error, code is correct
D. Missing semicolon after setAttribute

Solution

  1. Step 1: Review DSN and credentials

    The DSN string is correct and includes host and dbname properly.
  2. Step 2: Check error mode setting

    PDO::ATTR_ERRMODE and PDO::ERRMODE_EXCEPTION are valid constants to enable exceptions on errors.
  3. Step 3: Verify syntax

    All lines end with semicolons and try-catch is properly structured.
  4. Final Answer:

    No error, code is correct -> Option C
  5. Quick Check:

    Correct DSN and error mode = no error [OK]
Hint: Check constants and syntax carefully [OK]
Common Mistakes:
  • Using wrong error mode constants
  • Forgetting semicolons
  • Miswriting DSN string
5. You want to connect to a MySQL database using PDO and ensure that any connection error throws an exception. Which code snippet correctly sets up the connection and error handling?
hard
A. try { $pdo = new PDO('mysql:host=localhost;dbname=testdb', 'user', 'pass'); $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); } catch (PDOException $e) { echo 'Connection failed: ' . $e->getMessage(); }
B. try { $pdo = new PDO('mysql:host=localhost;dbname=testdb', 'user', 'pass'); $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_SILENT); } catch (Exception $e) { echo 'Error'; }
C. $pdo = new PDO('mysql:host=localhost;dbname=testdb', 'user', 'pass'); $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING);
D. try { $pdo = new PDO('mysql:host=localhost;dbname=testdb', 'user', 'pass'); } catch (PDOException $e) { echo 'Error: ' . $e->getMessage(); } $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

Solution

  1. Step 1: Check error mode setting

    Setting PDO::ATTR_ERRMODE to PDO::ERRMODE_EXCEPTION ensures exceptions on errors.
  2. Step 2: Verify try-catch placement

    The error mode must be set inside the try block before any database operations, so exceptions are caught properly.
  3. Step 3: Analyze options

    try { $pdo = new PDO('mysql:host=localhost;dbname=testdb', 'user', 'pass'); $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); } catch (PDOException $e) { echo 'Connection failed: ' . $e->getMessage(); } correctly sets error mode inside try and catches PDOException with detailed message.
  4. Final Answer:

    try { $pdo = new PDO('mysql:host=localhost;dbname=testdb', 'user', 'pass'); $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); } catch (PDOException $e) { echo 'Connection failed: ' . $e->getMessage(); } -> Option A
  5. Quick Check:

    Error mode exception + try-catch = try { $pdo = new PDO('mysql:host=localhost;dbname=testdb', 'user', 'pass'); $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); } catch (PDOException $e) { echo 'Connection failed: ' . $e->getMessage(); } [OK]
Hint: Set error mode to exception inside try block [OK]
Common Mistakes:
  • Setting error mode outside try block
  • Using wrong error mode constants
  • Catching wrong exception type
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard