reference/pdo/error-handling.xml
1508d46d0998c4843a22d28460bb6c4244290129
...
...
@@ -84,22 +84,29 @@ $dsn = 'mysql:dbname=testdb;host=127.0.0.1';
84
84
$user = 'dbuser';
85
85
$password = 'dbpass';
86
86

87
-
try {
88
-
$dbh = new PDO($dsn, $user, $password);
89
-
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
90
-
} catch (PDOException $e) {
91
-
echo 'Connection failed: ' . $e->getMessage();
92
-
}
87
+
$dbh = new PDO($dsn, $user, $password);
88
+
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
93
89

94
-
?>
90
+
// This will cause PDO to throw a PDOException (when the table doesn't exist)
91
+
$dbh->query("SELECT wrongcolumn FROM wrongtable");
95
92
]]>
96
93
</programlisting>
94
+
&example.outputs;
95
+
<screen>
96
+
<![CDATA[
97
+
Fatal error: Uncaught PDOException: SQLSTATE[42S02]: Base table or view not found: 1146 Table 'testdb.wrongtable' doesn't exist in /tmp/pdo_test.php:10
98
+
Stack trace:
99
+
#0 /tmp/pdo_test.php(10): PDO->query('SELECT wrongcol...')
100
+
#1 {main}
101
+
thrown in /tmp/pdo_test.php on line 10
102
+
]]>
103
+
</screen>
97
104
</example>
98
105
</para>
99
106
<note>
100
107
<para>
101
108
<methodname>PDO::__construct</methodname> will always throw a <classname>PDOException</classname> if the connection fails
102
-
regardless of which <constant>PDO::ATTR_ERRMODE</constant> is currently set. Uncaught Exceptions are fatal.
109
+
regardless of which <constant>PDO::ATTR_ERRMODE</constant> is currently set.
103
110
</para>
104
111
</note>
105
112
<para>
...
...
@@ -112,27 +119,17 @@ $dsn = 'mysql:dbname=test;host=127.0.0.1';
112
119
$user = 'googleguy';
113
120
$password = 'googleguy';
114
121

115
-
/*
116
-
Using try/catch around the constructor is still valid even though we set the ERRMODE to WARNING since
117
-
PDO::__construct will always throw a PDOException if the connection fails.
118
-
*/
119
-
try {
120
-
$dbh = new PDO($dsn, $user, $password, array(PDO::ATTR_ERRMODE => PDO::ERRMODE_WARNING));
121
-
} catch (PDOException $e) {
122
-
echo 'Connection failed: ' . $e->getMessage();
123
-
exit;
124
-
}
122
+
$dbh = new PDO($dsn, $user, $password, array(PDO::ATTR_ERRMODE => PDO::ERRMODE_WARNING));
125
123

126
124
// This will cause PDO to throw an error of level E_WARNING instead of an exception (when the table doesn't exist)
127
125
$dbh->query("SELECT wrongcolumn FROM wrongtable");
128
-
?>
129
126
]]>
130
127
</programlisting>
131
128
&example.outputs;
132
129
<screen>
133
130
<![CDATA[
134
131
Warning: PDO::query(): SQLSTATE[42S02]: Base table or view not found: 1146 Table 'test.wrongtable' doesn't exist in
135
-
/tmp/pdo_test.php on line 18
132
+
/tmp/pdo_test.php on line 9
136
133
]]>
137
134
</screen>
138
135
</example>
139
136