PHP PHP Database Integration & MySQL 2 — Questions and Answers
Question 1: What syntax does PDO use for named placeholders in prepared statements?
- ?name
- {name}
- #name
- :name (Correct answer)
Correct answer: :name
PDO named placeholders use a colon prefix (e.g., :username), which are then bound to actual values via bindParam() or bindValue().
Question 2: Which PDO method binds a PHP variable to a named placeholder, passing by reference?
- bindValue()
- bindColumn()
- bindParam() (Correct answer)
- bindRef()
Correct answer: bindParam()
bindParam() binds a PHP variable by reference to a named placeholder, so the value is read at execution time.
Question 3: How should PDO connection errors be caught in PHP?
- Using a global error handler
- Using try-catch with PDOException (Correct answer)
- Checking the return value of new PDO()
- Using set_error_handler()
Correct answer: Using try-catch with PDOException
PDO throws PDOException on connection and query failures when error mode is set to exceptions, which should be caught with try-catch.
Question 4: Which PDO attribute setting enables exceptions to be thrown on database errors?
- PDO::ATTR_ERRMODE => PDO::ERRMODE_WARNING
- PDO::ATTR_ERRMODE => PDO::ERRMODE_SILENT
- PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION (Correct answer)
- PDO::ATTR_TIMEOUT => PDO::ERRMODE_EXCEPTION
Correct answer: PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
Setting PDO::ATTR_ERRMODE to PDO::ERRMODE_EXCEPTION causes PDO to throw PDOException objects on errors.
Question 5: What does PDOStatement::rowCount() return after a SELECT query in most databases?
- Always the exact number of rows fetched
- The number of rows in the entire table
- An unpredictable or zero value (behavior varies by driver) (Correct answer)
- The number of columns in the result
Correct answer: An unpredictable or zero value (behavior varies by driver)
rowCount() reliably returns affected rows for INSERT/UPDATE/DELETE, but its behavior with SELECT is driver-dependent and often returns 0.
Question 6: Which PHP function is used to start a database transaction using PDO?
- PDO::startTransaction()
- PDO::begin()
- PDO::beginTransaction() (Correct answer)
- PDO::openTransaction()
Correct answer: PDO::beginTransaction()
beginTransaction() disables auto-commit mode and starts a new transaction that must be completed with commit() or rollBack().
What syntax does PDO use for named placeholders in prepared statements?