[man]break[/man] and [man]continue[/man] 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.

    5 months later

    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

    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($log) log_error($msg,$priority); die('System Error: ' . $msg); case 3: // User / general error if($log) log_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:

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

      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: [man]nl2br[/man]! You have to convert the new line characters from the textarea fields to HTML break tags.

        Too add to LShryku's comment, an answer to another common question: "Why are there backslashes all over the place?"

        Use [man]stripslashes[/man]

          3 months later

          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.

          if(false !== $foo))
              echo $bar;
          
          print($foo .' '.$bar);
          
            a month later

            hmmm i for one like to have my code clean

            <?
            define( 'DEBUG'  , 1 );
            if ( DEBUG ){
                echo "something";
            }
            ?>

            I use this to display SQL from queries and time them (ALL OF THEM) for optimization and such niceties.

              4 months later

              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.

                Just to simplify on a seeminlgy good idea...

                functions.php

                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:

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

                [/B]

                  3 months later

                  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 [man]stripslashes[/man]

                  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.

                    a month later
                    GilesGuthrie wrote:

                    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:

                    $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:

                    $value = 2;
                    if (1 == $value)
                        echo 'one';
                    elseif (2 == $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.

                    barand wrote:

                    Check variable contents
                    Use something like this to check you received what you expected to receive

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

                    That could be done in one line:

                    echo '<pre>', print_r($_POST, TRUE), '</pre>';
                    

                    hth.

                      9 days later

                      or use // */ comments in your code, to check/uncheck it

                      used code:

                      echo '<pre>';
                      print_r ($_POST);
                      echo  '</pre>';
                      // */
                      

                      unused code

                      /*
                      echo '<pre>';
                      print_r ($_POST);
                      echo  '</pre>';
                      // */
                      

                        if your mysql comes up with error messages
                        instead of this line:

                        $q=mysql_query ( "SELECT * FROM table" );
                        

                        do

                        //$q=mysql_query 
                        echo ( "SELECT * FROM table" );
                        

                        so you can see the sql directly

                          kakki wrote:

                          if your mysql comes up with error messages
                          instead of this line:

                          $q=mysql_query ( "SELECT * FROM table" );
                          

                          do

                          //$q=mysql_query 
                          echo ( "SELECT * FROM table" );
                          

                          so you can see the sql directly

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

                          echo "SELECT $columns FROM $table $where";
                          

                          would be more appropriate 😉

                            6 months later

                            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.

                              2 months later

                              Bung Xdebug onto your server

                              The Xdebug extension from PECL is something to go on your development server. It boosts PHP's error reporting with a lot more information about what it was doing when the fault occurred.

                                8 months later

                                Hi all,

                                there have been a few suggestions in this thread regarding how to benefit from var_dump and print_r. Over the years I've come to the following dumping functions which are available in all of my PHP projects and are quite handy.

                                Simply spoken, "vd" means "var_dump" only that is shorter and more useful.
                                "vdd" means "var_dump and die" - stops execution immediatly after output.

                                /**
                                 * vd functions version 1.1 by matto
                                 *
                                 * dump any object
                                 * set return_it to true so the dump will be returned as a string
                                 * otherwise it will be dumped to the screen
                                 * html_entities filter will be applied
                                 *
                                 * @param mixed $anobject, boolean return_it
                                 */
                                function vd($anobject, $return_it=false)
                                {
                                        ob_start();
                                        var_dump($anobject);
                                        $out = ob_get_contents();
                                        ob_end_clean();
                                
                                    if(!$return_it)
                                    {
                                            echo "<pre>";
                                            echo htmlentities($out);
                                            echo "</pre>";
                                    }
                                    else
                                    {
                                            return htmlentities($out);
                                    }
                                }
                                
                                function vdd($anobject)
                                {
                                        vd($anobject);
                                        exit;
                                }

                                Everything gets nicely formatted, HTML won't be interpreted, plus you can re-route output into a variable in order to collect it for later display. Hope you find it useful.

                                  Weedpacket mention Xdebug just above, which can also format the output of var_dump() for a browser. It also creates some process log files which can be analysed in KCacheGrind or the windows equivalent WinCacheGrind. Handy for finding code bottlenecks.

                                    matto wrote:

                                    "var_dump and die"

                                    That reminds me; anyone else been thinking of PHP t-shirt slogans? 🙂

                                      3 months later

                                      Cut-and-paste code does not work

                                      As the programmer, it is your responsibility to understand what your code is doing and what it is supposed to do; the computer is not capable of doing that for you. Taking chunks of other people's code and inserting them into yours without bothering to work out how to use them is a sure way of turning your code into an unworkable mess.

                                      If it's a class, study its interface to see what it provides and then decide if you can use it to do what you're wanting. If it's just a fragment of code of the sort that is posted here to illustrate a solution, remember that it is just an illustration and not necessarily the real thing. Who knows what it will do when you run it? If you don't, you're in trouble.