Updated PDO error handling chapter with new example and added note to reflect PDO::__construct behavior.

This fixes Bug #63845 in that a note is added to inform the user that PDO::__construct will always throw an exception if the connection fails.
A new example is also added to reflect that even when the PDO::ATTR_ERRMODE is set in the constructor, and the connection fails, a PDOException will still be thrown.


git-svn-id: https://svn.php.net/repository/phpdoc/en/trunk@329077 c90b9560-bf6c-de11-be94-00142212c4b1
This commit is contained in:
Sherif Ramadan 2013-01-11 11:09:57 +00:00
parent cd908490ca
commit cfcfe6e059

View file

@ -95,6 +95,47 @@ try {
</programlisting>
</example>
</para>
<note>
<para>
<function>PDO::__construct</function> will always throw a <classname>PDOException</classname> if the connection fails
regardless of which <constant>PDO::ATTR_ERRMODE</constant> is currently set. Uncaught Exceptions are fatal.
</para>
</note>
<para>
<example>
<title>Create a PDO instance and set the error mode from the constructor</title>
<programlisting role="php">
<![CDATA[
<?php
$dsn = 'mysql:dbname=test;host=127.0.0.1';
$user = 'googleguy';
$password = 'googleguy';
/*
Using try/catch around the constructor is still valid even though we set the ERRMODE to WARNING since
PDO::__construct will always throw a PDOException if the connection fails.
*/
try {
$dbh = new PDO($dsn, $user, $password, array(PDO::ATTR_ERRMODE => PDO::ERRMODE_WARNING));
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
exit;
}
// This will cause PDO to throw an error of level E_WARNING instead of an exception (when the table doesn't exist)
$dbh->query("SELECT wrongcolumn FROM wrongtable");
?>
]]>
</programlisting>
&example.outputs;
<screen>
<![CDATA[
Warning: PDO::query(): SQLSTATE[42S02]: Base table or view not found: 1146 Table 'test.wrongtable' doesn't exist in
/tmp/pdo_test.php on line 18
]]>
</screen>
</example>
</para>
</chapter>
<!-- Keep this comment at the end of the file