For database access, PHP Data Objects (PDO) provides a uniform layer across multiple database engines. You connect by instantiating PDO with a Data Source Name that encodes the driver, host, and database name, along with credentials. Once connected, you should always use prepared statements to execute queries. A prepared statement separates SQL logic from data by binding parameters through placeholders, and the database driver handles escaping automatically, eliminating the most common class of SQL injection vulnerabilities.
PDO offers several fetch modes for reading rows from a result set. PDO::FETCH_ASSOC returns each row as an associative array keyed by column name, PDO::FETCH_OBJ returns each row as a stdClass object, and PDO::FETCH_CLASS maps each row onto an instance of a specified class. PDO::FETCH_NUM provides numeric-indexed arrays. You can set a default fetch mode globally so that every fetch call respects it without repetition.
Beyond databases, PHP provides several mechanisms for managing state and handling errors. Sessions let you persist data across requests by storing it server-side, identified by a cookie that holds only a session ID; you start a session with session_start() and read or write the $_SESSION superglobal. Cookies are pure client-side storage created with setcookie() before any output, useful for preferences but less secure for sensitive data. To shut a session down cleanly, you call session_unset() to clear variables and session_destroy() to discard the server-side store, optionally deleting the session cookie as well. Errors and exceptions are managed with try-catch-finally blocks, where finally always runs even when an exception propagates. PHP distinguishes between Exception, which represents recoverable conditions, and Error, which usually signals bugs such as TypeError or ParseError; both implement the Throwable interface. You can create custom exceptions by extending the Exception class, and you can convert traditional PHP warnings into exceptions by registering a callback with set_error_handler() that throws an ErrorException.