Use exception mode-pdo::errmode_exception (the error method in the capture SQL statement in PDO three)

Source: Internet
Author: User
Use exception mode-pdo::errmode_exception (the error method in the capture SQL statement in PDO three)

The exception mode creates a pdoexception and sets the Erorcode property, which encapsulates the execution code into a try{...} Catch{...} Statement, an uncaught exception will cause the script to break and display a stack trace to let the user know where the problem is!

In the first two articles, "using the default mode-pdo::errmode_silent (Error method in capturing SQL statements in PDO)", "Using warning mode-pdo::errmode_warning (capturing the error method in the SQL statement in PDO II)" We introduce the default mode and exception mode two methods, then we introduce the third method today to catch the error of SQL statement in PDO ~

Exception mode Another very useful is that, compared to traditional PHP style warnings, you can build your own error handling more clearly, and the exception pattern requires less code/nesting than silent mode and explicitly checking the return value of each database call.

In addition to setting the error code, PDO throws a Pdoexception exception class and sets its properties to reflect the error code and error message. This setting is also useful during debugging because it effectively magnifies the points in the script that produce errors, so you can quickly point out potential areas of the code that are problematic! (Remember: If the exception causes the script to terminate, the transaction is automatically rolled back).

When performing a delete operation of the data in the database, set to the exception mode, and write an incorrect SQL statement to understand the difference between the exception mode and the warning mode and the default mode.

The steps are as follows:

(1) Create a PHP file, connect to the database, perform a select query operation through the prepare () and execute () methods of the scheduled processing statement, complete the loop output of the data through the while statement and the fetch () method, and set the delete hyperlink. Connecting to another PHP file, the passed parameter is the ID value of the data, the code is as follows:

<?phpheader ("content-type:text/html;    Charset=utf-8 ");                                  Set the encoding format of the page $dbms = "MySQL";                                The type of database $dbname = "PHP_CN";                                   The database name used is $user = "root";                                    Database user name used $pwd = "root";                              The database password used $host = "localhost"; Host name used $DSN = "$dbms: host= $host;d bname= $dbName"; try{$pdo =new PDO ($DSN, $user, $pwd);//Initialize a PDO object to create a database connection object $pdo  $pdo->setattribute (pdo::attr_errmode,pdo::errmode_exception);            Set to Warning mode $query= "SELECT * from User",//SQL statement to execute $res= $pdo->prepare ($query);//Prepare Query statement $res->execute (); Executes a query statement and returns a result set? ><table border= "1" width= "> <tr> <td height=" "align=" center "valign=" mi Ddle ">id</td> <td height=" "align=" center "valign=" Middle "> User name </td> <td height=" 22 "align=" center "valign=" Middle "> Password </td> <td height=" "align=" center "valign= "middle" > Operations </td> </tr> <?php while ($result = $res->fetch (PDO::FETCH_ASSOC)) {//Loop output check and sets the result set to the associated data form.?> <tr> <td height= "" "align=" center "valign=" Middle "><?p HP echo $result ["id"];? ></td> <td height= "align=" center "valign=" Middle "><?php echo $result [" username "];? ></td> <td height= "align=" center "valign=" Middle "><?php echo $result [" password "];? ></td> <td height= "align=" center "valign=" middle "><a href=" 2.php?code_id=<?php Echo $r esult[' id '];? > > Delete </td> </tr> <?php}}catch (Exception $e) {die ("error!:". $e->getmes Sage (). '    <br> '); }?></table>

The output results are as follows:

(2) Create another file, get the data ID value of the hyperlink, connect the database, set the SetAttribute () method to the exception mode, define the DELETE delete statement, delete the data from the wrong data table, and pass the try{...} Catch{...} Statement to get the error message with the following code:

<?php$id = $_get[' code_id '];if ($id) {header ("content-type:text/html;    Charset=utf-8 ");                                  Set the encoding format of the page $dbms = "MySQL";                                The type of database $dbname = "PHP_CN";                                   The database name used is $user = "root";                                    Database user name used $pwd = "root";                              The database password used $host = "localhost";    Host name used $DSN = "$dbms: host= $host;d bname= $dbName"; try{$pdo =new PDO ($DSN, $user, $pwd);//Initialize a PDO object to create a database connection object $pdo  $pdo->setattribute (pdo::attr_errmode,pdo::errmode_exception); Set to warning mode $query = "Delete * from User_12 where id = $id";//SQL statement to be executed $res = $pdo->prepare ($query);//Prepare query statement $res     ->bindparam (': Id ', $_get[' code_id ']);            Bind Update Data $res->execute ();    Executes the query statement and returns the result set}catch (Pdoexception $e) {echo "PDO Exception caught";    Echo ' Error with the database:<br> '; Echo ' SQL Query; '.    $query;    Echo ' <pre> '; echo "Error:". $e-GetMessage (). "<br> "; echo "Code:". $e->getcode (). "    <br> "; echo "File:". $e->getfile (). "    <br> "; echo "line:". $e->getline (). "    <br> "; echo "Trace:". $e->gettraceasstring (). "    <br> "; echo "</pre>";}}

Attention:

In the above code, when defining the delete DELETE statement, we deliberately used the wrong data table name User_12 (the correct data table name is: User), this is to test write!

After setting the exception mode, execute the error SQL statement, and the output is as follows:

About three ways to capture errors in a SQL statement in PDO here we go, I believe that the small partners have a certain understanding of the error of capturing SQL statements in PDO, and next we will continue to introduce the method of error handling in PDO, please read the Method of error handling in PDO a-errorcode () Method!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.