do professional PHP programmers use error checking in their code?

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

Threaded View

I've made it habit to check all returns in my code, and usually, on
most projects, I'll have an error function that reports error messages
to some central location. I recently worked on a project where someone
suggested to me I was spending too much time writing error messages,
and that I was therefore missing the benefit of using a scripting
language. The idea, apparently, is that the PHP interpreter writes all
the error messages that are needed, and that I shouldn't write such
code myself. I was given the impression that if I needed extensive
error checking, or strict typing, then I should use a real language,
like Java, but if I'm going to use a scripting language like PHP or
Ruby, then I should leave errors to the interpreter, since the whole
point of using scripting languages is speed of development. Has anyone
else heard this argument, and do you agree with it?  I'm wondering how
other PHP programmers handle error messages. Check everything or leave
it to the PHP interpreter to tell you when there is an error?

Which of these two functions is better, the one with error checking or
the one without?

function getWeblogEntries() {
    $query = "SELECT * FROM weblogs";
    $result = mysql_query($query);
    $howManyWeblogEntries = mysql_num_rows($result);
    for ($i=0; $i < $howManyWeblogEntries; $i++) {
          $row = getRow($result);
         echo "<h1>$headline</h1>";
         echo "<h7>$date</h7>";
         echo "<div class=\"mainContent\">$mainContent</div>";

function getWeblogEntries() {
    $query = "SELECT * FROM weblogs";
    $result = mysql_query($query);
    if ($result) {
      $howManyWeblogEntries = mysql_num_rows($result);
      for ($i=0; $i < $howManyWeblogEntries; $i++) {
            $row = getRow($result);
            if (is_array($row)) {
               echo "<h1>$headline</h1>";
               echo "<h7>$date</h7>";
               echo "<div class=\"mainContent\">$mainContent</div>";
          } else {
               reportError("In getWeblogEntries, the function getRow
failed to return an array on the $i iteration.");
   } else {
       reportError("In getWeblogEntries, the query to the database

My own feeling, obviously, is that it is better to error check
everything, and to write extensive comments everywhere. I've taken over
PHP projects, started by other programmers, that had no error checking
and no comments, and such projects are always a big pain in the neck. I
lose time playing Sherlock Holmes, trying to track down where a
function's parameter first originates and why it's in use. I'd rather
have a comment on it, and error message for when the wrong thing is
passed in. Obviously this slows development. Is there any concensus
among developers about what is the best approach? I think whatever is
cheapest for the client should be considered the best approach, but it
seems to me cheapest-in-the-short-term is quite different from

Re: do professional PHP programmers use error checking in their code?

Quoted text here. Click to load it

The one with error checking.

/Always/ check for errors and print a meaningful message. The interpreter
can't do that for you, no matter how impressive it is.

/Always/ comment your code, and for large projects, keep your design
documents around (you do make design documents, right?). It'll save
time and money in the long run.

And by long run, I mean more than two weeks after the code is finished.

Andrew Poelstra       <
To reach me by email, use `apoelstra' at the above domain.
"Do BOTH ends of the cable need to be plugged in?"  -Anon.

Re: do professional PHP programmers use error checking in their code?

Quoted text here. Click to load it

I agree with you, although I think the extent you take it to depends on  
the needs project.  Having quality error reporting is much different  
than interpreter errors.  An error like:

"You have an error in your SQL syntax; check the manual that  
corresponds to your MySQL server version for the right syntax to use  
near ') VALUES ( 1, 2, 'asdf', 'asdf',' at line 8"

doesn't tell you much other than there is problem.  A function like:

function myFunction($sql) {
        $result = @mysql_query($sql, $connection);
        if (!is_resource($result) && $result !== true) {
              die(mysql_error()." (Full query: ".$sql.") in function  
        return $result;

can save you lots of debugging, doesn't really take any extra time to  
write and gives the added benefits of showing both the interpreter's  
error, the full context of the error and the function used.  But this  
just describes an error that would kill the script anyway.  What if, as  
in your example, you needed program behavior to change based on  
external influences (I.E. user input, database results, etc.)?  In any  
'real' language (PHP is just as real as Java) you would be foolish not  
to have error checking and reporting.  Why wouldn't that apply to an  
interpreted language?  In the end, what's the difference other than the  
fact that it's not compiled into bytecode (you can compile PHP btw, )?  Most  
interpreter errors are comparable to compiler errors, and data checking  
in otherwise 'compilable' code is a necessity in any language.

Granted, I think you should take advantage of PHP's abilities when you  
can and when it makes sense (better not to re-invent the wheel, a tired  
phrase I know) but that hardly covers everything.

Re: do professional PHP programmers use error checking in their code?


Quoted text here. Click to load it

Personally, so far as MySQL stuff is concerned, I now use Adodb as
well as your method of if... else... echo... exit();

With Adodb you can easily turn on a higher level of Debug which
displays the SQL queries without you needing to do anything in the
Locate your Mobile phone: <
Great gifts: <

Re: do professional PHP programmers use error checking in their code?

The error-checking policies also evolve during time. At first projects
at my current job, there was not much error checking. Now there's still
lot to improve, but things are better. There's sort of error-checking
framework in use, and it evolves.

if( !$dbresult ) {
  HandleError("DatabaseError", "strErrorCode", "ELEVEL_CRITICAL", $sql,
mysql_error(), "Script location");

Well that's just from top of my head. But that's basically what happens
when there's an error. If error level is critical (or whatever), send
email to this address. Write all error to log.

So shortly my 5c is to always error check, and from project to project,
develop the error checking procedure according to needs and problems to
have a generic error checking process, which works for you and your
company policies.


Re: do professional PHP programmers use error checking in their code?

It is definitely the better way to include error checking, but only for  
fatal errors. When it comes to database errors it is FAR better to use the  
error message which is generated by the DBMS engine and access it via a  
customised error handler. So in your code you would have something like:

$result = mysql_query($this->query, $this->dbconnect) or  
trigger_error($this, E_USER_ERROR);

For details on how to customise the error handler take a look at

Tony Marston

Quoted text here. Click to load it

Re: do professional PHP programmers use error checking in their code?

Would you call a PHP programmer that does not check for errors a  
professional then?

Most web sites developed with PHP are a kind of "robot" that represent a  
company or person. Think of any web shop, for example. People pay real  
money when buying things through the internet.

Nobody is perfect, off course. So people do make mistakes. But when my  
"robot" makes a mistake (better said: discovers a mistake that I have  
made), I would like to know about it. So it saves any errors into a  
table or file, or sends it to me by e-mail.

Quoted text here. Click to load it

I am totally flabbergasted by this. First, these error messages are for  
you, the programmer. They can contain sensitive data about table names,  
file names, etc. You don't want to show the internal PHP message to a user.
Furthermore, because these messages are meant for you, you will miss  
them if they are only shown to a user. Especially if they are hard to  

Quoted text here. Click to load it

What a load of crap. On what planet his this person been for the last  
decade? PHP is an object-oriented language that is still backwards  
compatible with hacker-style or "blind panic" type of programming, but  
has outgrown it since long.
To speed up development, I have written classes that I share between  
projects (using SourceSafe or Subversion). So, database handling is  
something I have written just once. Error logging is something I have  
written just once. And so on. If you want to speed up development,  
prepare your code for reuse.

Quoted text here. Click to load it

I already answered that one, I think. Besides that, I write unit tests  
to get a feeling of the quality of my code. If error handling is already  
thought bad, writing unit tests will probably cost you your job.
But I still recommend them. They force you to program in a much more  
modular way, and they take away a lot of complexity when a project gets  

Quoted text here. Click to load it

I would check mysql_errno($connection) to see if MySQL really was told  
something it could understand. If not, make sure a developer gets the  
message returned by mysql_error($connection).

Quoted text here. Click to load it

There's even a better way: use good names instead of comments. Lots of  
editors feature some autocomplete or intellisense that show you the  
variable name. Consider:

function item($i) // $i is a one based integer


function item($intOneBasedIndex)

In the last case, your editor will show this "comment" when you use it,  
not just when you define it.

Quoted text here. Click to load it

Huh? You did all the Sherlock Holmesing in your own free time then? I  
also worked for a company that thought all quality as bad and too  
expensive. Most of my tasks involved writing or correcting two lines of  
code, and took at least three days trying to find which lines or where I  
could insert them. Now THAT is slowing down development.

Quoted text here. Click to load it

I think you get the point.

Best regards

Re: do professional PHP programmers use error checking in their code?

lawrence k wrote:
Quoted text here. Click to load it

Obviously either someone who was entirely clueless or a very sloppy  
programmer.  In either case there is no way I would want to work with  
anyone with that attitude.

Quoted text here. Click to load it

Definitely the second one is better.  Additionally, you've taken the  
extra step of hiding the MySQL error message itself - which is a good thing.

Those messages are meant for you, the programmer, and can contain  
information useful to hackers.  It's much better to keep that  
information private.

Although I do generally take the extra step of writing the MySQL message  
to an error log.

Quoted text here. Click to load it

Yes.  Do all of your own error checking, write messages you aren't  
afraid of your client or a website user seeing, and log more sensitive  
information to a file for later reference.

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

Re: do professional PHP programmers use error checking in their code?

Jerry Stuckle wrote:
Quoted text here. Click to load it

Actually the fellow (whom I took the project over from) is well
regarded in the town I live. He is mostly a C programmer. He's
apparently done quite a few projects (in C) that were quite successful.
Myself and a co-worker wondered if his PHP work was merely an
expression of haste, or design. From conversation, I was given the
sense the answer was "design". But I lost time figuring out his code,
and I feel that some comments would have done a lot to speed my
comprehension. I write error checks to make life easier for the next

Re: do professional PHP programmers use error checking in their code?

lawrence k wrote:
Quoted text here. Click to load it

Yep, I've had "hot shots" like that on teams before.  Quite frankly, I  
haven't been that impressed.

Give me a good programmer who checks response codes, comments code and  
follows a good design any day.

I do remember on rather large (15 programmers/1 year) project I managed  
several years ago.  One of them was one of these hot shots who was also  
"well regarded" by management.  But he wouldn't comment his code,  
wouldn't submit his code for code reviews, wouldn't change his code when  
it was reviewed - you get the idea.

I finally had to take it up with his manager.  His manager's comments  
were something on the order of "that's the way he is - you'll have to  
live with it".

The only thing was - my contract made me responsible for the project.  
To make a long story short, there was a lot of hemming and hawing on the  
manager's part.  But my contract gave me responsibility for successful  
completion of the project - and control over the people on it.  They  
finally had to take him off the project.

And you know what?  The project finished on time and within budget.  And  
the people on the project were much happier.  Seems a lot of them had  
problems with this "hot shot" - he wrote code that was fast and  
efficient, but no one else could understand it, either.

Interestingly enough, when the company found the project ran so much  
better with this guy, his reputation wasn't quite so hot.

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

Re: do professional PHP programmers use error checking in their code?

lawrence k wrote:
Quoted text here. Click to load it

I think you're missing a basic point. Error messages and code comments
are form of human communication. The merit of saying something versus
not saying something obviously depends on how the listener makes use of
the information communicated. Aimless verbosity does no one any good.

If we look at the messages in your example:

  "In getWeblogEntries, the function getRow failed to return an array
on the $i iteration."
  "In getWeblogEntries, the query to the database failed."

Say I'm a programmer picking up your project, how would I respond?
Well, all I know is that there is something wrong in getWeblogEntries.
So I do a search for getWeblogEntries, open the file and look. Even
without your messages though I would have done the exactly the same
thing. The messages emitted by PHP gives me the file path and line
number, so they actually do a better job.

In programming as in real life, don't open your month unless you have
something worthwhile to say. A few judicious utterances is better than
a constant stream of banalities.

Re: do professional PHP programmers use error checking in their code?

Following on from Chung Leong's message. . .
Quoted text here. Click to load it

Aha! Some sense from Chung Leong
* It is correct that programmers go WCPGW [1] like clocks go tick and  
cows go moo.
* But it doesn't necessarily follow that the way to deal with this is  
what the OP called 'error checking'.
* Distinguish between
   -  Errors and exceptions  (Exceptions are where something doesn't work  
as normal.  Errors are where an incorrect result/action is obtained.)
   -  Detection, reporting and handling

For example if (in the UK) I ask for a date then I want it in  
day-month-year order.  But you might be used to m-d-y and input to my  
form like that.
   "1-1-2006" is not an error or an exception
   "10-1-2006" is an error  (10th Jan accepted though you meant 1st  
   "1-15-2006" is an exception (you meant Jan 15th but my validation says  
there isn't a 15th month)
   (Not being able to handle "Unknown" or "2006" may be /faulty/ design.)
I'll leave readers to mull over the d,r,h issues with this example....

* Beware of tests that are not watertight, opaque or make a shot at, but  
don't pin down the conditions that matter.  In the example code given
             $row = getRow($result);
             if (is_array($row)) {
What does the function getRow() return?  Here I'll assume it is an alias  
for mysql_fetch_array() which returns FALSE if there's a problem.  So if  
the result is to be tested it is good practice to test according to the  
signals in the documentation.

It is the result of extract() that matters in the processing.  (Also  
it's a handy point to put in an assertion-style test along the lines of
   if(3==extract($row)){  // headline,date,mainContent

* Beware of complex 'error' handling introducing new problems.

* Don't forget try...catch

So, to conclude:  IMHO the original poster should get A for effort but  
would be better off with simply reporting a failure at the end of the  
routine.  I'd do this like:

function ReportWeblogEntries() {
// ------------------------------------------------
// Prints up to last 30 rows of Weblogs table (latest at top)
// Returns actual number of entries or -ve diagnostic for failure
// ------------------------------------------------
    $actualLogCount = -1; // default = failure diagnostic
    $query = "SELECT * FROM weblogs ORDER BY date DESC";
     if($rows=mysql_query($query)){  // fails on error
       $actualLogCount = mysql_num_rows($rows);
       // trap stupid number of rows inside loop
       for ($i=1; $i <= $actualLogCount; $i++) {   // note change of  
index base
             if($i>30){  // ENOUGH! STOP!
                $excess = $actualLogCount-($i-1);  // how many still left  
to print
                print("<hr><b>There are $excess more items (not  
             if($row = getRow($rows)){   // can never fail!
               if(3==extract($row)){ //headline,date,mainContent -> vars
                  print( "<h1>$headline</h1>
                  $actualLogCount = -2;  // diagnostic for can never  
                  $actualLogCount = -3;  // diagnostic for can never  
       } // end of step through results loop
   return $actualLogCount;  // normally 0 or +ve for no of rows

Note from my version that the function returns /diagnostics/ from the  
very first line.  Since you have to look at the code to understand  
exactly what's happening you don't need more than an alert and possibly  
a pointer.

Note that my version frees the database resource under 'all' conditions  
that matter.

Note that for the purposes of this exercise I've said "Nobody can  
possibly deal with more than 30 items at a time" - so showing more would  
be a /fault/ in the design.

Note the original function had a misleading name.

So spend less time on fancyfying the bits that you think might go wrong  
and more on discovering what the important failure modes are; and  
understanding the context in which the information is going to be used.

[1]What could possibly go wrong

PETER FOX Not the same since the bookshop idea was shelved
2 Tees Close, Witham, Essex.
Gravity beer in Essex  <

Re: do professional PHP programmers use error checking in their code?

Peter Fox wrote:
Quoted text here. Click to load it

Making that distinction is important. That's where the colleague of the
OP erred. Error handling/reporting in PHP is different not because it's
a scripting language. It's different because it's designed for web
application. Unlike desktop apps, the operating environment for web
apps is usually controlled by the programmer. That allows PHP to make
the assumption that any error encountered is a programming error and
accordingly, throwing up a message to inform the programmer. Take
fopen() for instance. In a desktop app it could fail in normal
circumstances (end-user mistake etc.) In a PHP app, when it fails it
usually means the programmer did something wrong, as the file being
opened can either be a file that's part of the app or a file uploaded.
The guy is correct is saying that it's pointless to do what PHP does
for you already.

Quoted text here. Click to load it

That's not a terribly good example, I must say. User errors should
always be expected. Handling them is part of a application's basic

Quoted text here. Click to load it

I didn't mention it since it's just an example, but there is really no
way for that condition to arise. If mysql_num_rows() succeeds, then
mysql_fetch_array() cannot fail, since the rows are in memory already.

Quoted text here. Click to load it

The only real failure modes are (a) the DB connection is bad, or (b)
the table weblogs is missing or don't have the right column names.
PHP's error reporting mechanism would inform you of both. If one wants
to be helpful, then say something that's actually informative like "the
database schema is incorrect, run create_tables.php to create the
database." Otherwise, if all you're writing are messages in the vein of
"an error happened," then you might as well leave it to PHP.

Re: do professional PHP programmers use error checking in their code?

Kimmo Laine wrote:
Quoted text here. Click to load it

Unless next_page.php generates PHP, the script with this include will
only get HTML.

Quoted text here. Click to load it


    if (isset($_GET['foo'])) {
      echo '<?php echo $_GET[\'foo\']; ?>';
    } else {
      echo '<?php echo \'Not available\'; ?>';

File not found: (R)esume, (R)etry, (R)erun, (R)eturn, (R)eboot

Re: do professional PHP programmers use error checking in their code?

lawrence k wrote:

Quoted text here. Click to load it

I believe other posters have given pretty firm answers to that... let me
just make a suggestion in the name of readability.

Instead of writing

  if ( ! $thereIsAnError ) {
      if ( ! $thereIsAnotherError ) {
      } else {
          // handle the second problem
  } else {
      // handle the first problem


  if ($thereIsAnError)

As you can see, this puts the error checking first in the file, and it also
prevents the unholy levels of if/else nesting that can occur if you use
if/else blocks for all of your error checking.  Assuming that handle_error()
will exit, you can just add a quick, two-line test to check for and handle
an error; there's no need to wrap the entire rest of the code in an else { }

Benjamin D. Esham  |  AIM: bdesham128  |  Jabber: same as e-mail
'I wish I had never come here, and I don't want to see no more
magic,' he said and fell silent.
                           — Sam in /The Fellowship of the Ring/

Re: do professional PHP programmers use error checking in their code?

 I'm not so sure that it is faster or cheaper to write sloppy or code.

 Most project have a life that extends much longer than the end of
development, so when you add up the debugging and maintenance over a
period of months or years, then the better and more fully documented
code will win every time.

 However, everything should be done in moderation.   Your example
shows maybe too much error checking and too little comments.

 Spend less time writing error checking and more time documenting your
code.  Search and Replace does wonders with this so you only write the
documentation comment once per procedure and replace it thruout the




Quoted text here. Click to load it

Re: do professional PHP programmers use error checking in their code?

Quoted text here. Click to load it

In my personal opinion and experience, if I were a project manager and  
I've heard the words "php will handle errors for you, why bother?" from  
any of the programmers I work with, I would fire that person on spot.  
It's HORRIBLE practice and it leads to lots of crap php code out there  
and also the "not serious programmer" stereotype about php developers  
(enforced mostly by java and c# folks - who (you've guessed it :) handle  
their errors and exceptions). So my advice is handle all the errors, USE  
the exceptions as much as you can, log errors for after analysis but  
don't reinvent the wheel (e.g. don't reinvent the text of DB error  
messages, just handle them and give them context).


B.r.K.o.N.j.A = Bionic Robotic Knight Optimized for Nocturnal Judo and  

Site Timeline