Making Sense Of PHP Errors - Other Common Errors
(Page 3 of 4 )
One of the most common errors I see -- and quite possibly the most confusing -- occurs when you don’t end a function or loop with a curly bracket ( } ). This code, for example:
function UselessFunction() {
for($i < 0; $i < 10; $i++){
} Produces the following error:
Parse error: parse error, unexpected $ in c:\program files\apache group\apache\htdocs\ereg2.php on line 9 Because UselessFunction never ended it's function with a closing bracket (}), the PHP interpreter kept on looking for the closing bracket until the end of the file. Since it didn't find one, it reported the error at the end of the file.
While the mistake seems very obvious with properly indented code, without proper indentation, it eventually becomes nearly impossible to see what was forgotten. So remember, always indent your code… the tab key is your friend! It also makes things easier on future developers when they're trying to hack through your code to modify it.
MySQL Errors Another annoying error is the most common MySQL error, which often leaves PHP newbies scratching their heads:
Warning: Supplied argument is not a valid MySQL result resource in... The line it reports will often look something like this:
while($row = mysql_fetch_array($result)) { The argument, $result, is not a valid resource. In English, that means that since your query failed, it cannot process mysql_fetch_array. Either the query had invalid syntax (you should copy-paste your query into the MySQL console window to test it), or a connection failed to your database (in which case you should double-check your username, password, etc).
Preventing Errors From Occuring There are a few steps that a diligent PHP coder can take to eliminate some of these parse errors from happening in the first place:
- After the end of a statement, don't even think about adding a semicolon -- It should be second nature.
- Always indent your code, which allows you to see if you forgot to place a curly bracket after an if call, or the end of a function, etc.
- Use an editor (such as HTML-Kit) that highlights your syntax. Within the confides of this editor you will be able to see if you didn't escape a quote, missed a semi-colon, etc.
Next: Conclusion >>
More PHP Articles
More By Elan Bechor