How to Configure PDO to Throw Exceptions by Default
In PDO, errors are handled by default using the PDO::ERRMODE_SILENT mode, which suppresses error messages. This can be inconvenient, as it makes it difficult to detect and handle errors.
To configure PDO to throw exceptions by default, you can use the PDO::setAttribute() method to set the PDO::ATTR_ERRMODE attribute to PDO::ERRMODE_EXCEPTION. This will cause PDO to throw an exception whenever an error occurs.
For example, you could modify your code as follows:
<code class="php">$dbh = new PDO("mysql:host=$kdbhost;dbname=$kdbname",$kdbuser,$kdbpw); $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);</code>
However, it is not possible to set this attribute in a configuration file like php.ini. Therefore, you will need to set the attribute explicitly in your code every time you create a new PDO instance.
Alternatively, you could create a wrapper class that automatically sets the PDO::ATTR_ERRMODE attribute to PDO::ERRMODE_EXCEPTION whenever a new PDO instance is created. This would allow you to use PDO without having to set the attribute explicitly every time.
The above is the detailed content of How to Configure PDO to Throw Exceptions by Default?. For more information, please follow other related articles on the PHP Chinese website!