If this is your first visit, be sure to
check out the FAQ by clicking the
link above. You may have to register
before you can post: click the register link above to proceed. To start viewing messages,
select the forum that you want to visit from the selection below.

PHP PDO execute() .... somewhat confused ?

Hi,

Below i have some sample code and am confused over execute(), i have the code below in a try and catch block, in the catch block i call a function i created to log any error that is caught in catch block to a .txt file.

I then looked online and it seems that i should do an if statement check on execute to ensure it executed the query, the part that confuses me if the execute failed i thought it would be caught in the catch block but it seems that is not the case.

To explain better i have commented the code in depth on the area that i am confused about.

Any help in making me understand would be great. I have not included all code above try and catch to keep things simple

// this is the part i am confused with, why is it i would use an if statement on execute() ?
// i thought using a try and catch block any errors would be caught in the catch block.
// using an if statement to check if execute() worked, i thought if execute failed it would
// be handled by the catch block, i mean in my exmaple code here, what could cause the execute to fail ?
// and why if execute failed it would not be caught by catch block ?
// i am looing at exmaple online and i am reading different things and its all confusing me

Thanks for replying. I already have it set to the following in my sql_con() function which establishes connection to database:

PHP Code:

$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

My confusion is in my try block i try to check if a username exists on the users table and user ban list table, it then gets executed using execute(), now my confusion is why would i use an if statement around the execute() as shown in my code ?

I thought if the execute() failed it would be caught in the catch block, but seeing examples online i see people wrap the execute() in an if statement as illustrated in my code.

and back to my questions:

1) In example code, why is it i would use an if statement on execute() ? (if it failed to execute shouldn't it be caught in the catch block ? )

Basically anything caught in the catch block in example code is written to a log file, in example code in catch block i call my function ExceptionErrorHandler($e);, this function writes any error to file.

Looks like it's because the default behavior for MySQL is to emulate prepared statements, which then seems to short-circuit the error-to-exception process. You can tell it not to do this, though it may cost some in terms of performance: