mysql errors and transaction handling

Do you have a question? Post it now! No Registration Necessary.  Now with pictures!

Threaded View
Hi all,
(1) The "standard method" for handling errors when executing queries to
a mysql database, which is shown in most tutorials and books is:

mysql($query) or die("select/insert/update/delete query failed for

Actually that is hardly what should be done in a good application.
Every other function has a means of returning a value, often true/false
or "0"/"1".
I feel it is best if we had something like :

$success = mysql($query);

if ( $sucess) {
    //do something
} else {
   //log error
   //show customized error page

True, we can do the following:

mysql($query) or my_own_db_error_handler();

Is there anything that I dont know or any better idea?

Also, a basic question I have is - why we do have to do "or die()"? Is
it because we need to ensure that a moment a db script gives an error,
we have a query that has failed, so as damage control, we immediately
terminate the script, knowing that some queries have been executed and
others have not.
If this is the reason to use "or die()" is it not better to use
mysql_query("start transaction") and mysql_query("commit") or
"rollback" and put the commit at the end of the script and the rollback
in the above mentioned my_own_db_error_handler() ?
Is this a good way?

(2) Also, most big web hosts (shared hosting - I cannot afford to set
up a host myself or even dedicated hosting) do not have PHP5,  which
has MySQLi which has much better MySQL functionality(bind variables
etc) . They have PHP 4.3.x. I am under the impression that for an
efficient PHP4 app you need to use the procedural style, since PHP4's
OO features are "slow and inefficient". Am i correct ?

Thanks in advance for your responses,

Re: mysql errors and transaction handling

Joseph S. wrote:
Quoted text here. Click to load it

I agree.  Using ... or die() is just a lazy way of damage control.  I  
don't use it.

A failed request should never terminate the program.  Rather, it should  
return some kind of failure result and allow the caller to determine  
what action should be taken.  And good programming practices allows the  
caller to handle this "failed" result gracefully.

Unfortunately, this and other poor programming practices seem to be more  
pervasive in PHP books than most other languages.

Remove the "x" from my email address
Jerry Stuckle
JDS Computer Training Corp.

Site Timeline