Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete 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'
Attempts:
3 left
💡 Hint
Common Mistakes
Passing the DSN as a string literal instead of the variable.
Using an undefined variable name.
✗ Incorrect
The PDO constructor requires the DSN string variable, which is stored in $dsn.
2fill in blank
mediumComplete 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'
Attempts:
3 left
💡 Hint
Common Mistakes
Using PDO::ERRMODE_SILENT which hides errors.
Using a non-existent constant like PDO::ERRMODE_FATAL.
✗ Incorrect
Setting PDO::ATTR_ERRMODE to PDO::ERRMODE_EXCEPTION makes PDO throw exceptions on errors.
3fill in blank
hardFix 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'
Attempts:
3 left
💡 Hint
Common Mistakes
Leaving the placeholder unchanged.
Using a wrong database name.
✗ Incorrect
The DSN must specify the actual database name, which is 'mydb' here.
4fill in blank
hardFill 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'
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'charset=utf8' instead of 'utf8mb4'.
Setting persistent connection to false or omitting it.
✗ Incorrect
The DSN must include 'charset=utf8mb4' for UTF-8 support, and persistent connection is enabled by setting PDO::ATTR_PERSISTENT to true.
5fill in blank
hardFill 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'
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.
✗ Incorrect
You prepare the statement with prepare(), bind the parameter with bindValue(), and run the query with execute().