Jump to content

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


PHPFAN10

Recommended Posts

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

 

<?php

try {
	// connect to database
	$dbh = sql_con();

	// checke if username exists on users table or users banlist table
	$stmt = $dbh->prepare("
	SELECT
	  users.user_login
	FROM
	  users
	WHERE
	  users.user_login = ?
	UNION ALL
	SELECT
	  users_banlist.user_banlist
	FROM
	  users_banlist
	WHERE
	  users_banlist.user_banlist = ?");

	// 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


	// execute query
	if(!$stmt->execute(array($username, $username))){
		echo 'something went wrong .. ';
	} else {
		// execute worked
		}
} // if any errors found log them  in my ExceptionErrorHandler() function and display friendly message
catch (PDOException $e) {
	// this function catches an error and logs them to file
	ExceptionErrorHandler($e);
	require_once($footer_inc);
	exit;
}
}

?>

 

Thanks or any help!

Link to comment
Share on other sites

The default error handling is: PDO::ERRMODE_SILENT -

 

This is the default mode. PDO will simply set the error code for you to inspect using the PDO::errorCode() and PDO::errorInfo() methods on both the statement and database objects; if the error resulted from a call on a statement object, you would invoke the PDOStatement::errorCode() or PDOStatement::errorInfo() method on that object. If the error resulted from a call on the database object, you would invoke those methods on the database object instead.

 

You need to call the ->setAttribute() method to set the PDO::ATTR_ERRMODE to PDO::ERRMODE_EXCEPTION

 

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

Link to comment
Share on other sites

Hi,

 

Thanks for replying. I already have  it set to:

$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 ? )

 

2)  What could cause the execute to fail ?

 

3)  and why if execute failed it would not be caught by catch block ?

 

I am confusing myself somewhere and am not quite getting it, hence my questions.

 

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.

 

Hopefully i have explained better.

 

Thanks for any more replied and thanks for replying!

 

Link to comment
Share on other sites

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 ? )

 

You don't need the if statement if you've configured PDO to use Exceptions for errors.  You only need it when using other error modes.

 

2)  What could cause the execute to fail ?

 

Syntax error, network failure, database corruption, possibly any number of things.

 

3)  and why if execute failed it would not be caught by catch block ?

 

It would be caught, provided your using exception mode.

 

 

Your probably getting yourself confused because your reading different tutorials/sites that use different error reporting behavior when it comes to PDO.  One place probably sets it to exception mode and just wraps try/catch around things.  Another might set it to PDO::ERRMODE_SILENT or PDO::ERRMODE_SILENT and testing each action manually with an if statement (i do this).

 

Link to comment
Share on other sites

Hi,

 

Thanks for the reply much appreciated.

 

When you say:

 

You don't need the if statement if you've configured PDO to use Exceptions for errors.  You only need it when using other error modes.

 

What do you mean exactly ? perhaps giving an example, if that is ok of course.

 

Basically in the sample code i gave, in the catch block i call a function ExceptionErrorHandler() this basically logs an error to file. Apart from that i have not changed any configuration options so PDO to use exceptions, not sure what you mean exactly by that ?

 

and when you say

 

It would be caught, provided your using exception mode.

 

When you say using exception mode, do you mean ... using try and catch block ? again sorry if i sound dumb. In my sql_con() function i have it set to:

 

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

 

So you know what my ExceptionErrorHandler does, i have provided it below: ( i use the below function in a catch block so i can catch an error and log it to a .txt file and display a friendly message to user and not any valuable details thats could compromise my database for example)

 

<?php
####################################
# Exception Handler Error Function #
####################################
function ExceptionErrorHandler ($e) {
    // get pdo error log location to store pdo errors in
    global $pdo_exception_error;

    // display user friendly error message
    echo '<h2>Holy Mother of God </h2>';
    echo '<p>Don\'t get angry and don\'t cry. We was unable to fulfill your request at this time. Please try again. ';
    echo 'If the problem persists please try again later.</p>';

    // log all the below errors, do not show to users
    $e->getMessage();
    // get error code, 0, as we didn't pass a code along as second parameter
    $e->getCode();
    // location of file
    $e->getFile();
    // get line error occured on
    $e->getLine();
    // get current date time (server set date/time) and add to error
    $date = date('d/m/Y H:i:s');

    // log error to file
    // file name and location, can be altered in config.php
    $FileName = $pdo_exception_error;
    // open file for writing; a = append to file (keeps any existing date in file and appends to it)
    $FileHandle = fopen($FileName, 'a');
    // write error to file
    fwrite($FileHandle, "[$date] - ".$e."\n\n");
    // close file after finishing with it
    fclose($FileHandle);
}
?>

 

Thanks for your time and help, much apprecaited!

phpfan

Link to comment
Share on other sites

When you say:

 

You don't need the if statement if you've configured PDO to use Exceptions for errors.  You only need it when using other error modes.

 

What do you mean exactly ? perhaps giving an example, if that is ok of course.

 

As mentioned, this code is how you put PDO into exception mode:

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

 

When you do that, then whenever there is an error PDO will throw a PDOException which will then be caught by your try/catch block.

 

Link to comment
Share on other sites

When you say:

 

You don't need the if statement if you've configured PDO to use Exceptions for errors.  You only need it when using other error modes.

 

What do you mean exactly ? perhaps giving an example, if that is ok of course.

 

As mentioned, this code is how you put PDO into exception mode:

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

 

When you do that, then whenever there is an error PDO will throw a PDOException which will then be caught by your try/catch block.

 

Great! Thanks so much for explaining :) ....

 

So basically because i have PDO in exception mode, i don't need to do if statement on execute() because if it failed it will be caught by the catch block  ? and then my function will obviously log it.

 

To my understanding now, use try and catch blocks when i want to catch an error, not nessecary syntax errors because obviously they should be fixed in development with php errors to display all errors and log them, but i guess if i'm thinking rite now that use try and catch blocks when theres a possibility that something may not happen or go as planned and by using a try and catch block we can catch the error and log it. I hope i am thinking rite now after your much appreciated effort in explaining to me. I'm hopeless at explaining and can confuse people so sorry if i have done.

 

Thanks,

phpfan

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.