Debugging 101
Page 1 of 5 123 ... LastLast
Results 1 to 15 of 61

Thread: Debugging 101

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

    Exclamation Debugging 101

    As mentioned in a post I recently read http://www.phpbuilder.com/board/show...eadid=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 :
    PHP Code:
    $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) :
    PHP Code:
    $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)
    Last edited by Bunkermaster; 05-23-2003 at 03:34 AM.

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

  2. #2
    Parse error line -1 Bunkermaster's Avatar
    Join Date
    Sep 2002
    Location
    France
    Posts
    1,769
    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

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

  3. #3
    Senior Member
    Join Date
    Feb 2003
    Posts
    508
    Comment closing brackets {}

    PHP Code:
    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.
    Last edited by Bunkermaster; 05-23-2003 at 02:20 PM.

  4. #4
    Parse error line -1 Bunkermaster's Avatar
    Join Date
    Sep 2002
    Location
    France
    Posts
    1,769
    Did a slight edit here to remove extra lines in code (shows double in FireBird each time... Annoying)

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

  5. #5
    50,000 Watts of Goodwill goldbug's Avatar
    Join Date
    May 2003
    Location
    Rummaging through your garbage.
    Posts
    1,315
    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):
    PHP Code:
    $moo 'This is what ' $cow 'said to me.'
    Instead of:
    PHP Code:
    $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).
    Many eyes make few mistakes

    goldendance

  6. #6
    Parse error line -1 Bunkermaster's Avatar
    Join Date
    Sep 2002
    Location
    France
    Posts
    1,769
    Yes goldbug but you have made the typical error

    PHP Code:
    // 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.

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

  7. #7
    NULL Mordecai's Avatar
    Join Date
    Mar 2003
    Location
    Springfield, MO, USA
    Posts
    2,020

    Remove headers!

    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.
    - cai
    caiPHP

  8. #8
    Senior Member xblue's Avatar
    Join Date
    Dec 2002
    Location
    Europe
    Posts
    1,100

    debugging parse errors:

    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?]
    No keyboard found. Press F1 to continue...

  9. #9
    Senile Member
    Join Date
    Oct 2002
    Location
    Cheshire, UK
    Posts
    1,658

    Check variable contents

    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>'
    Last edited by Bunkermaster; 05-27-2003 at 06:17 AM.
    Barand

  10. #10
    Senior Member Tekron-X's Avatar
    Join Date
    Oct 2002
    Posts
    294
    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.
    Tek

  11. #11
    Member GilesGuthrie's Avatar
    Join Date
    Jun 2003
    Location
    Edinburgh, UK
    Posts
    43
    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.
    Take a break on the web at giles-guthrie.com

  12. #12
    Pedantic Curmudgeon Weedpacket's Avatar
    Join Date
    Aug 2002
    Location
    General Systems Vehicle "Thrilled To Be Here"
    Posts
    21,771
    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.
    Last edited by Weedpacket; 06-14-2003 at 07:26 AM.
    THERE IS AS YET INSUFFICIENT DATA FOR A MEANINGFUL ANSWER
    FAQs! FAQs! FAQs! Most forums have them!
    Search - Debugging 101 - Collected Solutions - General Guidelines - Getting help at all

  13. #13
    Pedantic Curmudgeon Weedpacket's Avatar
    Join Date
    Aug 2002
    Location
    General Systems Vehicle "Thrilled To Be Here"
    Posts
    21,771

    Leave @ off until later.

    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.:
    PHP Code:
    $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.
    THERE IS AS YET INSUFFICIENT DATA FOR A MEANINGFUL ANSWER
    FAQs! FAQs! FAQs! Most forums have them!
    Search - Debugging 101 - Collected Solutions - General Guidelines - Getting help at all

  14. #14
    Pedantic Curmudgeon Weedpacket's Avatar
    Join Date
    Aug 2002
    Location
    General Systems Vehicle "Thrilled To Be Here"
    Posts
    21,771

    Deal with the first error first.

    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.
    Last edited by Weedpacket; 02-04-2006 at 07:30 AM.
    THERE IS AS YET INSUFFICIENT DATA FOR A MEANINGFUL ANSWER
    FAQs! FAQs! FAQs! Most forums have them!
    Search - Debugging 101 - Collected Solutions - General Guidelines - Getting help at all

  15. #15
    42
    Join Date
    Oct 2002
    Location
    Portland, Oregon
    Posts
    299
    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 Code:
    <?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.
    Do not fear the manual and ask questions the smart way.

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
  •