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 try { $pdo = new PDO('mysql:host=localhost;dbname=testdb', 'user', 'pass'); echo 'Connected successfully'; } catch (PDOException $e) { echo 'Connection failed: ' . $e->getMessage(); } ?>
If the credentials and database exist and are correct, the try block runs without error.
The code tries to create a PDO object with given credentials. If successful, it prints 'Connected successfully'. If it fails, it prints the error message.
What error will this PHP code produce when trying to connect to a MySQL database with an invalid DSN string?
<?php try { $pdo = new PDO('mysql:host=localhost;port=wrongport;dbname=testdb', 'user', 'pass'); echo 'Connected'; } catch (PDOException $e) { echo $e->getMessage(); } ?>
Using an invalid port in the DSN causes a connection failure related to the network or socket.
The DSN has an invalid port, so PDO cannot connect to the MySQL server. This causes a connection error with SQLSTATE[HY000] and error code 2002.
Examine this PHP code snippet. Why does it cause a fatal error?
<?php $pdo = new PDO('mysql:host=localhost;dbname=testdb', 'user', 'pass'); echo $pdo->connect_error; ?>
PDO does not use 'connect_error' like mysqli does.
PDO does not have a 'connect_error' property. Trying to access it causes a fatal error. PDO uses exceptions to report errors.
Which of the following code snippets correctly sets the PDO error mode to throw exceptions?
The method is setAttribute with the error mode constant as the second argument.
Option D uses the correct method and constants. Option D swaps arguments, C uses a non-existent method, and D passes the constant as a string.
Given this PHP code connecting with PDO and fetching all rows, how many items will be in the $rows array?
<?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); ?>
fetchAll returns all rows matching the query as an array.
The fetchAll method returns all rows matching the query as an array. The count of this array equals the number of matching rows.