The Administrative Side


The first script I'll write will be for the purpose of adding products (specifically a print) to the database. The page will allow the administrator to select the artist by name or enter a new one, upload an image, and enter the details for the print (Figure 14.7). The image will be stored on the server, and the print's record inserted into the database. But since thisand pretty much every script in this chapterwill require a connection to the MySQL database, I'll write a connection script first.

Figure 14.7. The HTML form for adding prints to the catalog.


As I stated in the introduction to this chapter, I'll be using the Improved MySQL Extension functions, first demonstrated in Chapter 11. These functions require that you have

Security

With respect to an e-commerce site, there are three broad security considerations. The first is how the data is stored on the server. You need to protect the MySQL database itself (by setting appropriate access permissions) and the directory where session information is stored (see Chapter 9, "Cookies and Sessions," for what setting must be changed).

The second security consideration has to do with protecting access to sensitive information. The administrative side of the site, which would have the ability to view orders and customer records, must be safeguarded to the highest level.

The third factor is protecting the data during transition. By the time the customer gets to the checkout process (where credit card and shipping information comes in), secure transactions must be used. To do so entails establishing a Secure Sockets Layer (SSL) on your server with a valid certificate and then changing to an https:// URL. Also be aware of what information is being sent via e-mail, since those messages are frequently not transmitted through secure avenues.


  • PHP 5 or greater

  • MySQL 4.1.3 or greater

  • Improved MySQL Extension support enabled in PHP

In case you don't meet all of these criteria or if you would just prefer to use the standard MySQL functions, I'll include the alternative code in these first two examples. You'll see it commented out in the scripts, but it won't be present in the step-by-step sequences. You can also always refer back to the examples in Chapter 7, "Using PHP with MySQL," for the proper syntax (or use the PHP manual, of course).

To keep a complicated process more simple, none of the examples in this chapter will use the kind of error management techniques you would want on a live site. When you're ready to make an actual e-commerce application, incorporate the error management ideas discussed elsewhere in the book (like that developed in Chapter 13, "ExampleUser Registration").

To create mysql_connect.php

1.

Create a new PHP document (Script 14.1).

 <?php # Script 14.1 - mysql_connect.  php 

Script 14.1. The mysql_connect.php script connects to the database, using the Improved MySQL Extension functions, and defines a function for handling data.


2.

Define the database connection constants.

 define ('DB_USER', 'username'); define ('DB_PASSWORD', 'password'); define ('DB_HOST', 'localhost'); define ('DB_NAME', 'ecommerce'); 

Naturally you will need to use a username/password/hostname combination that has access to your MySQL database.

3.

Connect to MySQL and select the database.

 $dbc = mysqli_connect (DB_HOST,  DB_USER, DB_PASSWORD, DB_NAME) OR  die ('Could not connect to MySQL:  ' . mysqli_connect_error() ); 

Although you may want to use more advanced error-management techniques, for the sake of brevity and development, I'll use the die() function if a connection error occurs.

Again, this code uses the mysqli_* functions. See the commented-out code in the script to see how the standard mysql_* functions connect to MySQL and select the database.

4.

Define the escape_data() function and complete the PHP page.

 function escape_data ($data) {   if (ini_get('magic_quotes_gpc')) {      $data = stripslashes($data);   }   global $dbc;   $data = mysqli_real_escape_string    ($dbc, trim($data));   return $data; } 

This function is defined much as it has been in the past. The function takes a string of data as its lone argument. It then checks to see if Magic Quotes is enabled. If so, the slashes are stripped from the data to avoid over-escaping the string. Next, the database connection is made available via the global statement and the string is run through the mysqli_real_escape_string() function. Finally, the processed string is returned by the function.

5.

Complete the PHP script and upload to your Web server (outside of the Web document root).

 ?> 

The structure for this site will be exactly like that in the previous two examples, keeping security in mind aXs much as possible. For a visual representation of the layout, see Figure 14.8.

Figure 14.8. The site structure for this Web application. The MySQL connection script and the uploads directory (where images will be stored) are not within the Web directory (they aren't available via http://).


To create add_print.php

1.

Create a new PHP document, beginning with the HTML head (Script 14.2).

 <!DOCTYPE html PUBLIC "-//W3C//DTD  XHTML 1.0 Transitional//EN "http://www.w3.org/TR/xhtml1/DTD/  xhtml1-transitional.dtd> <html xmlns="http://www.w3.org/1999/  xhtml xml:lang="en" lang="en"> <head>   <meta http-equiv="content-type"    content="text/html; charset=    iso-8859-1 />   <title>Add a Print</title> </head> <body> <?php # Script 14.2 - add_print.php 

Script 14.2. This administration page adds products to the database. It handles a file upload, inserts the new print into the prints table, and even allows for a new artist to be submitted.


Normally, I would create a template system for the administrative side, but since I'll be writing only this one administrative script in this chapter, I'll do without.

2.

Include the database connection script and check if the form has been submitted.

 require_once ('../../mysql_connect.  php); if (isset($_POST['submitted'])) { 

The administration folder will be located inside of the main (html) folder and is therefore two directories above the connection script. Keep your directory structure (Figure 14.8) in mind when including files.

3.

Validate the print's name.

 if (!empty($_POST['print_name'])) {   $pn = escape_data($_POST['print_    name]); } else {   $pn = FALSE;   echo '<p><font color="red">    Please enter the print\'s name!    </font></p>'; } 

This is one of the required fields in the prints table and should be checked for a value. I could also choose to use regular expressions here, but I'm assuming that the site's administrator will not want to undermine the integrity of the application. If no value is entered, an error message is printed (Figure 14.9).

Figure 14.9. If the print's name is not submitted, the record will not be added to the database.


4.

Handle the image file, if one was selected.

 if (is_uploaded_file ($_ FILES['image']['tmp_name'])) {   if (move_uploaded_file($_FILES    ['image]['tmp_name'], "../../    uploads/{$_FILES['image]    ['name]}")) {     echo '<p>The file has been      uploaded!</p>';   } else {     echo '<p><font color="red">      The file could not be moved.      </font></p>';     $i = FALSE;   }   $i = $_FILES['image']['name']; } else {   $i = FALSE; } 

When I demonstrated the techniques for handling file uploads with PHP (in Chapter 11), I mentioned the is_uploaded_file() function. It returns trUE if a file was uploaded and FALSE if not. If a file was uploaded, the script will attempt to move the file over to the uploads directory. Messages are printed (Figure 14.10) indicating its success in doing so.

Figure 14.10. The result if a file was selected for the print's image and it was successfully uploaded.


Finally, the $i variable will be set to either the name of the file or an empty string.

This is one area of the script that could be easily improved. You could do what I did in Chapter 12, "ExampleContent Management," and rename the print using the print's ID from the database. You could also validate that the image is of the right size and type. To keep an already busy script more manageable, I'm assuming that the administrator will use this page properly.

5.

Validate the size, price, and description inputs.

 if (!empty($_POST['size'])) {   $s = escape_data($_POST['size']); } else {   $s = '<i>Size information not    available.</i>'; } if (is_numeric($_POST['price'])) {   $p = (float) $_POST['price']; } else {   $p = FALSE;   echo '<p><font color="red">    Please enter the print\'s price!    </font></p>'; } if (!empty($_POST['description'])) {   $d = escape_data($_POST    ['description]); } else {   $d = '<i>No description available.    </i>'; } 

The size and description values are optional, but the price is not. As a basic validity test, I ensure that the submitted price is a number (it should be a decimal) using the is_numeric() function. If the value is numeric, I type-cast it as a floating-point number just to be safe. An error message will be printed if no price or an invalid price is entered (Figure 14.11).

Figure 14.11. The print's price is checked for an appropriate value and type.


If the size and description inputs are not used, I'll set the $s and $d variables to default messages. These default messages will then be displayed on the public side.

6.

Check if a new artist is being entered.

 if ($_POST['artist'] == 'new') {   $query = 'INSERT INTO artists    (first_name, middle_name,    last_name) VALUES ('; 

To enter the print's artist, the administrator will have two choices (Figure 14.12): select an existing artist (from the records in the artists table) using a pull-down menu or enter the name of a new artist. If a new artist is being entered, the record will have to be inserted into the artists table before the print is added to the prints table. Here, I have begun the appropriate query for adding an artist.

Figure 14.12. The administrator can select an existing artist from the database or choose to submit a new one.


7.

Finish assembling the query.

 if (!empty($_POST['first_name'])) {   $query .= "'" . escape_data    ($_POST['first_name]) . "', "; } else {   $query .= 'NULL, '; } if (!empty($_POST['middle_name'])) {   $query .= "'" . escape_data    ($_POST['middle_name]) . "', "; } else {   $query .= 'NULL, '; } if (!empty($_POST['last_name'])) {   $query .= "'" . escape_data    ($_POST['last_name]) . "')";   $result = mysqli_query    ($dbc, $query);   $a = mysqli_insert_id($dbc); } else {   $a = FALSE;   echo '<p><font color="red">    Please enter the artist\'s name!    </font></p>'; } 

The artist's first and middle names are optional fields, whereas the last name is not (since there are artists referred to by only one name). Depending upon whether the inputs have a value, either the first and middle names will be added to the query or NULL will be. The final query created by this process will be like INSERT...VALUES (NULL, NULL, 'Christo') or INSERT...VALUES ('John', 'Singer', 'Sargeant'). Because the last name is a required field, an error message is printed if it's omitted for a new artist record (Figure 14.13).

Figure 14.13. If a new artist is being used, the artist's last name must be entered, at the least.


If the new artist was added to the database, the artist's ID will be retrieved (for use in the print's INSERT query) using the mysqli_insert_id() function.

8.

Complete the artist conditional.

 } elseif ( ($_POST['artist']  == 'existing) && ($_POST  ['existing] > 0)) {   $a = (int) $_POST['existing']; } else {   $a = FALSE;   echo '<p><font color="red">    Please enter or select the    print\'s artist!</font></p>'; } 

If the administrator opted to use an existing artist, then a check is made that an artist was selected from the pull-down menu. If this condition failed, then an error message is printed (Figure 14.14).

Figure 14.14. If no artist is entered or selected, an error message is printed.


9.

Insert the record into the database.

 if ($pn && $p && $a && $i) {   $query = "INSERT INTO prints    (artist_id, print_name, price,    size, description, image_name)    VALUES ($a, '$pn, $p, '$s',    '$d, '$i')";   if ($result = mysqli_query    ($dbc, $query)) {      echo '<p>The print has been       added.</p>';   } else {     echo '<p><font color="red">      Your submission could not be      processed due to a system      error.</font></p>';   } 

If the four required fields (print_name, price, artist_id, and image_name) have proper values, the print will be added to the database. Messages will be sent to the Web browser indicating the success of running the query (Figure 14.15).

Figure 14.15. The result of a print being added to the catalog.


If you are using the older MySQL functions, you'll need to change the code accordingly. And if you encounter MySQL errors, use the standard debugging methods: printing out the query, using mysqli_error() or mysql_error(), and so on.

10.

Complete the conditionals.

   } else {      echo '<p><font color="red">       Please click "back and try       again.</font></p>';   } } else { ?> 

The first else statement applies when one of the four validation tests fails. The second else will be used to display the form if it has not been submitted.

11.

Begin creating the HTML form.

 <form enctype="multipart/  form-data action="add_print.php"  method="post>   <input type="hidden" name=    "MAX_FILE_SIZE value="524288" />   <fieldset><legend>Fill out the    form to add a print to the    catalog:</legend>   <p><b>Print Name:</b> <input    type="text name="print_name"    size="30 maxlength="60" /></p>   <p><b>Image:</b> <input    type="file name="image" />    <small>The file name should not    include spaces or other invalid    characters and should have a    file extension.</small></p> 

Because this form will allow a user to upload a file, I must include the enctype in the form tag and the MAX_FILE_SIZE hidden input.

12.

Create the artist pull-down menu.

 <p><b>Artist:</b> <p><input type="radio"  name="artist value="existing"  /> Existing => <select name="existing"><option>  Select One</option> <?php $query = "SELECT artist_id,  CONCAT_WS(' ', first_name,  middle_name, last_name) AS name  FROM artists ORDER BY last_name,  first_name ASC; $result = mysqli_query  ($dbc, $query); while ($row = mysqli_fetch_array  ($result, MYSQLI_ASSOC)) {   echo "<option value=\"{$row    ['artist_id]}\">{$row    ['name]}</option>\n"; } mysqli_close($dbc); ?> </select></p> 

The artist pull-down menu will be dynamically generated (Figure 14.16) from the records stored in the artists table using this PHP code. It's prefaced by a radio button so that the administrator can select an existing artist or enter a new one (see Step 13). The MySQL CONCAT_WS() functionshort for concatenate with separatoris used to retrieve the artist's entire name as one value. If you are confused by the query's syntax, run it in the mysql client or other interface to see the results.

Figure 14.16. The PHP-generated HTML source code for the artists portion of the form.


13.

Create the inputs for adding a new artist.

 <p> <input type="radio" name="artist"  value="new /> New => First Name: <input type="text"  name="first_name size="10"  maxlength="20 /> Middle Name: <input type="text"  name="middle_name size="10"  maxlength="20 /> Last Name: <input type="text"  name="last_name size="10" ]  maxlength="30 /> </p> 

Rather than create a separate form for adding artists to the database, the administrator will have the option of doing so directly here. The PHP code that handles the form (described earlier) will create a new database record using the new artist information.

14.

Complete the HTML form.

 <p><b>Price:</b> <input  type="text name="price"  size="10 maxlength="10" />  <small>Do not include the dollar  sign or commas.</small></p> <p><b>Size:</b> <input  type="text name="size" size="30"  maxlength="60 /></p> <p><b>Description:</b> <textarea  name="description cols="40"  rows="5></textarea></p> </fieldset> <div align="center"><input  type="submit name="submit"  value="Submit /></div> <input type="hidden" name=  "submitted value="TRUE" /> </form> 

15.

Complete the PHP conditional and the HTML page.

 <?php } ?> </body> </html> 

This last bit of PHP codethe curly bracecompletes the else part of the conditional (that displays the form if it hasn't been submitted).

16.

Save the file as add_print.php.

17.

Create the necessary directories on your server.

This administrative page will require the creation of two new directories. One, which I'll call 4dm1n (see Figure 14.8), will house the administrative files themselves. The second, uploads, should be placed below the Web document directory and have its privileges changed so that PHP can move files into it. See Chapter 11 for more information on this.

18.

Upload add_print.php to your Web server (into the administration folder) and test in your Web browser (Figures 14.17 and 14.18).

Figure 14.17. Here I'm adding a print using an existing artist.


Figure 14.18. In this example, I'm adding a print for a new artist.


Tips

  • This is actually the most complicated script in this entire chapter. The complexity arises from the artists option (use an existing one or add a new one). To simplify this aspect of the application, you could create one form for adding artists to the database and a separate one for adding prints (the separate add_print.php page would therefore only allow the selection of an existing artist).

  • Although I did not do so here for the sake of brevity, I would recommend that separate MySQL users be created for the administrative and the public sides. The admin user would need SELECT, INSERT, UPDATE, and DELETE privileges, while the public one would need only SELECT and INSERT.

  • The administrative pages should be protected in the most secure way possible. This could entail HTTP authentication using Apache, a login system using sessions or cookies, or even placing the admin pages on another, possibly offline, server (so the site could be remotely managed from just one location).




    PHP and MySQL for Dynamic Web Sites. Visual QuickPro Guide
    PHP and MySQL for Dynamic Web Sites: Visual QuickPro Guide (2nd Edition)
    ISBN: 0321336577
    EAN: 2147483647
    Year: 2005
    Pages: 166
    Authors: Larry Ullman

    flylib.com © 2008-2017.
    If you may any questions please contact us: flylib@qtcs.net