Practical PHP and MySQL Web Site Databases: A Simplified Approach (2013)

Chapter 12. Troubleshooting Your Database-Driven Web Site

As you worked through the chapters, you will have encountered many error messages. This is normal; even seasoned programmers see error messages as they develop new projects. If you can’t immediately locate where a mistake was made, walk away and return later when your frustration has subsided. I sometimes leave the problem for a day and continue with some other part of the project.

This chapter lists some of the problems, the error messages, and their solutions. If your problem is not in the list, try entering the error message into a search engine.

image Tip  I usually make a copy of a faulty page and save it with a new name. I can then experiment by changing the code on the copy rather than mess up the original page.

Humans can infer a meaning from poorly written or spoken grammar. For instance, despite the double negative, we know that “I ain’t got no money” means the man is broke. When listening to a hesitant speaker, we mentally omit the “ums,” “ers,” and “you knows” from each sentence so that we can understand what the speaker means. Computers are unable to apply common sense to code containing mistakes or extraneous characters. However, computers can provide very helpful error messages, and they are usually right, so read them carefully.

Although error messages can be frustrating, they are an extremely valuable tool because we learn better and faster from our mistakes, and the messages usually explain the mistakes in plain English. A small number of messages might seem cryptic, but familiarity will eventually help you to understand them.

image Tip  Don’t try random changes to fix a problem. Take time to think it through carefully. Then try one change at a time by commenting out and replacing the line(s) of code. If that change does not work, delete the new line and remove the comment-out characters to restore the original code. Comment-out the sections where you think the error occurred, but be very careful that your comment-outs do not cause a mismatch of curly brackets. Place the comment-outs around the code between a pair of existing curly brackets.

HTML Code Errors

Most WYSIWYG web editors have built-in error checking. For instance, Microsoft Expression Web 4 (now free) has an excellent error checker. The errors are highlighted in yellow, and pressing the F9 key in code view reveals and explains the errors step by step.

Browser Quirks

In the event of a display fault, don’t investigate the code until you try the page in a different browser. For example, if the page display is unsatisfactory in Internet Explorer, it might be fine in Mozilla Firefox or vice versa. In such a case, the code contains no errors, but you will need to use a conditional style sheet for the browser that gives a poor display. A conditional style sheet for Internet Explorer 8 was provided in some of the earlier chapters in this book. Many conditional style sheets are available at the following location:

http://quirksmode.org/dom/tests/stylesheets.html

Install the five main browsers in your computer: Internet Explorer, Mozilla Firefox, Safari, Chrome and Opera. Put their icons on the desktop, and test your pages in each browser as you work. You might find one of the following browser emulators to be helpful:

·     IE Tester from: http://www.my-debugbar.com/wiki/IETester/HomePage

·     Net Renderer from  http://netrenderer.com

·     https://browserlab.adobe,com/en-us/features.html

A Style Change Has No Effect

It’s particularly frustrating to make a style change and find that it has no effect. This is due to a style in some file that is taking precedence over the style you are trying to change. The rogue style is probably lurking in one of the included files. Remove styles from all included files, and place them in the main style sheet. Avoid inline styles and, wherever possible, remove internal styles from the <head></head> section of a page and place them in external style sheets. Reduce the number of external style sheets to an absolute minimum.

Most modern browsers have development tools that make it easy to see which styles are being applied to each element so that you can track and fix the rogue style.

A Page Fails to Validate

Always validate each page of a web-site code using the W3C validator available at http://validator.w3.org. Remember that PHP is run in the background and produces HTML. The validator scans the HTML and not the PHP script.

Validating with the W3C validator is an important form of troubleshooting. It ensures that your pages are correctly coded so that browsers do not produce odd results. Also, search engines will not be blocked by your minor coding errors when pages are valid. By using validated pages, visually impaired users will be able to access your pages; otherwise, small coding errors can baffle an automated screen reader. Mobile devices use cut-down versions of browsers, and they cannot cope with the errors in nonvalidated sites.

If you put styling instructions in an included file, the W3C validator will display a failure message in a red font like this: “Element style not allowed as child of element div.” To solve this problem, remove the style instruction from the included file and put the style in the main style sheet.

A PayPal Pull-Down Menu Does Not Work

Judging by the cries for help on the Internet, this is an occasional but frustrating problem. If using a pull-down menu results in a PayPal error message, you would normally check the code carefully to see if you can spot the problem. This usually fails to produce a solution. If you upload the code to a forum for analysis, the forum normally confirms your own analysis—that is, that the code is correct. At the time of this writing, if you send an e-mail to PayPal you will receive only a list of FAQs. Very rarely are the FAQs related to your problem.

To save yourself time and frustration, don’t fiddle with the PayPal code; instead, simply log in to your PayPal account, set up a new pull-down menu, and copy the code. Then replace the faulty code with the new code. When setting up the pull-down menu, omit the currency symbols, such as £, because these will display as a square box or some other symbol. If you try to replace the currency symbols with an entity, the code will usually fail.

PHP Script Errors

The three main error levels are as follows:

·     Errors: These errors halt the script, and the fault must be corrected.

·     Warnings: The script can recover from this error level, but the error should be found and corrected.

·     Notices: Minor errors in the script that need correcting. Often this is caused by a misspelled variable name.

Included Items Missing from the Display

“Includes” will appear only when you view the page using a URL. Check that XAMPP has been started and that Apache and MySQL are running. Also, check that the included files are actually in the folder specified in the PHP code.

Call to an Undefined Function

Either you called a function that you forgot to define, or there is a spelling error in the function call. You might have called what you thought was a standard PHP function that does not actually exist.

Cannot Redeclare Function

You have created a function and declared it twice; remove one of the declarations.

Undefined Index or Undefined Variable

Check the spelling of the index or variable, paying attention to the case of each letter. Check that the variable has been assigned a value. Perhaps you forgot to initiate the variable before you called it. A missing dollar sign (or an upper case S instead of a dollar sign) at the beginning of a variable will also cause this error to appear.

Empty Variable Value

This error is caused by forgetting the initial dollar sign or misspelling a variable. Check the case of each letter in a variable.

General Variable Errors

Echo statements provide a simple way to track down variable errors in a long script. Taking a registration script as an example, beneath each validation check add an echo statement.

For instance, where the e-mail variable is validated, add the echo statement as shown in bold type:

   // Check for an email address
   if (empty($_POST['email'])) {
   $errors[] = 'You forgot to enter your email address.';
   } else {
   $e = trim($_POST['email']);
   echo "<p>\$e is $e</p>\n";
   }

To test the script, deliberately cause it to stop running by omitting an entry in one of the fields. You will see the error message saying you forgot to enter data in one of the fields, and you will also see a list of variables and their content. You might see a variable that does not have the content you expected.

Headers Already Sent

Perhaps you called a header function after you sent some HTML (or even a space) to the browser. The following piece of code will fail because the header statement is preceded by some HTML:

<html>
<?php
header("location:somefile.php");
?>

This statement will work:

<?php
header("location:somefile.php");
?>
<html>

If you put a space before the <?php tag, the error message will reappear.

Blank Screen

This can be caused by the same fault that produces the “headers already sent” message.

If you are expecting a display produced by a looping array and nothing appears, you probably forgot that arrays start at zero and you started the loop at 1.

Some incorrect HTML or PHP can produce a blank screen. The fault can also result from an error that has halted the script.

Unexpected End of File in Line xxx

This is a common PHP error, and it refers to the last line in the file. It usually means you have a mismatched number of curly brackets or normal brackets. For instance, you might have 20 opening curly brackets but only 19 closing brackets. To find the missing bracket, try indenting the PHP code so that the brackets can be counted more easily. To find the error in a large file, print a hard copy of the code and then number all the left brackets with a red pen and all the right brackets with a green pen. The number of red brackets must equal the number of green brackets. Often, this error is caused by using a normal bracket instead of a curly bracket or vice versa. Free tools such as Notepad++ and Microsoft Expression Web Version 4 show helpful line numbers. Some HTML editors highlight tags that do not have a matching opening or closing tag.

Common PHP Parse Errors

Almost all parse errors are caused by missing items and unmatched items in PHP statements. Opening curly brackets or normal brackets might not have matching closing brackets. Opening quotation marks might not have a closing quotation mark. Perhaps the quotes don’t match—for instance, opening with a single quote and closing with a double quote or vice versa. If you forget to escape a quotation mark in a string, you will see a parse error. Following are some typical parse error messages.

You will see something like "unexpected (/)" or "unexpected (,)". These are the easiest PHP parsing errors to spot because the PHP parser directs you to the line and column in the code where the error is located.

Parse error: expecting (,) or (;) in /somefile.php on line 10

Often, this means that you forgot to close the statement with a semicolon.

A missing normal bracket ")" or quote mark can also trigger this error.

If you see an error message like this:

Parse error: unexpected T_echo, expecting (,) or (;) on /somefile.php on line 10

again, you omitted a closing semicolon, but this time it applies to the statement before line 10.

The incorrect nesting of quote marks can result in the “unexpected” type of error messages and a display you did not expect.

The following code will produce a parse error:

$some_variable =  "table width="960px">";

The parser reads the first double quote and assumes that the double quote following the equal sign signals the end of the statement.

Use a pair of single quotes around the 960px to prevent this, as follows:

$some_variable =  "table width='960px'>";

If you omit the final double quote, the parser will continue to read the code until it finds another double quote. This could be several lines down, so the error message refers to that line rather than the line where the error is located. If you can’t find the error on the line stated in the error message, move back through the lines until you find the mistake.

Unexpected T_STRING

The usual causes are a missing semicolon, missing quote, or missing double quote. An example of a missing quote follows:

$somevariable = 'fname ;

It should have been

$somevariable = 'fname' ;

Unexpected T_ELSE

Often this error results from having an extraneous semicolon after an if clause as follows:
 
If (some condition exists);
    {
    $result = "that condition exists" ;
    }

Remove the semicolon from the if clause to solve the problem. The error message can also appear if you have omitted one or more curly brackets, or you have more than one else clause in block of code. If you have more than one else clause, change the earlier one(s) to elseif so that you have only one else clause in a block of code.

Wrong Equals Sign

Check your code to see where you used the wrong equals sign. The rules for equal signs are as follows:

·     A single equals sign is used to assign a value to a variable.

·     If an item is to be equal to another item, you must use a double equals sign (==).

·     If an item is to be absolutely identical to another item, you must use three equals signs (===).

Failed to Open Stream

This message indicates the server cannot find a file or an included file. Either the file being called is not in the correct folder or the file name has a spelling error. Sometimes we can forget to give the correct path for the file. The error message can be the result of the following statement:

<?php include(header.php) ?>;

Instead, the statement should have been the following:

<?php include(includes/header.php) ?>;

Warning: Division by Zero

Neither PHP nor mathematics allow division by zero. The message will indicate the location of the error so that you can correct it.

Display Is Not What Was Expected

Although many errors are the result of omitting characters, extraneous characters can display something you did not intend; for instance, the following code seems fine at first glance:

for ( $var = 0; $var =5; $var++ ) ;
{ echo 'display something' <br>;
}

The code was intended to loop through and display a variable five times. Unfortunately, it displayed the variable only once. This is because there should not be a semicolon after the for statement. The extraneous semicolon halts the loop so that only one item is displayed by the echo command. This extraneous semicolon is the PHP equivalent of the spoken “er” or “um.” Humans can disregard them, but the PHP parser cannot.

MySQL Errors

Most MySQL and database errors are caused by the following:

·     Listing the clauses in a query in the wrong order

·     Misspellings

·     Unbalanced brackets or quotes

·     Unescaped apostrophes

·     With INSERT queries, the columns names don’t match the VALUES.

Table Displays Headings Only

When a table displays only the headings, it means that either (i) the item being searched does not exist in the database table or (ii) you know that the data exists, but the search criteria does not match the data in the database table. A typical case is shown in Figure 12-1.

image

Figure 12-1. A table may display only the headings

If you are sure that the data exists in the table being searched, the problem is that the SELECT query contains one or more incorrect items. A typical query is as follows:

$q = "SELECT ref_num, loctn, thumb, price, type, mini_descr, b_rooms, status FROM houses
WHERE loctn='$loctn' AND (price <= '$price') AND type='$type' AND b_rooms='$b_rooms'
ORDER BY ref_num ASC ";

Make a hard copy of the query so that you can refer to it and roll back the code if you mess up. Then, in your text editor, look for items that have a corresponding item in the WHERE clause. Delete one matching pair at a time, and test after each deletion.

If a populated table is then displayed, you know that the deleted item is the cause of the faulty display. You might find that the three pages involved in the process have differing entries. For instance, in the search page you might have the location items entered with hyphens such as South-Devon, Mid-Devon, and North-Devon; whereas in the administrator’s add-a-house page, you might have underscores, such as South_Devon, Mid_Devon, and North_Devon.

Access Denied

The “access denied” error message looks something like this:

    "Access denied for user 'root'@'localhost' <using password: YES>"

The YES means that a password was entered by the user; it does not mean that the user entered YES as the password. If the user failed to enter a password, you would see NO instead of YES.

The error message means that one or more of the items in your database connection file does not match the database details. It could be a misspelling in the connection file of any of the following items: user, password, host, or database name.

Syntax Errors

SQL syntax errors produce an error message like this:

Error 1064 (42000): You have an error in your SQL syntax

Fortunately, the message usually gives a clue to the whereabouts and cause of the error. It will say something like this: "near * FROM members at line 6". This means that line 6 contains an asterisk, and near that asterisk you will find the error.

Reference to a Primary Key Could Not be Created

If you try to set a foreign key in one table that links to a primary key in another table, ensure that both keys have exactly the same type and length. Otherwise, you will see an error message stating that the reference to the primary key could not be created.

Summary

This chapter described some error messages, and appropriate solutions were suggested. No doubt, you encountered many error messages as you worked through this book. In fact, you will always have to deal with error messages unless you are superhuman. I recommend that you recognize messages that are not mentioned in this chapter, make a note of them, and record the solutions.

We have come to the end of the instructional chapters, and you should now have an understanding of PHP and the basic principles for designing practical databases for web sites. I hope you will regard this book as a starting point for further study of PHP, MySQL and, in particular, security. This simplified approach to database design omitted such topics as PDO, Object Oriented Programming (OOP), Ajax, and Frameworks; none of them is essential. They are alternatives to the techniques employed in this book. The Appendix will help you locate resources for further study. You would also learn more by combining techniques from the chapters in this book.