As mentioned in a post I recently read http://board.phpbuilder.com/d/10240313 (not all of it, it seams some people can't stop talking here so fast it's like IRC now) some people have NO IDEA whatsoever about debugging and actually finding errors so here are my useless hints :

1. When you code a MySQL query use new lines :

$sql = "SELECT
        `yourtable`,`field1` as f1,
        `yourtable`,`field2` as f2
        FROM
        `yourtable`
        ";

Why? If you have an error MySQL will give you line number referencing a line INSIDE the query. Always saves time to actually be able to use the info.

2. When you code a MySQL query echo it in a HTML comment (not in production) :

$sql = "SELECT
        `yourtable`,`field1` as f1,
        `yourtable`,`field2` as f2
        FROM
        `yourtable`
        ";
echo "<!--\n$sql\n-->";

Why? Well if your pages doesn't work try running your querries in phpMyAdmin or your DB manager and see the output. It sometimes is interesting.

More soon (tired now)

    add your tricks here, it is NOT c losed thread 😃 (or is it? /me checks) ok it is NOT a closed thread. Just use same coloring as i did so peeps can look at it fast

    [COLOR=#FF8000] for tricks titles

    Code goes inside [PHP] blocks 😃

      Comment closing brackets {}

      if (isset($_COOKIE["me"])) {
             Do all the code in here
                 if ($_COOKIE["me"] == 'poser') {
                     Do all the code in here
                 } else {
                     Do all the code here
                 } //Poser if
              } else {
                     Do all the code here
              } //Is Cookie Set
      

      Why? Because as applications get more and more nested this will help you solve the unexpected $end on line number XXX error and will help you figure out where the close } is.

        Did a slight edit here to remove extra lines in code (shows double in FireBird each time... Annoying)

          It's probably been mentioned before elsewhere, but when constructing strings, sql queries, whatever,....I prefer to escape out of the string (and use single-quotes where possible):

          $moo = 'This is what ' . $cow . 'said to me.';
          

          Instead of:

          $moo = "This is what $cow said to me."
          

          WHen using an editor that syntax-highlights, it makes it MUCH easier to pick out the variables (especially in large or complex strings).

            Yes goldbug but you have made the typical error 🙂

            // No space after $cow
            $moo = 'This is what ' . $cow . 'said to me.';
            // Space after $cow
            $moo = "This is what $cow said to me."

            hehe but good one especially when embedding in HTML strings.

              Remove all headers when you are about to debug. Specifically if you are working on an image script. If you output a PNG (or another format) using header("Content-type: Image/PNG"), then no errors can be echoed. Errors can only be seen if something is text/html, not an image. This just results in a broken image, since PHP still echoes out the error.

              Edit: Uhh.. I don't know how to use the board's code in the subject, so I took out the [color] thing.

                indent your code
                this helps to detect missing braces, and can help to spot logical errors, too.

                use an editor with syntax highlighting
                makes it easy to find unclosed strings or unescaped quotes within string.

                [bunkermaster, I think this might be more often needed in the newbie or general forum, maybe other moderators would be willing to place a reference there?]

                  Check variable contents

                  Use something like this to check you received what you expected to receive

                  echo '<pre>';
                  print_r ($_POST);
                  echo '</pre>';
                  
                  13 days later

                  WORK BACKWARDS

                  Most know this already but for those that don't...

                  When PHP spitts an error line and number out at you go from the line number given and if the error is not in that line work backwards.

                  The Reason for this is that PHP is not always accurate on its error line numbers.

                    Check for double-equals ==

                    If your conditional statement isn't working properly, and it's testing for equivalence, check that you've got two equals signs.

                      5 days later

                      Originally posted by Tekron-X
                      The Reason for this is that PHP is not always accurate on its error line numbers.

                      I wouldn't say that; I'd say that PHP reports the number of the line it was processing when it discovered that there was an error (if you miss out a }, PHP can't tell you where it should have been). So , depending on the error message, even if the error itself is not on the line indicated, that line may provide clues as to where the error actually is. For example, if it says that there was a type conversion error (where, say, an array was used where it expected a string), then one of the variables in that line is at fault: work backwards and see where they get their values from.

                        Leave using @ to suppress error messages until later.

                        When you tack an @ to the beginning of a function call, you prevent PHP from reporting any error messages the call generates. This feature was intended for use by people who want to write their own error-handling routines - e.g.:

                        $foo = @bar() or choke('bar() is broken!', __FILE__, __LINE__);

                        While you're debugging, you want errors to be reported as soon as PHP realises there is one to report. Otherwise, your script will either just stop without giving any clue as to why, or it will try and keep running and most likely have more problems later on (and the error messages you get then would be less help).

                        So leave the @ off unless you are sure that you are properly handling any suppressed errors or you are sure that ignoring them won't cause any problems later.

                          Deal with the first error first.

                          If your script suddenly starts haemorrhaging dozens of Warning and Notice messages, it's not a cause for panic: it doesn't mean that you've got dozens of bugs to fix - it's more likely to be one bug causing dozens of errors.

                          Concentrate on the first error message reported and fixing the problem causing it; don't worry about the others too much. There's a good chance that whatever caused the first error message to be displayed is also responsible for making the mess that the other messages are talking about. Two causes for haemorrhages are that (1) the message is coming from a line inside a loop, and is being reported every time the loop is run through, and (2) the first error was caused by bad data; PHP continued to run, but that bad data caused more and more data to be corrupted and PHP became more and more confused about what to do with it.

                          Sometimes PHP's act of displaying an error message is itself enough to cause the other errors, especially if you're using one of the various header-manipulating functions, like header() or setcookie().

                          So fixing the first bug reported can make the others magically disappear.

                          With experience, you can use the other messages as additional clues to what went wrong in the first place; you can think of them as tracking the flow of corrupted data through the script.

                            6 days later

                            Always code with E_ALL on and do not generate any errors.

                            Many functions return false on failure, you should check for that. One of the most common questions and errors is how people assume mysql_query() will return a valid MySQL resource 100% of the time. It won't. Instead you should check to make sure it doesn't return false, here's an example that demonstrates a few ways to check a functions returned value. I prefer to not use the 'or' operator (such as foo() or die(...)) as it's rather limiting but whatever, same idea:

                             
                            <?php
                            error_reporting(E_ALL);
                            
                            if (!$conn = @mysql_connect('localhost','user','pass')) {
                                echo 'Could not connect to MySQL: ' . mysql_error();
                                exit;
                            }
                            
                            if (!@mysql_select_db('somedb')) {
                                echo 'Could not select db: ' . mysql_error();
                                exit;
                            }
                            
                            // mysql_query returns false on failure
                            $sql = "SELECT foo,bar FROM stuff";
                            $result = @mysql_query($sql);
                            if (!$result) {
                                echo "Could not run query ($sql): " . mysql_error();
                                exit;
                            }
                            
                            // If we expect rows, let's make sure some exist
                            if (mysql_num_rows($result) < 1) {
                                echo "No rows match your query, please try again";
                                exit;
                            }
                            
                            // We know $result is valid, and rows exist to fetch
                            while ($row = mysql_fetch_assoc($result)) {
                                print_r($row);
                            }
                            ?>
                            

                            The above isn't perfect but demonstrates basic error handling. Of course printing our sql queries and mysql errors isn't good in a production environment so consider showing prettier user friendly errors in production environments. For example, if no rows exist, consider telling them but including the search form again. Or creating/using db_error() that prints something differerent in "debug mode". @ is used to supporess PHP errors because we implemented out own error handling instead of relying on PHP's warnings. Anyway, the point is that mysql_query() (or whatever you're using) does sometimes fail and return false as our world isn't perfect, also, rows don't always exist to fetch.

                              if u just can't figure out what the heck is wrong with ur code.. go watch southpark or simpsons for 10 mins, drink a quick md and eat a slice a pizza. go back to the comp. and suddenly ur prob will hit u in the face 🙂 okay, i know it doesn't always work, but, u'd be surpised how often 10 mins of breathing room can do!

                                20 days later

                                This isn't necessarily focused at just PHP:

                                When designing/coding an application, try to avoid hardcoding any proper nouns in anything (variable names, file names, site 'structures', etc...). It can be a huge pain in the ass to go back and change them later.

                                Example (which just so happens to be bothering me at work):

                                Your company's name is hardcoded into file names, contact addresses, what have you (recent situation: company name was hardcoded as the default "other" category for equipment -- used throughout code & database).
                                ....... what happens when/if your company changes name or gets bought?

                                Not sure if that makes any sense, but I've found keeping things vague or non-possessive saves a LOT of time, down the line.

                                If this still doesn't make sense, just code your stuff as if you were to design something completely generic, as to be sold to many different people. All branding, names, logos should be easily modified in one place and accept drop-in replacements.

                                  10 days later

                                  Ok, this are some things that help me debug my scripts:

                                  1. Keep trace of my vars: This is so important, and so basic. Sometimes the whole problem with your script is a typo which is ver frustrating.

                                  I even have a dump function to be aware of the values on arrays, objects, post/get/session/etc vars .... It started looking something like this:

                                  function dump($var, $label = '')
                                  {
                                      echo '<h1>'.$label.'</h1>';
                                      echo '<pre>';
                                      var_dump($var);
                                      echo '</pre>';
                                  }
                                  

                                  Now am using some nice code I found here.

                                  1. In order to reduce typos I avoid declaring more variables that i strictly need. A basic example:
                                    /**
                                    I dont like doing this kind of things:
                                    */
                                    $date = time();
                                    $log = $user_input . 'issued at' . $date;
                                    my_function($log);
                                    
                                    /**
                                    Instead, try using something like this:
                                    */
                                    my_function ($user_input . 'issued at' . time() );
                                    
                                    The are some exceptions to this (see this article for details and some other very important stuff), but keep in mind this practices not only improve your scripts' performance, but reduces a lot of time while tracing a value.
                                    1. Ok doing this all the time may result in some FREAKY code. That's why I use sprintf() when i need to give some formating or i see i have lots of function calls and stuff in the string.
                                      $string = sprintf('
                                          %s, keeping %f  things readable
                                          %d is easy %s',
                                          foo( 'bar', implode($words, $_GET['token']),
                                          $a - floor(rand($_apples)),
                                          $counter/2,
                                          $object->serialzeMe()
                                      );
                                      
                                      Get the point? Imagine doing the same thing concatenating all that stuff. That'll look horrible. Some people may find the use of sprintf unnecesary, but I personally like it.
                                    that's it for now.

                                    Hope this helps,
                                    Abx_
                                    15 days later

                                    DO get yourself into the habit of using a variable naming scheme, such as always capitalizing new words, using underscores, and using names that are relative to the variable.

                                    This will give you an idea of exactly what's going on, if you see $Person_Index instead of $Blah
                                    I bring this up because I was staring at code for a good half an hour before I noticed that I wrote $blah instead of $Blah for the index of an array. I looked everywhere for the error but the case of my variables!:eek:

                                      Originally posted by JDunmyre
                                      DO get yourself into the habit of using a variable naming scheme, such as always capitalizing new words, using underscores, and using names that are relative to the variable.

                                      This will give you an idea of exactly what's going on, if you see $Person_Index instead of $Blah
                                      I bring this up because I was staring at code for a good half an hour before I noticed that I wrote $blah instead of $Blah for the index of an array. I looked everywhere for the error but the case of my variables!:eek:

                                      the very reason why I practice

                                      $vars = 'lowercase only';

                                      😃