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

Appendix

This Appendix contains details of four new downloadable files for arrays and PHP e-mailing. It has the following sections:

·     PHP quick reference

·        Downloadable files for arrays

·        Downloadable files for e-mailing

·     MySQL and phpMyAdmin quick reference

·     What next?

·     Resources (books and Internet help, including a forum tutorial, PayPal tutorials, PayPal forums, e-commerce resources)

PHP Quick Reference

The PHP references are in alphabetical order for rapid searching.

Arrays

Arrays are variables that store multiple values. The registration forms in previous chapters used an array to store all the error messages. The name of the array indicates a category, such as cars, error_messages, or cereals. In an array named cereals, the multiple values might beoats, barley, corn, and wheat. The array can be created using the following code:

$cereals = array();

The values can be inserted as follows (note that the key for the first value is zero):

<?php
$cereals = array();
$cereals[0] = "oats";
$cereals[1] = "barley";
$cereals[2] = "corn";
$cereals[3] = "wheat";
?>

The number inside the square brackets is known as the key. Every key has a value paired with it. The first key in our example has a valueoats. The following code will display the contents of the cereals array. The file is available in the downloadable files for the Appendix assimple_array.php.

<!doctype html>
<html lang=en>
<head>
<title>The simple array page</title>
<meta charset=utf-8>
<style type="text/css">
.cntr {text-align:center; }
</style>
</head>
<body>
<h2 class="cntr">This is the Array page</h2>
<p class="cntr">
<?php
$cereals = array();
$cereals[0] = "oats";
$cereals[1] = "barley";
$cereals[2] = "corn";
$cereals[3] = "wheat";
echo ("$cereals[0] " . "$cereals[1] " . "$cereals[2] " . $cereals[3]);
?>
</p>
</body>
</html>

The display would appear as follows:

Oats barley corn wheat

Note that the same array can also be initiated as follows:

$cereals = array("oats","barley","corn","wheat");

Associative Arrays

Associative arrays allow you to use strings called keys instead of reference numbers. This can provide more explicit code. Associative arrays use the array operator symbol =>. (Note that the symbol does not mean “equal to or greater than”). In the example given next, the => symbol indicates that the key Monday has the value “Clean car”. The key is case sensitive; “Monday” is not the same as “monday”.

image Caution  In associative arrays, pay particular attention to the punctuation and quotes. Especially remember not to add a comma after the final array value (Church in our next example).

Let’s look at an example with seven key/value pairs in an array that we will call $events. This file, named assoc_array.php, is available in the downloadable files for the Appendix.

<!doctype html>
<html lang=en>
<head>
<title>The associative array page</title>
<meta charset=utf-8>
<style type="text/css">
h2 { margin-left:150px; }
p {margin-left:250px; text-align:left; }
</style>
</head>
<body>
<h2 class="cntr">This is the associative array page</h2>
<?php
$events = array(
'Monday' => 'Clean car',
'Tuesday' => 'Dental appointment',
'Wednesday' => 'Shopping',
'Thursday' => 'Gardening',
'Friday' => 'Fishing',
'Saturday' => 'Football match',
'Sunday' => 'Church'
);
foreach($events as $day => $event) {
echo "<p>$day: $event</p>\n";
}
?>
</body>
</html>

The code produces the following display:

This is the associative array page

Monday: Clean car

Tuesday: Dental appointment

Wednesday: Shopping

Thursday: Gardening

Friday: Fishing

Saturday: Football match

Sunday: Church

The downloadable files for the Appendix include simple_array.php and assoc_array.php.

Comments

PHP accepts three symbols to indicate a comment as follows:

//A single line comment
#A single line comment
/*A multiple line comment
   some text
   some text
   some text*/

Concatenation

Concatenating strings means joining them together by using a period. See the $full_name, for example:

<?php
$first_name = 'Annie';
$last_name = 'Versary';
$full_name =$first_name . $last_name;
echo $full_name;
?>

The display would be as follows;

Annie Versary

Constants

Items that never change are stored as constants using the function define(). The function takes two parameters: the name of the constant and its fixed value. Because I have no intention of changing my first name, I could define it as a constant as follows:

<?php
define('MY_FNAME', 'Adrian');
echo = 'Hello';
echo = MY_FNAME;
?>

The display would be:

Hello Adrian

image Note  Constants do not use a dollar sign because they are not variables.

E-mailing with PHP

PHP provides an easy method for sending e-mails using the mail() function. The format is as follows:

mail($to,$subject,$message,$headers);

You can confirm that your hosting company’s e-mail server will respond to PHP instructions. Create a PHP file named simple_email.php, or use the downloadable file. Then insert your own e-mail address in place of the two dummy addresses me@myisp.co.uk:

<!doctype html>
<html lang=en>
<head>
<title>Testing a simple email</title>
<meta charset=utf-8>
</head>
<body>
<?php
mail("me@myisp.co.uk", "This is a subject", "This is the body of the email", image
"From:me@myisp.co.uk\r\n");
?>
</body>
</html>

Upload the file simple_email.php to the host, and then access the file from a browser. You will see a blank page, but you should receive an e-mail via your usual e-mail client, such as Windows Live Mail or a web mail client.

Note that \n stands for a new line and \r stands for a carriage return or Enter. Together they drop down one line and start a new line from the beginning—that is, from the left side of that line.

A more practical version, multiple_email.php, includes multiple recipients and uses variables instead of hard coding. As a first test, I used my alternative e-mail address to replace recipient-1. The e-mail addresses of cooperative friends or colleagues were used for recipient-3and recipient-4. The code for multiple_email.php shown next is provided in the downloadable files for the Appendix.

<!doctype html>
<html lang=en>
<head>
<title>An email for multiple recipients</title>
<meta charset=utf-8>
</head>
<body>
<?php
$to = "me@myisp.co.uk,recipient-2@someisp.co.uk";
$subject = "My email test.";
$message = "This is the body of the email";
$headers = "From:me@myisp.co.uk\r\n";
$headers .= "Reply-To:me@myisp.co.uk\r\n";
$headers .= "CC:recipient-3@someisp.co.uk\r\n";
$headers .= "BCC:recipient-4@someisp.com\r\n";
mail($to,$subject,$message,$headers);
if ( mail($to,$subject,$message,$headers) ) {                                            #1
   echo "The email has been sent!";
   } else {
   echo "The email has failed!";
   }
?>
</body>
</html>

The elements To:, CC:, and BCC: can consist of several recipients. You accomplish this by using a comma-separated list as shown in the line beginning with $to. To use the file with fewer recipients, simply delete the unwanted items. Save the file as multiple_email.php, and upload the file to a host. Then access the file from a browser. You should receive the e-mail(s) via your usual e-mail client, such as Windows Live Mail or web mail.

Explanation of the Code

The top section of an e-mail is the header. The variables called $headers supply the header with its content. The $headers are concatenated using a dot and an equals sign (.=), and each one is moved down a line by the code (\r\n).

if ( mail($to,$subject,$message,$headers) ) {                                            #1
   echo "The email has been sent!";
   } else {
   echo "The email has failed!";
   }

This block of code is optional and can be deleted. It will let you know whether the e-mail was sent or not, but it will not tell you whether it was received.

Functions

function is a self-contained piece of reusable code that performs a task when called. PHP has over a thousand built-in functions. In this book, you have been using several built-in functions, for instance: array(), mysqli_real_escape_string(), include(), require(),strip_tags(), count(), and mysqli_connect().

A function name can contain letters, digits, and underscores but not hyphens. The name must not begin with a digit, and function names are not case sensitive. A function can be created by the web designer using the following format:

function function_name()
{ task to be performed; }

For example:

function greeting()
      { echo "Hello user!" ; }

The function can be called from within a script as follows:

<?php
   greeting();
?>

This would display as “Hello user!”

include( ) vs. require( )

Both functions pull a file into an HTML page. The difference is that if include() fails to retrieve the file, the script will display an error message and continue to run; if require() encounters the same problem, it will stop the script. Use include() for including most files, but userequire() for vital items, such as accessing the database connection file. If the connection fails, it is pointless to continue.

if, else, and elseif

A series of PHP conditional statements can take the following pattern:

if something is true
Do this
elseif something else is true
Do that
else
Do something different from the previous two instructions.

You can use as many elseif statements as you like, but only one else is permitted and it must be the last item in the list of conditionals.

When students look at my code for a registration page, they ask why several else clauses appear one after another when there should be only one. Some code that prompts the question is as follows:

if (empty($errors)){ // If no problems occurred in the user's input
   //Determine whether the email address has already been registered for a user
   $q = "SELECT user_id FROM users WHERE email = '$e' ";
   $result=mysqli_query ($dbcon, $q) ;
if (mysqli_num_rows($result) == 0){//The email address was not already registered image
therefore register the user in the users table
   // Make the query
   $q = "INSERT INTO users (user_id, title, fname, lname, email, psword, registration_date, image
    uname, class, addr1, addr2, city, county, pcode, phone, paid) VALUES (' ', '$title', image
   '$fn', '$ln', '$e', SHA1('$p'), NOW(), '$uname','$class', '$ad1', '$ad2', '$cty', image
   '$cnty', '$pcode', '$ph', '$pd')";
   $result = @mysqli_query ($dbcon, $q); // Run the query
if ($result){ // If the query ran without a problem
   header ("location: register-thanks.php");
   exit();
} else {// If the query failed to run
// Error message
   echo '<h2>System Error</h2>
<p class="error">You could not be registered due to a system error. We apologize for image
the inconvenience.</p>';
// Debugging message
   echo '<p>' . mysqli_error($dbcon) . '<br><br>Query: ' . $q . '</p>';
} // End of if ($result)
   mysqli_close($dbcon); // Close the database connection.
// Include the footer and stop the script
   include ('includes/footer.php');
   exit();
}else{//The email address is already registered
   echo '<p class="error">The email address is not acceptable because it is image
already registered</p>';
   }
}else{// Display the errors

Explanation of the Code

The ifs and elses are shown in bold type There are three ifs and three elses. The three elses appear to be following each other, but in fact the ifs and elses are nested; they are each complete in themselves, as you will see from the formatted summary that follows:

if (empty($errors)){ //If no problems occur in the user's input, run the query
      if (mysqli_num_rows($result) == 0){ //The email address is not already registered, image
          so continue to run the query
         if ($result){ //If the query ran without a problem, continue to run the script
         }else{//If the query fails to run, display an error message
      }else{//The email address is already registered, display that information to the user
}else{ //If errors are detected, display the errors

Loops

loop is a device that searches through an array or a file item by item. It functions by executing a block of code as long as a condition is true.

The while Loop

The while loop is used when the number of items that might be retrieved is unknown. The format for a while loop is:

while (condition is true)
{
do something
}

We used while loops in pages that retrieved the results of search queries. The code looped through the data in a database table and displayed records if they existed. This use of the while loop was as follows:

// Fetch and print all the records
while($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
   echo '<tr>...

While records were found, the rows were retrieved and displayed in a table.

The for Loop

The for loop and the foreach loop are used when the number of items is known. The for loop has the following format:

for (start value, last value, expression) {
do something
}

The for loop used in the next example is restricted to a known number of iterations (in this case, 3):

<!doctype html>
<html lang=en>
<body>
<?php
for($x=0; $x<=3; $x++)
{
echo "Iteration: $x<br>";
}
?>
</body>
</html>

The display would be:

Iteration: 1

Iteration: 2

Iteration: 3

The foreach Loop

This loop is used with arrays with a known number of elements. If an array holds the three primary colors, you know there are three items; therefore, use foreach. The foreach loop has the following format:

foreach ($array as $value)
{
code to be executed
}

Take the example of an array holding the three primary colors:

<!doctype html>
<html lang=en>
<body>
<?php
$primaries = array("red","yellow","blue");
foreach ($primaries as $value) {
echo "value <br>";
}
?>
</body>
</html>

The display would be as follows:

red

yellow

blue

foreach is used in the next snippet of code, which was extracted from the registration pages in this book. Because the loop followed some code that detected a number of error messages (or no messages) in the $errors array, the number of messages is known to be either zero or a known amount.

} else { // Display the errors
   echo '<h2>Error!</h2>
   <p class="error">The following error(s) occurred:<br>';
   foreach ($errors as $msg) { // Display each error
     echo " - $msg<br>\n";
   }
     echo '</p><h3>Please try again.</h3><p><br></p>';
   }

The do while Loop

The do while loop executes the piece of code once, and then it will check the result. If the result is not equal to a predetermined amount, it will continue to loop until the result is equal to the predetermined amount. The do and the while are separated by the code that executes some task, as follows:

An initial variable;
do
{code to be executed;
}
while (condition is true);
 
body text first
          <?php
          $x=1;
          do
          (
          echo "Number: $x <br>";
          }
          while ($x<=3)
          ?>

The display would be:

Number: 1

Number: 2

Number: 3

Numbers

Here are some examples of valid numbers for use in PHP scripts:

Valid integers: 4 and –4

Valid floating point numbers: 4.0 or –4.0 or 40.44

Invalid numbers: ¾ or 3a or 04.01.14

The operators for numbers are: add +, subtract –, multiply *, divide /

Here’s an example:

<?php
  $price = 100;
  $sales_tax = 0.2;
  $total_price = $price + ($price * $sales_tax);
  echo $total_price;
?>

The total price displayed would be 120.

Quotation Marks

Items enclosed within single quotes are treated literally. Items within double quotes are replaced by their values, as shown in the following example:

<?php
$fname = 'Adrian';
   echo 'Single quotes will display $fname. ';
   echo "Double quotes will display $fname";
?>

The display would be:

Single quotes will display $fname. Double quotes will display Adrian

Note that numbers do not require quotes.

Sessions

The period of uninterrupted time that a user spends viewing a web site is a session. By using a PHP built-in array named $_SESSION, a user’s data can be stored in a session as she moves from page to page. This is achieved by assigning the user’s data to a session as follows:

if (isset($_POST['id'])
{
$id = $_POST['id'];
}
session_start()
$_SESSION['id'] = $id
do some action

The function session_start() must appear on every page where a session will be used. The function will then either start a session or access an existing session. The function must appear in the page code before anything is sent to the browser. It will not tolerate even a preceding space or empty line.

Logging In with a Session

We have used sessions in most chapters, and the login pages provide a typical example, as shown in the following snippet:

<?php
// Check if the login form on the login page has been submitted
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
   require ('mysqli_connect.php'); //connect to database
//Insert your email validation code here and assign email alias as $e
// Insert your password validate code here and assign password alias as $p
if ($e && $p){//if no problems were encountered
// Fetch the user_id, first_name and user_level for that email/password combination:
$q = "SELECT user_id, fname, user_level FROM users WHERE (email='$e' AND psword=SHA1('$p'))";
   $result = mysqli_query ($dbcon, $q);
// Was there a record that matched the email/password combination
if (@mysqli_num_rows($result) == 1) {//if a database record matched the user's input
// Fetch the record and set the session data
   session_start();                                                                      #1
   $_SESSION = mysqli_fetch_array ($result, MYSQLI_ASSOC);
$_SESSION['user_level'] = (int) $_SESSION['user_level']; // Ensure user level is an integer
// Use a ternary operation to set the URL                                                #2
$url = ($_SESSION['user_level'] === 1) ? 'admin-page.php' : 'members-page.php';
header('Location: ' . $url); // Make the browser load either the members' or the admin page
exit(); // Stop the script.
   mysqli_free_result($result);
   mysqli_close($dbcon);
   } else { // No match was made
echo '<p class="error">The email address and password entered do not match our records.</p>'
   }
   } else { // If there was a system problem
   echo '<p class="error">Please try again.</p>';
   }
   mysqli_close($dbcon);
   } // End of submit conditional
?>
<!-- Display the form fields-->                                                          #3
<div id="loginfields">
<?php include ('login_page.inc.php'); ?>
</div

Note that the session_start() function (line #1) is not preceded by anything that is sent to the browser. It is followed by code that takes the data from the found record and assigns the data to the session. A ternary operator (line #2) then uses the data stored in the session to make the browser load either the members’ or the admin page. After the PHP code is processed, the code finally sends some information to the browser (line #3).

Logging Out Destroys a Session

Sessions are located in the memory of the server for security; closing the browser will end the session. However, if the user wishes to log out and then browse the web site’s public pages, for security she can log out and the code in the logout page shown next will destroy the session.

<?php
session_start();//access the current session
// If no session id variable exists, redirect the user
if (!isset($_SESSION['user_id'])) {
header("location:index.php");
exit();
}else{ //Destroy the session
   $_SESSION = array(); // Destroy the variables stored in the session
   session_destroy();   // Destroy the session itself
   setcookie (session_name(), '', time()-3600);
   setcookie('PHPSESSID', time()-3600,'/', 0, 0);//Destroy the cookie
header("location:index.php");
exit();
}

Ternary Operator

The ternary operator is a very concise way of setting a conditional. The ternary operation uses the symbols ? and the colon : The example is taken from Chapter 3 of this book.

// Use a ternary operation to set a page URL
$url = ($_SESSION['user_level'] === 1) ? 'admin-page.php' : 'members-page.php';
header('Location: ' . $url); // Make the browser load either the members’ orimage
the admin page
exit(); // Stop the script

The first part (enclosed in brackets) takes the user_level in the session array and asks if it is identical to 1. The three equal signs mean identical to. The item after the question mark is stating that if the user_level is identical to 1, then assign the admin-page.php to the variable named $url. The colon is the equivalent of else; therefore, if user_level is not identical to 1, $url is set so that it directs the user to the members-page.php. (Registered members have a user_level of 0.) The variable $url, therefore, is set to a particular page, and the user is redirected to that page using the header() function.

header('Location: ' . $url); // Make the browser load either the members' or the admin page
exit(); // Quit the script

The long-hand equivalent of the preceding ternary statement is

if ($_SESSION['user_level'] === 1) {
header('location: admin-page.php');
exit();
}else{
header('location: members-page.php');
exit();
}

Validation and Sanitization Filters

The following script validates an e-mail address using the filter_var() function:

//If the email address is present, trim it
   if (isset($_POST['email'])) {
   $etrim = trim($_POST['email']);
//Validate the trimmed address
   $validated_etrim = (filter_var($etrim, FILTER_VALIDATE_EMAIL));
   $e = mysqli_real_escape_string($dbcon, $validated_etrim);
   }else{
$errors[] = 'Your email address is invalid or you forgot to enter your email address.';
}

Malicious user input can be sanitized by means of the filter_var function. If a user inputs script into a registration form variable named $last_name, any HTML or JavaScript tags can be removed as follows:

$last_name ='<script>alert('some_alert');</script>';
echo filter_var($last_name, FILTER_SANITIZE_STRING);

The <script></script> tags will be removed, leaving a harmless string as follows:

$sanitized_input = alert('some_alert');

Resources listing the filter_var functions are given later in this Appendix.

Variables

Variables store values and can be accessed only on the page on which they are created. If you click a link to switch to another page, the next page knows nothing about that variable. However, there are ways of passing the variable’s value to another page. Variables begin with a dollar sign ($). Following the dollar sign, the variable’s name can be text (uppercase or lowercase), hyphens, or underscores. The name can include numbers but must not start with a number.

Example:$first_name

Variables are case sensitive, $Firstname is not the same as $firstname.

Variables: Predefined (aka Built-in Variables or Global Variables)

You have used PHP predefined variables in most of the chapters. They allowed us to transfer data from a form to a handler, or from one HTML page to another. Predefined variables always begin with a dollar sign and an underscore, as shown in the following four examples:

$_SERVER,    $_POST['fname']   $_GET(fname},   $_SESSION['fname'],

In our tutorials, the predefined variables $_POST['fname' were assigned to shorter variables like this:

$fname = $_POST['fname']

Variables: String

String variables are groups of characters enclosed in single or double quotes—for example:

$my_pet = 'cat';   $animal = "dog";   $birthday = 'March 10th, 1952';

If the string contains an apostrophe, it must be escaped—for example: $last_name = "O\'Brien "

MySQL and phpMyAdmin Quick Reference

INSERT

When using the INSERT query to insert data into a table, the query has two parts: the column names and the VALUES, as shown in the following example:

$q = "INSERT INTO users (user_id, title, fname, lname, email, psword, registration_date) image
VALUES (' ', '$title', '$fn', '$ln', '$e', SHA1('$p'), NOW())";

The number and order of the column names must exactly match number and order of the values.

SELECT

The elements of a SELECT query must be in the following order:

SELECT (column or expression) AS (set an alias) FROM (table) WHERE (condition) ORDER BY (column)

AS and ORDER BY are optional and can be omitted. ORDER BY can be followed by the keywords ASC or DESC to specify how the selected items are to be ordered. The number of records selected can be specified by putting LIMIT and an integer at the end of the query.

UPDATE

Let’s say Rose Bush has a new e-mail address. Use the UPDATE query to change it as follows:

$q = UPDATE users SET email ='rbush@mynewisp.co.uk' WHERE user_id = 15 LIMIT 1

Storage Engines and phpMyAdmin

Before creating a table, you need to decide whether you will require a full text search facility for searching through text in a database table. A user might wish to search for a particular topic. For example, he or she might search for the words “Mark Twain” to view a list of quotations by Mark Twain. If you need this facility, choose the MyISAM storage engine for your tables. However, if you have MySQL version 5.6.4 or later, the INNODB storage engine allows full text searches. For the latest information, see the MySQL web site:

http://dev.mysql.com/doc/refman/5.6/en/fulltext-search.html

Unfortunately, at the time of writing, the new version of MySQL was not available in the XAMPP download version 1.8.2. However, it is included in XAMPP version 1.8.3.

In phpMyAdmin, you can choose the type of storage engine. On the screen for creating the columns, a pull-down menu allows you to select the storage engine. This is shown circled in Figure App-1.

image

Figure App-1. Selecting a storage engine for a table

Changing the Storage Engine on an Existing Populated Table

If you wish to change an existing table’s storage engine from INNODB to MyISAM, or vice versa, this is quite easily accomplished in phpMyAdmin as long as you have not changed collations or decreased the column size. As a precaution, before changing the engine, always back up your table using the phpMyAdmin Export facility. After changing the engine, check that all is well with the web site and then back up the table again.

The items referred to in the steps that follow are shown circled in Figure App-2.

image

Figure App-2. Changing the type of storage engine

1.    In phpMyAdmin, click the name of your database in the left panel.

2.    In the left panel, click the table you wish to change.

3.    Click the Operations tab.

4.    Use the storage engine’s pull-down menu to select the engine.

5.    Click Go.

What Next?

I hope the simplified approach in this book has inspired you to explore more advanced PHP techniques for developing databases. For increased security, you will need to learn about prepared statements and transactions. Prepared statements are analogous to include statements. The variable content of a query is taken out of the main code, and that content is the prepared statement (named stmt). The content is then pulled into the query by means of a bind statement. Separating the components of a query is a strong security measure.

Transactions ensure that items such as orders are truly completed before inserting them into the database table. Transactions allow the user to roll back to amend the order details or even cancel the order.

You might wish to examine the merits of procedural PHP vs. Object Oriented PHP (OOP); both will produce the same outcome, but OOP can be advantageous for maintaining very large web sites. This book used procedural PHP throughout. OO P is a recent addition to PHP and will be more familiar to programmers who are acquainted with Perl or C++.

JavaScript, Ajax, and jQuery can add enhancements to a database-driven web site. Help on these topics is provided in the resources listed next.

Use the resources to keep abreast of improvements and modifications in PHP and MYSQL. Most importantly, watch for any new developments for improving security.

Because arrays and functions are central to PHP database design, try to learn more about them.

Now that you are familiar with the terminology used for MySQL databases and PHP, you will be able to benefit from the available books and online resources. The following resources will help you to move on from the basic techniques described in this book.

Resources for PHP and MySQL

Before buying a book on PHP and MySQL, be sure to read the introduction on the book’s web page. If possible, borrow a copy before committing to a purchase. You might find that the book is far too advanced or that it covers what you already learned.

To use these resources, you will need to learn how to use the MySQL client command line; however, you should now be able to adapt the commands so that they can be used with the SQL tab in phpMyAdmin. Here are the books I recommend (My opinion only, check the reviews on Amazon for other opinions):

·     PHP and MySQL for Dynamic Web Sites (4 th Edition) by Larry Ullman (Peachpit Press, 2012). ISBN-13:978-0-321-784-07-0. Larry Ullman’s book is an excellent choice to help you expand on what you have now learned. The code is available for downloading, and the book has a first-class, friendly, online forum to help you with any problems. The book also contains a useful section on how to activate an account so that when users register, an e-mail containing a link is sent to them so that their e-mail address can be verified before they are allowed to log in. The book includes information on JQuery, JavaScript and Ajax.

·     PHP 6 and MySQL 5 for Dynamic Web Sites by Larry Ullman (Peachpit Press, 2008). Visual QuickStart Guide. ISBN-13:978-0-321-52599-4. This book is a little out of date in a few minor instances and it may be out of print but still available from some sources. It is partly a sequel to the first book in this list. The first few chapters overlap the previous book but the practical examples are different and more advanced. Although PHP 6 has yet to be released, the various new versions of PHP 5 adopt many of the proposed PHP 6 features.

·     PHP and MySQL Web Development (4 th Edition) by Luke Welling and Laura Thomson (Pearson Education, Inc., 2009). ISBN-13:978-0-672-32916-6. The book has a CD containing all the code.

·     PHP for the Web (3 rd edition) by Larry Ullman (Peachpit Press, 2009). Visual QuickStart Guide. ISBN-13:978-0-321-44249-9. This book is also a little out of date in a few minor instances, but otherwise it’s an excellent PHP resource. It is very practical and easy to follow. I frequently refer to it.

HTML and PHP Editing Software

Dreamweaver CC is the most comprehensive WYSIWYG editor. It is now part of Adobe’s Creative Cloud package that you can pay for monthly as and when you need it. See http://www.adobe.com.

I have always used the full-featured WYSIWYG tool Microsoft Expression Web. Now Microsoft has discontinued it (incorporating the features into Visual Studio), but the good news is that Microsoft now provides the last version, Expression Web 4, as a free download, which you can download at http://www.microsoft.com/en-us/download/details.aspx?id=36179.

The free Notepad++ version 6.5.1 is an extremely useful non-WYSIWYG text editor that supports several programming languages. It is available from http://notepad-plus-plus.org.

PHP and MySQL Internet Resources

Here are some online resources you can refer to for further guidance:

·     http://www.htmlite.com/: This site is great for practical PHP scripts and MySQL.

·     If you own a book by Larry Ullman, be sure to try his superb forum at http://larryullman.com/forums.

·     http://www.phpbuilder.com: This site has many PHP tutorials and a forum.

·     http://www.homeandlearn.co.uk/php/php.html: This site contains PHP for beginners with some good example scripts.

·     http://www.w3schools.com/php/: Here you’ll find a good selection of PHP scripts.

·     http://www.zend.com: This site offers tutorials and a forum from the brains behind the PHP core.

·     http://www.php.net: Keep up to date by visiting this site, which was the original PHP web site.

·     http://net.tutsplus.com/tutorials/php/getting-clean-with-php/: This site has good examples of the use of filter_var() for validating and sanitizing user input.

Resource for Creating a Forum

Try the following web site for a tutorials on creating a forum:

http://net.tutsplus.com/tutorials/php/how-to-create-a-phpmysql-powered-forum-from-image
scratch/?search_index=36

E-Commerce Resources

The first two book resources previously listed contain some information on e-commerce web sites. The CD provided with the book by Luke Welling and Laura Thomson has a good example of a custom shopping cart.

For resources dealing specifically with e-commerce, try the following:

·     Effortless E-Commerce with PHP and MySQL by Larry Ullman (New Riders). ISBN-13: 978-0-321-65622-3. At the time of this writing, Larry Ullman was working on a second edition of his manual.

Online Tutorials

One online tutorial gives instructions using 20 videos averaging 15 minutes each. View this at http://www.youtube.com/playlist?list=PL442E340A42191003.

Of course, you won’t be able to create an e-commerce web site by viewing videos, you would also need a great deal of documentation so that you can study the code and adapt it. However, the videos give an excellent outline of the enormous amount of work that would be required to create a fully operational e-commerce web site.

A good tutorial for an e-commerce database with downloadable files can be found at: http://www.webassist.com/community/tutorials/view_tutorial.php?tid=101.

Integrating PayPal with a Custom Shopping Cart

Check out the following web sites for information related to custom shopping carts:

https://www.paypal.com/us/cgi-bin/webscr?cmd=_shoppingcart-intro-outside
https://www.paypal.com/cgi-bin/webscr?cmd=p/xcl/rec/sc-techview_outside
https://www.paypal.com/cgi-bin/webscr?cmd=_pdn_howto_checkout_outside
https://developer.paypal.com/webapps/developer/docs/classic/paypal-payments-image
standard/integration-guide/cart_upload/

The third web site in the preceding list has some useful coded examples. The fourth web site has extra information and some helpful screen shots.

PayPal Forums

For the USA, check out the following web site: https://www.paypal-community.com/t5/US-PayPal-Community/ct-p/US. For the UK, check out the following web site: https://www.paypal-community.com/t5/UK-Community/ct-p/UK.

Third-Party Shopping Carts

Third-party shopping carts are available from the following resources:

·     Click Cart: I have seen very good reports of Click Cart Pro software. Apparently, it makes easy work of integrating payment systems into a web site. It supports the world’s most popular payment systems, including PayPal, Authorize.net, and Sage Pay. The cost at the time of writing was $199, and upgrades are $99. As e-commerce database web sites can be developed only by firms with deep pockets, the price is small compared to the annual budgets of most companies. For more details visit the following web site:http://www.kryptronic.com/.

·     Stripe: This is the latest payment gateway for PHP-based web sites. Charges are low for successful transactions, and it operates by means of users’ credit/debit cards. Your web-site development team needs to have a good knowledge of JavaScript because the gateway depends on the application of JavaScript and jQuery. For more information visit https://stripe.com. For the U.K version, visit https://stripe.com/gb.

·     Authorize.net: This is a USA and Canadian payment gateway that accepts credit/debit cards. It requires a setup fee of $99 and $20 monthly payments. Details can be found at http://www.authorize.net.

Summary

The Appendix provided an alphabetical list of the main PHP code required for creating interactive web sites and databases. This was followed by a brief reference for MySQL and phpMyAdmin. The question “What next?” was posed, and some suggestions offered. To help you to progress beyond the basic instruction given in this book, a list of resources was provided.