setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); return $db; } catch (PDOException $ex) { handle_error("Can not connect to the database. Please try again later.", $ex); } } /** * Prints out a plain text 400 error message given $msg. If given a second (optional) argument as * an PDOException, prints details about the cause of the exception. * @param $msg {string} - Plain text 400 message to output * @param $ex {PDOException} - (optional) Exception object with additional exception details */ function handle_error($msg, $ex=NULL) { # in practice, 503 is a better database (internal) error code, but we only ask you to # use 400 for the scope of this course header("HTTP/1.1 400 Invalid Request"); header("Content-type: text/plain"); if ($ex) { # Note that in practice, you probably don't want to print details about your # database errors in a response to a client. But for testing your code, this can # help pinpoint bugs in your PDO functions/database connections. echo ("Error details: $ex \n"); } die ("{$msg}\n"); } ?>