Debugging 101 - Page 2
Page 2 of 5 FirstFirst 1234 ... LastLast
Results 16 to 30 of 61

Thread: Debugging 101

  1. #16
    0100101100100110 FrozNic's Avatar
    Join Date
    Apr 2003
    Location
    http://www.originalityisoverrated.com
    Posts
    333

    Cool

    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!

  2. #17
    50,000 Watts of Goodwill goldbug's Avatar
    Join Date
    May 2003
    Location
    Rummaging through your garbage.
    Posts
    1,315
    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.
    Many eyes make few mistakes

    goldendance

  3. #18
    Sonic Member
    Join Date
    Aug 2002
    Posts
    39
    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:
    PHP Code:
    function dump($var$label '')
    {
        echo 
    '<h1>'.$label.'</h1>';
        echo 
    '<pre>';
        
    var_dump($var);
        echo 
    '</pre>';

    Now am using some nice code I found here.

    2. In order to reduce typos I avoid declaring more variables that i strictly need. A basic example:
    PHP Code:
    /**
    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.

    3. 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.
    PHP Code:
    $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_
    Last edited by abx_2112; 07-24-2003 at 04:42 AM.

  4. #19
    Junior Member
    Join Date
    Jul 2003
    Posts
    8
    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!

  5. #20
    the stand in Telepath tekky's Avatar
    Join Date
    Jul 2003
    Location
    College Station, Texas
    Posts
    2,258
    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!
    the very reason why I practice
    PHP Code:
    $vars 'lowercase only'
    -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!)

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

    Look and see what you get

    Look at the script's output.

    If your HTML page is coming out mangled in some way, have a look at the HTML source code the browser is receiving (most browsers will allow you to "View Source" - if you don't have one, get one). Sometimes it's not enough to just look at the rendered page.

    All too often people post problems like "I want to print [stuff] on different lines but it all comes out on one line." or "my form variables are getting shortened". If these people viewed the source they'd probably see things like
    Code:
    <p>
    I think I shall never see
    An HTML page as pretty as me
    </p>
    ("Oh, yes, that's right. HTML replaces line breaks with spaces. I need to turn those into <br> tags. That's nl2br.")

    and
    Code:
    <input type=text value=First name last name=bunchawords>
    ("Ah, now I know why I'm supposed to quote my tag attribute values. How else is the browser supposed to know where the value ends and the next attribute begins?")

    You might also find things like mislaid tags, discover that something that should have been inside a loop wasn't or vice versa, text HTML characters like < and > inside select options or textareas that is being mistaken for HTML (this is even easier in a browser that does sytnax highlighting in its view source window), and so on. (This last one happened to me today; HTML had accidentally got into the database and whenever that database field was printed out, the page went odd.)
    Last edited by Weedpacket; 11-19-2004 at 04:02 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

  7. #22
    black sheep with red wool Merve's Avatar
    Join Date
    Jul 2003
    Location
    North of the 49th parallel
    Posts
    2,193
    Functions and Arguments

    This is a really dumb, but not so common error. Supplying incorrect arguments to functions. I've seen coding where someone tried to pass an array to explode()...doesn't work too well...

    Also, when using your own functions, you might forget to supply arguments...very possible...I do that a lot, but I don't know if anybody else does.

    Finally all constants are CAPITALIZED.

    Wow that was simple stuff.
    "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

  8. #23
    Better fan than rebelo! Moonglobe's Avatar
    Join Date
    Apr 2003
    Location
    brain://localhost:left-side
    Posts
    2,044
    Check your configuration!
    A little while ago i was coding a test site using Slabatron for XSLT............. only to find that my server didn't have the extension installed. always run phpinfo() if your not sure about your server's capabilities.
    there's no place i can be, since i found serenity.

  9. #24
    Missing in Action LordShryku's Avatar
    Join Date
    Aug 2002
    Location
    Occupational Hypnotherapy
    Posts
    7,227
    SQL errors? Make sure none of your table's field names are named a MySQL Reserved Word

  10. #25
    @r8r sid's Avatar
    Join Date
    Aug 2002
    Location
    linz/austria
    Posts
    709
    if you dont get an actual error but the result you get is bogus, check what path your code is going (especially if it includes many nested structures):

    simply print out a mark each time your code offers more thatn one option to walk through it, to see what it actually does:

    PHP Code:
    <?php 
    if (...) {
        print 
    "<BR>mark 1<BR>";
        while (...) {
            print 
    "<BR>mark 2<BR>";
            if (...) {
                print 
    "<BR>mark 3<BR>";
            }
            elseif (...) {
                print 
    "<BR>mark 4<BR>";
                
    forechach (...) {
                    print 
    "<BR>mark 5<BR>";
                }
            }
            else {
                print 
    "<BR>mark 6<BR>";            
            }
        }
    }
    else {
        print 
    "<BR>mark 7<BR>";
    }
    ?>

    thisll give you a nice output like

    PHP Code:
    mark 1

    mark 2

    mark 4

    mark 5

    mark 5 
    you can also print out variables on each mark to check the values... all over this is a very effective way to follow the path of your code and find out where could be a glitch (very handy for cases like (if $foo = 1) {...} )
    @r8r · google+ · r8r.us · websalat · fresh new media solutions · <?PHPBuilder Profile?>

    Fatal error: Call to undefined function: signature() in /home/virtual/var/www/html/showthread.php on line 87
    X 666 X

  11. #26
    Member dta's Avatar
    Join Date
    Oct 2003
    Location
    n.jersey
    Posts
    81
    more for php/javascript pages
    check on multiple browsers

    what javascript does on IE might not be the same on Netscape, etc.etc.

    an added note, the builtin javascript debugger in Mozilla/Netscape is amazing if something in your script isnt what it should be

    $drink->heineken();

  12. #27
    black sheep with red wool Merve's Avatar
    Join Date
    Jul 2003
    Location
    North of the 49th parallel
    Posts
    2,193
    Originally posted by LordShryku
    SQL errors? Make sure none of your table's field names are named a MySQL Reserved Word
    MySQL reserved words

    If you must use a MySQL reserved word for some strange and wacky reason, be sure to use backticks. If not absolutely necessary, this should be avoided.
    "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

  13. #28
    Senior Member
    Join Date
    Apr 2003
    Location
    London, UK
    Posts
    151
    Just a simple one:

    All my code uses echo for outputting to the screen, but if I need to output something for debugging, then I use print instead, then when I go back over my code, I know easily which lines are real code and which I can take out.

  14. #29
    Pedantic Curmudgeon Weedpacket's Avatar
    Join Date
    Aug 2002
    Location
    General Systems Vehicle "Thrilled To Be Here"
    Posts
    21,855
    Originally posted by njm
    Just a simple one:

    All my code uses echo for outputting to the screen, but if I need to output something for debugging, then I use print instead, then when I go back over my code, I know easily which lines are real code and which I can take out.
    Hey, nifty!
    Reminds me of a practice I employ: exit() to stop the script processing because there's nothing more for it to do (e.g., after a header("Location:") call); die() to stop the script processing because something went wrong and it can't continue (e.g., the dbms has fallen over).
    Last edited by Weedpacket; 02-04-2006 at 07:28 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. #30
    Senior Member
    Join Date
    Dec 2002
    Posts
    536

    error_reporting(E_ALL);

    What philipolson said: use error_reporting(E_ALL).

    It can be hard at first, because you'll probably have a whole bunch of code that works fine but when you turn up error_reporting to E_ALL it starts spewing "notice" messages like crazy.

    It's worth it though, as you will end up saving lots of time in debugging. Things like mistyped variable names that would silently pretend to work and fail oddly at some later point in the code will now give you a notice message at exactly the line with the typo. Typos and similar bugs that used to cause hours of head-scratching can be found and fixed in seconds with error_reporting(E_ALL) enabled.

    It does take some effort to avoid notices in innocent code. Namely, you need to use isset() or empty() to check if variables are okay. Most of these "needless" checks are related to form variables. I recommend creating a function (call it getvar or something) that gets form variables, handling all of the isset checking. It could substitute a default (like, an empty string) if no value is set so that you can avoid notices related to undefined values. Having a seperate function for getting form variables gives you the opportunity to do other things to, like checking the get_magic_quotes_gpc() setting and doing addslashes()/removeslashes() (whichever you prefer), allowing your code to work correctly no matter how the server is configured. Put this function and the error_reporting(E_ALL) call in a common include file and include it at the top of every script.

    And remember: null and the empty string are not the same thing! '' is a string of zero length. null is the complete lack of any string or other value. PHP can automaticly convert null to '', leading novices to believe they are the same). Those automatic conversions generate a notice with E_ALL so be aware of the difference.

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
  •