Will the false returned PDO execute () be the same as the exception it threw?

As requested, I reformat the question:

For the following code:

$newPDO=new PDO($DSN,$USER,$PASS); $newPDO->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION); $SQL='SOME SQL STATEMENT MAYBE FAULTY'; try{ $Query=$newPDO->Prepare($SQL) $Success=$Query->execute(); if(!$Success) echo('A'); } catch(PDOException $e) { echo('B'); } 

The question is, can I print "A"? Will the answer change for a different type of $SQL how to select or paste?

The original question:

  • First, I set the attribute PDO :: ATTR_ERRMODE, PDO :: ERRMODE_EXCEPTION, so I think when execute () detects an error from the database, it should throw an exception. Then I realized that if this is true, I don’t even need to check the return of execute () until the exception is the same as the returned "false". I just need to fish outside. If nothing is caught, the question should be in order.
    But I'm not sure about this, since execute () by default does not throw an exception according to the manual. I tried to perform several operations, such as duplicating a PC and a unique violation of restrictions when I insert something. my statement is supported: PDO will throw an exception and I can get the detaield error message from DB. However, I do not know if this is a universal truth. Is it possible to get false from execute () rather than PDOEXCEPTION if I set ERRMODE to the maximum? *
+1
php exception pdo execute
source share
2 answers

Try the following:

  try { //Initial query processing $execute = $query->execute() if (!$execute) { //catch the exception throw new Exception ("blah") } } catch (Exception $e) { //Exception logic here } 

Write your queries like this, and if they encounter an exception in the try section, it will go into the catch section and you will be able to handle it as you like (regardless of whether the ID depends on a specific case).

If there are no exceptions, it will never reach the catch statement, and your request will simply be executed.

When it comes to DUPLICATES -> you need to get around this in SQL. For example, your request could be:

 INSERT INTO table (a,b,c) VALUES (1,2,3),(4,5,6) ON DUPLICATE KEY UPDATE c=VALUES(a)+VALUES(b); 
+1
source share

I saw that execute () returns false without throwing an exception, which in my opinion is unexpected / bad. This means that we basically have to do simultaneously - handling errors and exceptions in parallel.

In my case: if I prepared an insert request without any parameters, and then executed with a parameter. Execute does not throw an exception, but returns false. I suggest anyone use the @mlishn solution.

0
source share

All Articles