Debugging 101 - Page 3
Page 3 of 5 FirstFirst 12345 LastLast
Results 31 to 45 of 61

Thread: Debugging 101

  1. #31
    black sheep with red wool Merve's Avatar
    Join Date
    Jul 2003
    Location
    North of the 49th parallel
    Posts
    2,193

    break and continue

    break and continue are great and are often ignored. They can shorten code bigtime. Their optional numerical arguments are great. Without using them, one may end up really long code that is much harder to debug.
    Last edited by Merve; 01-09-2004 at 08:25 PM.
    "A proof is a proof. What kind of a proof? It's a proof. A proof is a proof. And when you have a good proof, it's because it's proven." -- Jean Chrétien

    The Three C's

  2. #32
    Senior Member Tekime's Avatar
    Join Date
    Aug 2002
    Location
    Portland, ME
    Posts
    116

    error levels

    error levels

    You may need to differentiate between error levels - such as errors generated by a form, a 'no results returned' error, etc. vs. system or database errors.

    Use a generic error handler to customize error handling. You can already control error handling through PHP, but you might want generic application-level error handling. My scripts use a lot of templating stuff, but something along the lines of:

    functions.php
    PHP Code:
    function s_error($msg='Undefined Error'$kill=false$priority=3$log=false)
    {
        switch(
    $priority)
        {
              case 
    1// Alert the troops
                  
    log_error($msg,$priority);             
                  
    sound_the_alarms($msg);
                  die(
    'We might not be back for a bit.');
              case 
    2// Unrecoverable system error
                  
    if($loglog_error($msg,$priority);
                  die(
    'System Error: ' $msg);
              case 
    3// User / general error
                  
    if($loglog_error($msg,$priority);
                  echo 
    "Sorry, an error occurred: " $msg;
                  break;
              default: 
    // Or however else you want to handle this by default
                  
    die('Unspecified error');
        }
        return 
    false;


    Obviously, a lot more can be done with this, like handling error codes, formatting user errors, sending messages off to your mobile, etc. I check for an array in $msg and list multiple errors through a templater for example.

    This way you can handle unrecoverable errors, or just spit general errors back to the user:

    PHP Code:
    if(!database_exists()) s_error("Our database has been stolen!",true,1,true); 
    PHP Code:
    if(!is_friendly($_POST['username'])) s_error("Sorry, you're mean!"); 

  3. #33
    Missing in Action LordShryku's Avatar
    Join Date
    Aug 2002
    Location
    Occupational Hypnotherapy
    Posts
    7,227
    Alright, I've answered this question so many times now...

    Q: I have a form with a textarea. When the user submits the form, the multiple lines from the textarea are all on one line. Why?

    A: nl2br! You have to convert the new line characters from the textarea fields to HTML break tags.

  4. #34
    black sheep with red wool Merve's Avatar
    Join Date
    Jul 2003
    Location
    North of the 49th parallel
    Posts
    2,193
    Too add to LShryku's comment, an answer to another common question: "Why are there backslashes all over the place?"

    Use stripslashes
    "A proof is a proof. What kind of a proof? It's a proof. A proof is a proof. And when you have a good proof, it's because it's proven." -- Jean Chrétien

    The Three C's

  5. #35
    Parse error line -1 Bunkermaster's Avatar
    Join Date
    Sep 2002
    Location
    France
    Posts
    1,769

    "Our ASP will blot out the sun!"
    "Then we will PHP in the shade"

  6. #36
    Banzi suepahfly's Avatar
    Join Date
    Jun 2004
    Location
    The Netherlands
    Posts
    53
    As someone mentioned somwere on this forum;
    Use print(); for debugging and ECHO for normal output.

    This way you can easily find them in your code.

    PHP Code:
    if(false !== $foo))
        echo 
    $bar;

    print(
    $foo .' '.$bar); 

  7. #37
    Parse error line -1 Bunkermaster's Avatar
    Join Date
    Sep 2002
    Location
    France
    Posts
    1,769
    hmmm i for one like to have my code clean
    PHP Code:
    <?
    define
    'DEBUG'  );
    if ( 
    DEBUG ){
        echo 
    "something";
    }
    ?>
    I use this to display SQL from queries and time them (ALL OF THEM) for optimization and such niceties.

    "Our ASP will blot out the sun!"
    "Then we will PHP in the shade"

  8. #38
    Not Yet Involved Shrike's Avatar
    Join Date
    Oct 2003
    Location
    The Eighth, Sursamen
    Posts
    2,277
    I sometimes put a die() statement after a debug statement, that way you often won't end up with a page of HTML masking your debug lines.

    Test your code in bitesize pieces, that is don't write an entire script and then debug it, write a function or a method and then debug it with dummy data.

    This leads naturally on to Unit Testing.

    Finally Comment Your Code! I am the worst offender for not doing this and it has often led to hours of confusion about why something does something.
    The Hundredth Idiot

  9. #39
    the stand in Telepath tekky's Avatar
    Join Date
    Jul 2003
    Location
    College Station, Texas
    Posts
    2,258

    Re: error levels

    Just to simplify on a seeminlgy good idea...

    functions.php
    PHP Code:
    function s_error($msg='Undefined Error'$kill=false$priority=3$log=false)
    {
        
    //one time call to a used everytime function
        
    if ($log === true)
            
    log_error($msg,$priority);
        switch(
    $priority)
        {
              case 
    1// Alert the troops
                  //assuming this log_error was supposed to be identical to the other 2 and removing it also
                  
    sound_the_alarms($msg);
                  die(
    'We might not be back for a bit.');
              case 
    2// Unrecoverable system error
                  
    die('System Error: ' $msg);
              case 
    3// User / general error
                  
    echo "Sorry, an error occurred: " $msg;
                  break;
              default: 
    // Or however else you want to handle this by default
                  
    die('Unspecified error');
        }
        return 
    false;



    Obviously, a lot more can be done with this, like handling error codes, formatting user errors, sending messages off to your mobile, etc. I check for an array in $msg and list multiple errors through a templater for example.

    This way you can handle unrecoverable errors, or just spit general errors back to the user:

    PHP Code:
    if(!database_exists()) s_error("Our database has been stolen!",true,1,true); 
    PHP Code:
    if(!is_friendly($_POST['username'])) s_error("Sorry, you're mean!"); 
    -Karl
    Problem solved? Mark your thread resolved!
    See how many times my link has been used to mark a thread resolved here
    (fixed to work with updated VBulletin... this works again!)

  10. #40
    Posts: 13
    Join Date
    Mar 2003
    Location
    Ewok Village (Wales) / Mos Ilford
    Posts
    1,593
    Originally posted by Merve
    Too add to LShryku's comment, an answer to another common question: "Why are there backslashes all over the place?"

    Use stripslashes
    It's hot needles in the eye time when I see "You put addslashes when you put data into a database and stripslashes when you take it out"

    It's become like an old wives' tale of sql programming.
    Not using [PHP] tags makes the baby jesus cry.
    The help of an enthusiastic idiot is worse than the sabotage of an expert.
    Don't be a PhPenis - RTFM - still stuck? Then go DAFT (Do A Fekkin Tutorial)

  11. #41
    Senior Member toplay's Avatar
    Join Date
    Dec 2003
    Location
    California, USA
    Posts
    597
    Quote Originally Posted by GilesGuthrie
    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.
    I'm just going to expand on this and share a tip that would help if you've been using literals and constants on the right side of an 'if' expression. Example code:
    PHP Code:
    $value 2;
    if (
    $value 1)
        echo 
    'one';   // This gets displayed
    elseif ($value 2)
        echo 
    'two'
    The equal comparison operator in PHP requires two equal signs (==) and not just one (=). One equal sign is an assignment operator. In the example code, the '1' was assigned to the $value variable at the first 'if' expression, and this made the expression evaluate to TRUE; causing the echo 'one' to be executed and displayed. With this type of code example, PHP produces no errors (when there's a variable name to the left of the equal sign). This makes debugging this kind of problem more difficult and potentially time consuming. It's not always very apparent.

    Here's a tip to avoid this problem in the future. Get in the habit of coding the 'if' expression with the literal value or constant first or to the left of the equal sign, like this:
    PHP Code:
    $value 2;
    if (
    == $value)
        echo 
    'one';
    elseif (
    == $value)
        echo 
    'two';  // This gets displayed 
    That way if you happen to make a mistake and put just one equal sign again, then PHP will give you a parse error. The code of '1 = $value' is invalid because PHP can't assign the contents of $value to '1' (a literal; it must be a variable). This could potentially save you lots of time in testing/debugging because you get an error alert.

    Quote Originally Posted by barand
    Check variable contents
    Use something like this to check you received what you expected to receive

    PHP Code:
    echo '<pre>';
    print_r ($_POST);
    echo 
    '</pre>'
    That could be done in one line:
    PHP Code:
    echo '<pre>'print_r($_POSTTRUE), '</pre>'
    hth.
    Last edited by toplay; 08-03-2005 at 06:09 AM.
    PHP Manual 1 2 | PHP Func/Ver List | MySQL Manual | Articles 1 | Snippet Library | Tips | How to ask

    Regex/PCRE: 1 2 3 4 5 6 7 8 9 | MySQL: 1 2 3 4 5 6 7 8 9 | PHP Security: 1 2 3 4 5 | PHP Compiler: 1 2

    FAQ | PHP GUI: 1 2 | PHP Magz 2 | "Just keep coding, coding, coding..." by toplay

  12. #42
    tryin hard 2 help kakki's Avatar
    Join Date
    Aug 2005
    Posts
    327
    or use // */ comments in your code, to check/uncheck it

    used code:
    PHP Code:
    echo '<pre>';
    print_r ($_POST);
    echo  
    '</pre>';
    // */ 
    unused code
    PHP Code:
    /*
    echo '<pre>';
    print_r ($_POST);
    echo  '</pre>';
    // */ 

  13. #43
    tryin hard 2 help kakki's Avatar
    Join Date
    Aug 2005
    Posts
    327
    if your mysql comes up with error messages
    instead of this line:
    PHP Code:
    $q=mysql_query "SELECT * FROM table" ); 
    do
    PHP Code:
    //$q=mysql_query 
    echo ( "SELECT * FROM table" ); 
    so you can see the sql directly

  14. #44
    the stand in Telepath tekky's Avatar
    Join Date
    Jul 2003
    Location
    College Station, Texas
    Posts
    2,258
    Quote Originally Posted by kakki
    if your mysql comes up with error messages
    instead of this line:
    PHP Code:
    $q=mysql_query "SELECT * FROM table" ); 
    do
    PHP Code:
    //$q=mysql_query 
    echo ( "SELECT * FROM table" ); 
    so you can see the sql directly

    not to be a hard*ss, but if i type in "SELECT * FROM table" then I have no need to echo it... maybe a better example like...

    PHP Code:
    echo "SELECT $columns FROM $table $where"
    would be more appropriate
    -Karl
    Problem solved? Mark your thread resolved!
    See how many times my link has been used to mark a thread resolved here
    (fixed to work with updated VBulletin... this works again!)

  15. #45
    Senior Member
    Join Date
    Jan 2006
    Posts
    137
    When working with databases, use a database object - And all queries are sent through it, eg

    $db->query("SELECT * FROM $table $where");

    Then, while your developing your site, you can have the db object always echo out the query being used (and runtime information that query took) to help in development.

    Another tip, 'return early'.

    If you can stop processing another line of code by doing a simple check, then do that. For example:

    Its better to do this:

    if ($data == '')
    return;

    Than:

    if ($data != '')
    {
    // do stuff here
    }

    And having it in one big IF statement.

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •