0
0
PHPprogramming~5 mins

PDO connection setup in PHP - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What does PDO stand for in PHP?
PDO stands for PHP Data Objects. It is a way to connect and work with databases in PHP.
Click to reveal answer
beginner
What is the basic syntax to create a new PDO connection?
Use new PDO(dsn, username, password) where dsn is the data source name, including database type and name.
Click to reveal answer
beginner
Why should you use try-catch blocks when setting up a PDO connection?
To catch errors if the connection fails and handle them gracefully instead of crashing the program.
Click to reveal answer
intermediate
What is the purpose of setting the PDO attribute PDO::ATTR_ERRMODE to PDO::ERRMODE_EXCEPTION?
It makes PDO throw exceptions on errors, which helps in debugging and error handling.
Click to reveal answer
beginner
Show a simple example of PDO connection setup to a MySQL database named 'testdb' on localhost with user 'root' and no password.
try { $pdo = new PDO('mysql:host=localhost;dbname=testdb', 'root', ''); $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); echo 'Connected successfully'; } catch (PDOException $e) { echo 'Connection failed: ' . $e->getMessage(); }
Click to reveal answer
What is the correct way to start a PDO connection in PHP?
APDO_connect('localhost', 'testdb')
BconnectPDO('localhost', 'testdb', 'user', 'pass')
Cnew PDO('mysql:host=localhost;dbname=testdb', 'user', 'pass')
Dmysql_connect('localhost', 'user', 'pass')
Why do we use try-catch blocks with PDO connections?
ATo handle connection errors without crashing the script
BTo speed up the connection
CTo encrypt the database password
DTo automatically close the connection
What does setting PDO::ATTR_ERRMODE to PDO::ERRMODE_EXCEPTION do?
AMakes PDO throw exceptions on errors
BDisables error reporting
CLogs errors to a file
DAutomatically retries failed queries
Which of these is NOT part of the DSN string for a MySQL PDO connection?
Acharset
Bdbname
Chost
Duser
What will happen if the PDO connection fails and there is no try-catch block?
AThe connection will retry automatically
BThe script will stop with a fatal error
CThe script will ignore the error and continue
DThe database will connect anyway
Explain how to set up a PDO connection to a MySQL database in PHP.
Think about the steps to connect safely and handle errors.
You got /4 concepts.
    Why is it important to set PDO error mode to exceptions when connecting to a database?
    Consider how errors are handled in your code.
    You got /3 concepts.