When your code isn’t doing what you think it ought to be doing, you need to examine and test your code to pinpoint where the problem lies. You need to be able to describe what the code is doing wrong, in addition to what is being displayed wrong in the browser.
These tests are easy and quick, and will help you discover where the problem lies in order to ask a coworker for assistance, and even perhaps to discover where the solution lies.
- Indent your code according to our style guidelines. This can show you where the logic is failing, whether it’s a missing close brace, a misplaced ENDIF, or an ELSE attached to the wrong IF. It is also a necessity if you want to ask someone else to look at your code and understand the expected logic and flow enough to assist you.
- If it involves PHP, add the PHP test lines to the very top of your code. If the page doesn’t display at all, run it through command-line php. But be careful for errors that only show up on the command line, such as MySQL connections that are forbidden except from the server. These errors can become red herrings that waste your time. Only trust the command line over warnings displayed by PHP in the browser if the page isn’t displaying any warnings at all.
- If it involves a PHP variable, use print_r to make sure that the variable contains what you think it contains. echo '<pre>VariableName:'; print_r($variable); echo '</pre>';
- When asking a colleague for assistance, describe the problem in terms of the HTML and the code that generates it. Since you’ve viewed source and you know what is generating that source, you should now be able to describe the problem in terms of what the code is doing, in addition to or rather than how the code is displaying. Often, describing the problem shows you where the error is.
- If you choose to troubleshoot further, make guesses, not assumptions. Assumptions permanently restrict your ability to find the true error. Guesses focus your attention temporarily on a specific part of the code. Many of your assumptions will be correct, and will not trip you up; but many will also be incorrect, and will make finding the error impossible until you lose the assumption. As a rule of thumb, if you’re ignoring PHP’s warnings and/or errors, or you’re disbelieving what print_r tells you a variable contains, you have made an unsupportable assumption. Turn it into a guess, and test it.