Multiple Choice Questions On Class 18: Working with Databases - Part 4
MCQs on Error Handling in PHP Database Operations
- What is the purpose of error handling in database operations?
- A) To enhance performance
- B) To manage unexpected issues and maintain stability
- C) To create more databases
- D) To optimize queries
Answer: B - Which PHP extension is commonly used for database interactions?
- A) OpenSSL
- B) PDO
- C) cURL
- D) mbstring
Answer: B - Which function is used to set the error reporting level for PDO?
- A) set_error_mode()
- B) setAttribute()
- C) error_reporting()
- D) reportError()
Answer: B - What does PDO stand for?
- A) PHP Data Object
- B) PHP Data Operations
- C) PHP Data Objectivity
- D) PHP Database Object
Answer: A - Which of the following is the default error reporting mode in PDO?
- A) PDO::ERRMODE_SILENT
- B) PDO::ERRMODE_WARNING
- C) PDO::ERRMODE_EXCEPTION
- D) PDO::ERRMODE_LOG
Answer: A - What does PDO::ERRMODE_EXCEPTION do?
- A) Suppresses error reporting
- B) Issues a warning on error
- C) Throws exceptions on error
- D) Logs errors to a file
Answer: C - Which method can you use to catch exceptions in PHP?
- A) try-catch
- B) if-else
- C) switch-case
- D) do-while
Answer: A - What should you do in the catch block of a try-catch statement?
- A) Ignore the error
- B) Handle the error appropriately
- C) Terminate the script
- D) Log the error to the database
Answer: B - Which function is used to log error messages to a file in PHP?
- A) log_error()
- B) error_log()
- C) write_log()
- D) log_message()
Answer: B - What does the beginTransaction() method do in PDO?
- A) Starts a new database connection
- B) Begins a new transaction
- C) Commits the current transaction
- D) Rolls back the current transaction
Answer: B - When should you call rollBack()?
- A) After a successful transaction
- B) When you want to undo changes
- C) At the beginning of a transaction
- D) When the database connection fails
Answer: B - What is a common reason for database connection failures?
- A) Wrong query syntax
- B) Incorrect database credentials
- C) Missing database tables
- D) Invalid PDO attributes
Answer: B - Which of the following will NOT trigger an exception in PDO?
- A) Invalid SQL syntax
- B) Trying to fetch from a nonexistent table
- C) Setting an invalid PDO attribute
- D) Setting a valid PDO attribute
Answer: D - Which of the following is a valid way to create a PDO instance?
- A) $pdo = new PDO("database_type:host=host_name;dbname=db_name", "user", "pass");
- B) $pdo = create PDO("host=host_name;dbname=db_name", "user", "pass");
- C) $pdo = connect("database_type", "host_name", "db_name", "user", "pass");
- D) $pdo = new PDO("connect:host=host_name;dbname=db_name", "user", "pass");
Answer: A - What happens if you try to commit a transaction after a query fails?
- A) The transaction will succeed
- B) The transaction will be ignored
- C) An exception will be thrown
- D) The transaction will roll back automatically
Answer: C - Which PHP function would you use to check for database connection errors?
- A) check_error()
- B) connection_error()
- C) getLastError()
- D) None of the above
Answer: D - Which of the following is a good practice for error handling?
- A) Displaying detailed error messages to users
- B) Logging errors for debugging
- C) Ignoring errors in production
- D) Using generic variable names
Answer: B - What is the purpose of a try block in PHP?
- A) To execute code without errors
- B) To catch exceptions
- C) To define a code segment that may throw exceptions
- D) To handle variable declarations
Answer: C - How do you retrieve the error message of an exception?
- A) $e->message
- B) $e->getMessage()
- C) $e->errorMessage()
- D) $e->message() Answer: B
- Which of the following would you use to handle errors in a web application?
- A) Try-catch
- B) If-else
- C) Switch-case
- D) Do-while
Answer: A - What does the setAttribute() method do in PDO?
- A) Changes the database
- B) Sets attributes for the PDO object
- C) Closes the database connection
- D) Executes a query
Answer: B - Which error handling level will display a warning but allow the script to continue?
- A) PDO::ERRMODE_EXCEPTION
- B) PDO::ERRMODE_SILENT
- C) PDO::ERRMODE_WARNING
- D) PDO::ERRMODE_LOG
Answer: C - What should you do if an exception is caught?
- A) Ignore it
- B) Log the error and display a user-friendly message
- C) Always display the error message to the user
- D) Rethrow the exception without handling
Answer: B - What is the result of calling commit() without an active transaction?
- A) No effect
- B) An error is thrown
- C) The transaction will be committed
- D) The database connection will close
Answer: A - Which function can be used to check the last error code?
- A) getLastError()
- B) error_code()
- C) error_get_last()
- D) lastErrorCode()
Answer: C - Which method would you use to execute a prepared statement with parameters?
- A) exec()
- B) run()
- C) execute()
- D) query()
Answer: C - What does fetch(PDO::FETCH_ASSOC) do?
- A) Fetches the next row as an associative array
- B) Fetches all rows as an associative array
- C) Fetches the next row as a numeric array
- D) Fetches all rows as numeric arrays
Answer: A - Which SQL statement is used to delete a row from a table?
- A) DELETE FROM table_name WHERE condition;
- B) REMOVE FROM table_name WHERE condition;
- C) DROP FROM table_name;
- D) DELETE table_name WHERE condition;
Answer: A - What is a common way to handle database connection errors in PHP?
- A) Suppress error messages
- B) Use try-catch blocks
- C) Always connect to the database first
- D) Display raw error messages to users
Answer: B - Which of the following is NOT a method of the PDO class?
- A) query()
- B) exec()
- C) close()
- D) prepare()
Answer: C - What happens if you don't handle exceptions in your code?
- A) The application will terminate unexpectedly
- B) It will work without any issues
- C) The application will continue with warnings
- D) Errors will be automatically logged
Answer: A - What is the purpose of using transactions in database operations?
- A) To allow multiple connections
- B) To group multiple queries into a single unit of work
- C) To increase the speed of queries
- D) To optimize database connections
Answer: B - Which of the following will trigger a PDOException?
- A) Incorrect database credentials
- B) Using a nonexistent table in a query
- C) Both A and B
- D) None of the above
Answer: C - What should you do if a query fails during a transaction?
- A) Commit the transaction
- B) Ignore the error
- C) Roll back the transaction
- D) Log the error and continue
Answer: C - What is the result of using an invalid SQL query in PDO?
- A) A warning is shown
- B) An exception is thrown
- C) The query runs successfully
- D) The connection is closed
Answer: B - Which of the following is the best practice for displaying error messages to users?
- A) Display raw error messages
- B) Provide user-friendly messages
- C) No error messages should be shown
- D) Show error codes only
Answer: B - What should you do if an error occurs while writing to the database?
- A) Ignore the error
- B) Display an error message
- C) Log the error and notify the user
- D) Both B and C
Answer: D - How do you handle multiple database errors efficiently?
- A) Use separate try-catch blocks for each operation
- B) Use a single try-catch block with different catch types
- C) Use a generic error handler
- D) Ignore errors
Answer: A - Which function is commonly used to close a PDO connection?
- A) close()
- B) disconnect()
- C) NULLify the PDO object
- D) __destruct()
Answer: C - What does bindValue() do in a prepared statement?
- A) Executes the statement
- B) Binds a value to a parameter
- C) Closes the statement
- D) Fetches the value from the database
Answer: B - When is it appropriate to use the try statement?
- A) When making a database connection
- B) When executing SQL queries
- C) Both A and B
- D) Only for closing connections
Answer: C - What does the getMessage() method return?
- A) The error code
- B) The error message as a string
- C) The severity of the error
- D) The stack trace
Answer: B - What is the best way to manage database credentials in a PHP application?
- A) Hard-code them in the script
- B) Store them in a configuration file outside the web root
- C) Use environment variables
- D) Both B and C
Answer: D - Which of the following is a recommended way to log errors?
- A) Use echo statements
- B) Write to a log file
- C) Send emails to the admin
- D) All of the above
Answer: D - What will happen if you call rollback() without a transaction in progress?
- A) An error will be thrown
- B) Nothing will happen
- C) The database will reset
- D) The connection will be lost
Answer: B - What does the fetchAll() method return?
- A) An associative array of all rows
- B) A single row
- C) A numeric array of all rows
- D) Both A and C
Answer: D - What is the significance of using prepared statements?
- A) They improve performance
- B) They protect against SQL injection
- C) They make queries simpler
- D) Both A and B
Answer: D - What is the output if an uncaught exception occurs in PHP?
- A) The application will continue running
- B) A fatal error is generated
- C) A warning is issued
- D) A custom error page is displayed
Answer: B - How do you set PDO to throw exceptions on errors?
- A) $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
- B) $pdo->setAttribute(PDO::ERRMODE_EXCEPTION);
- C) $pdo->setErrorMode(PDO::ERRMODE_EXCEPTION);
- D) $pdo->setMode(PDO::ERRMODE_EXCEPTION);
Answer: A - What is an SQL injection attack?
- A) A method to enhance SQL performance
- B) An unauthorized access attempt to the database
- C) An error caused by invalid SQL syntax
- D) A method of storing SQL queries
Answer: B - Which error level will stop script execution?
- A) Warning
- B) Notice
- C) Fatal Error
- D) Debug
Answer: C - In which scenario would you NOT want to use transactions?
- A) When performing multiple related updates
- B) When executing a single query
- C) When rolling back changes
- D) When handling financial transactions
Answer: B - Which of the following is a common error when connecting to a database?
- A) Database server is down
- B) Invalid SQL query
- C) Table not found
- D) All of the above
Answer: A - Which PHP function would you use to start a session for logging errors?
- A) start_session()
- B) session_start()
- C) begin_session()
- D) initiate_session()
Answer: B - What should you log for debugging purposes?
- A) User inputs
- B) SQL queries executed
- C) Error messages
- D) All of the above
Answer: D - What happens if you call execute() on a prepared statement without binding parameters?
- A) An error is thrown
- B) It executes successfully
- C) It returns null
- D) It will not execute
Answer: A - What is a primary reason for using exception handling?
- A) To create more readable code
- B) To catch all types of errors
- C) To separate error handling from regular code
- D) To speed up execution
Answer: C - What should you do if a user submits invalid data to your database?
- A) Accept the data anyway
- B) Validate the data before processing
- C) Ignore the data
- D) Log it without validation
Answer: B - How can you prevent SQL injection in your application?
- A) Use prepared statements
- B) Escape user inputs
- C) Use ORM (Object-Relational Mapping)
- D) All of the above
Answer: D - What is the default character set used by PDO?
- A) utf8
- B) ascii
- C) utf8mb4
- D) iso-8859-1
Answer: A - Which statement will successfully create a new table in SQL?
- A) CREATE TABLE table_name;
- B) ADD TABLE table_name;
- C) MAKE TABLE table_name;
- D) CREATE TABLE table_name (column_name data_type);
Answer: D - What is the result of calling exec() on a non-select SQL statement?
- A) Returns the number of affected rows
- B) Returns the fetched data
- C) Returns true or false
- D) Throws an exception
Answer: A - When logging an error, what is the best practice?
- A) Log detailed stack traces
- B) Log only the error code
- C) Log user inputs
- D) Do not log anything
Answer: A - What does the query() method do in PDO?
- A) Prepares a statement
- B) Executes a query directly
- C) Fetches data from the database
- D) Creates a new database
Answer: B - How do you specify a different error mode in PDO?
- A) $pdo->setErrorMode(PDO::ERRMODE_NEW);
- B) $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_SILENT);
- C) $pdo->setMode(PDO::ERRMODE_VERBOSE);
- D) $pdo->setAttribute(PDO::ERRMODE_SILENT);
Answer: B - Which error level allows the script to continue execution after a warning?
- A) Fatal
- B) Warning
- C) Notice
- D) All of the above
Answer: B - What is the function of the prepare() method in PDO?
- A) Executes a SQL statement
- B) Prepares a SQL statement for execution
- C) Fetches data from a database
- D) Closes the database connection
Answer: B - Which of the following is true about PDO?
- A) It only works with MySQL databases
- B) It provides a uniform method for accessing various databases
- C) It is slower than MySQLi
- D) It does not support transactions
Answer: B - What is the purpose of the fetch() method in PDO?
- A) To execute a prepared statement
- B) To retrieve a single row from the result set
- C) To prepare a SQL statement
- D) To close the database connection
Answer: B - What is the best way to manage exceptions in a web application?
- A) Ignore exceptions
- B) Use a global exception handler
- C) Log every exception in detail
- D) Both B and C
Answer: D - What is the purpose of the setAttribute() method in PDO?
- A) To execute a SQL query
- B) To set attributes for the PDO object
- C) To fetch data from the database
- D) To close the connection
Answer: B - How can you debug SQL queries effectively?
- A) Use echo statements
- B) Log queries and their parameters
- C) Show raw SQL errors to users
- D) All of the above
Answer: B - What will happen if you try to execute a prepared statement without parameters?
- A) It will execute successfully
- B) An error will occur
- C) It will return null
- D) It will skip execution
Answer: B - What should be done to ensure that sensitive data is secure during transmission?
- A) Use plain HTTP
- B) Use HTTPS
- C) Only log sensitive data
- D) Do not use transactions
Answer: B - What is a potential risk of not handling exceptions?
- A) The script will run faster
- B) Errors will be visible to users
- C) All queries will succeed
- D) No impact at all
Answer: B - What is the role of a transaction in database operations?
- A) To speed up queries
- B) To ensure data integrity
- C) To save server resources
- D) To optimize performance
Answer: B - Which method would you use to fetch the next row from a result set?
- A) fetchNext()
- B) fetchRow()
- C) fetch()
- D) nextRow()
Answer: C - How can you check if a PDO connection is successful?
- A) Use isConnected() method
- B) Check if the PDO object is not null
- C) Execute a simple query
- D) All of the above
Answer: D - What is the most secure way to handle user inputs in SQL queries?
- A) Sanitize inputs manually
- B) Use prepared statements with bound parameters
- C) Escape inputs using PHP functions
- D) Validate inputs against a whitelist
Answer: B - Which of the following is NOT a common database error?
- A) Connection timeout
- B) Syntax error in SQL
- C) Network latency
- D) Data redundancy
Answer: D - What is the result of a failed database connection in PDO?
- A) A warning is issued
- B) An exception is thrown
- C) The application continues running
- D) No action is taken
Answer: B - Which of the following is a method to prevent unauthorized database access?
- A) Use complex passwords
- B) Limit database privileges
- C) Encrypt sensitive data
- D) All of the above
Answer: D - What is the main purpose of using the exec() method in PDO?
- A) To run a select query
- B) To execute SQL statements that do not return data
- C) To fetch results from the database
- D) To prepare a SQL statement
Answer: B - How can you retrieve an error code after a database operation?
- A) Use getErrorCode()
- B) Use errorCode()
- C) Use errorInfo()
- D) Both B and C
Answer: D - Which of the following is true about the commit() method?
- A) It saves all changes made during the current transaction
- B) It cancels the current transaction
- C) It must be called before executing a query
- D) It has no effect on the database
Answer: A - What is the primary advantage of using transactions in a database?
- A) They improve performance
- B) They ensure atomicity and data integrity
- C) They simplify queries
- D) They allow for easier debugging
Answer: B - What is the behavior of PDO when the database server is down?
- A) It throws an exception
- B) It logs the error
- C) It continues execution
- D) It shuts down the script
Answer: A - What type of error does catch block handle?
- A) Syntax errors
- B) Logic errors
- C) Exceptions
- D) All of the above
Answer: C - What happens when you call setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_SILENT)?
- A) All errors will be displayed
- B) No errors will be reported
- C) Errors will be logged
- D) Only warnings will be shown
Answer: B - Which of the following is a valid SQL command to update a record?
- A) MODIFY table_name SET column_name = value WHERE condition;
- B) UPDATE table_name SET column_name = value WHERE condition;
- C) CHANGE table_name SET column_name = value WHERE condition;
- D) CHANGE TABLE table_name SET column_name = value WHERE condition;
Answer: B - Which exception is thrown when trying to divide by zero?
- A) PDOException
- B) LogicException
- C) DivisionByZeroError
- D) Error
Answer: C - What does the PDO::FETCH_ASSOC fetch style return?
- A) Numeric array
- B) Associative array
- C) Both numeric and associative arrays
- D) None of the above
Answer: B - How can you log detailed errors without exposing sensitive information?
- A) Display all errors to users
- B) Log to a file and show a generic message to users
- C) Ignore errors
- D) Show all errors in a pop-up
Answer: B - Which function can be used to display a custom error page?
- A) set_error_handler()
- B) trigger_error()
- C) custom_error_page()
- D) show_error()
Answer: A - What should be the first step when a database error occurs?
- A) Ignore it
- B) Log the error
- C) Display an error message
- D) Stop script execution
Answer: B - What method is used to start a transaction in PDO?
- A) beginTransaction()
- B) startTransaction()
- C) initiateTransaction()
- D) openTransaction()
Answer: A - What is the best practice for database error handling?
- A) Display errors to users
- B) Log errors and notify the development team
- C) Ignore errors
- D) Use simple messages
Answer: B - How can you ensure that all queries within a transaction are successful?
- A) Use the commit() method
- B) Use the rollback() method
- C) Check each query result
- D) Both A and C
Answer: D - Which of the following methods is used to retrieve a single row from a result set?
- A) getRow()
- B) fetchRow()
- C) fetch()
- D) retrieveRow()
Answer: C - What is a common cause of database connection errors? - A) Incorrect database name - B) Network issues - C) Invalid credentials - D) All of the above
Answer: D
These multiple-choice questions cover various aspects of PHP, PDO, database management, and error handling. They can be useful for assessing knowledge in a PHP course, particularly in understanding how to work with databases effectively and securely.