0
0
PHPprogramming~10 mins

PDO connection setup 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 create a new PDO instance for a MySQL database.

PHP
<?php
$dsn = 'mysql:host=localhost;dbname=testdb';
$username = 'root';
$password = '';
try {
    $pdo = new PDO([1], $username, $password);
} catch (PDOException $e) {
    echo 'Connection failed: ' . $e->getMessage();
}
?>
Drag options to blanks, or click blank then click option'
A$dsn
Bdsn
C'dsn'
D$database
Attempts:
3 left
💡 Hint
Common Mistakes
Passing the DSN as a string literal instead of the variable.
Using an undefined variable name.
2fill in blank
medium

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

PHP
<?php
$pdo = new PDO($dsn, $username, $password);
$pdo->setAttribute(PDO::ATTR_ERRMODE, [1]);
?>
Drag options to blanks, or click blank then click option'
APDO::ERRMODE_EXCEPTION
BPDO::ERRMODE_SILENT
CPDO::ERRMODE_WARNING
DPDO::ERRMODE_FATAL
Attempts:
3 left
💡 Hint
Common Mistakes
Using PDO::ERRMODE_SILENT which hides errors.
Using a non-existent constant like PDO::ERRMODE_FATAL.
3fill in blank
hard

Fix the error in the DSN string to connect to a PostgreSQL database named 'mydb'.

PHP
<?php
$dsn = 'pgsql:host=localhost;dbname=[1]';
$pdo = new PDO($dsn, $user, $pass);
?>
Drag options to blanks, or click blank then click option'
Atestdb
Bpostgres
Cmydb
Ddatabase
Attempts:
3 left
💡 Hint
Common Mistakes
Leaving the placeholder unchanged.
Using a wrong database name.
4fill in blank
hard

Fill both blanks to create a PDO connection with UTF-8 charset and persistent connection enabled.

PHP
<?php
$dsn = 'mysql:host=localhost;dbname=testdb;[1]';
$options = [
    PDO::ATTR_PERSISTENT => [2]
];
$pdo = new PDO($dsn, $user, $pass, $options);
?>
Drag options to blanks, or click blank then click option'
Acharset=utf8mb4
Btrue
Cfalse
Dcharset=utf8
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'charset=utf8' instead of 'utf8mb4'.
Setting persistent connection to false or omitting it.
5fill in blank
hard

Fill all three blanks to prepare a PDO statement, bind a parameter, and execute it.

PHP
<?php
$stmt = $pdo->[1]('SELECT * FROM users WHERE id = :id');
$stmt->[2](':id', $userId, PDO::PARAM_INT);
$result = $stmt->[3]();
?>
Drag options to blanks, or click blank then click option'
Aprepare
BbindValue
Cexecute
Dquery
Attempts:
3 left
💡 Hint
Common Mistakes
Using query() instead of prepare().
Using bindParam() instead of bindValue() (both work but bindValue is simpler here).
Forgetting to execute the statement.