0
0
PHPprogramming~10 mins

Error handling with PDO exceptions in PHP - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to catch PDO exceptions.

PHP
<?php
try {
    $pdo = new PDO($dsn, $user, $pass);
} catch ([1] $e) {
    echo 'Connection failed: ' . $e->getMessage();
}
?>
Drag options to blanks, or click blank then click option'
AException
BPDOException
CErrorException
DRuntimeException
Attempts:
3 left
💡 Hint
Common Mistakes
Using a generic Exception instead of PDOException.
Misspelling the exception class name.
2fill in blank
medium

Complete the code to set PDO to throw exceptions on error.

PHP
<?php
$pdo = new PDO($dsn, $user, $pass);
$pdo->setAttribute(PDO::ATTR_ERRMODE, [1]);
?>
Drag options to blanks, or click blank then click option'
APDO::ERRMODE_EXCEPTION
BPDO::ERRMODE_WARNING
CPDO::ERRMODE_FATAL
DPDO::ERRMODE_SILENT
Attempts:
3 left
💡 Hint
Common Mistakes
Using ERRMODE_SILENT which does not throw exceptions.
Using an invalid constant.
3fill in blank
hard

Fix the error in the catch block to correctly get the error message.

PHP
<?php
try {
    $pdo = new PDO($dsn, $user, $pass);
} catch (PDOException $e) {
    echo 'Error: ' . $e->[1]();
}
?>
Drag options to blanks, or click blank then click option'
AerrorMessage
Bmessage
CgetError
DgetMessage
Attempts:
3 left
💡 Hint
Common Mistakes
Trying to access a property instead of calling a method.
Using a non-existent method name.
4fill in blank
hard

Fill both blanks to create a try-catch block that connects and sets error mode.

PHP
<?php
try {
    $pdo = new PDO([1], $user, $pass);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, [2]);
} catch (PDOException $e) {
    echo 'Connection failed: ' . $e->getMessage();
}
?>
Drag options to blanks, or click blank then click option'
A$dsn
BPDO::ERRMODE_SILENT
CPDO::ERRMODE_EXCEPTION
D$dsnString
Attempts:
3 left
💡 Hint
Common Mistakes
Using a wrong variable name for DSN.
Setting error mode to silent instead of exception.
5fill in blank
hard

Fill all three blanks to create a safe PDO connection with error handling.

PHP
<?php
try {
    $pdo = new PDO([1], [2], [3]);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
    echo 'Failed: ' . $e->getMessage();
}
?>
Drag options to blanks, or click blank then click option'
A$dsn
B$user
C$pass
D$database
Attempts:
3 left
💡 Hint
Common Mistakes
Mixing up the order of parameters.
Using undefined variables.