Adding a New Artist to the Gallery admin_artist_insert.php The page for adding a new artist to the database, admin_artist_insert.php, is basically the same as the admin_artist_edit.php p
Trang 1Figure A.1 The admin_artlist.php page
Updating an Artist in the Gallery (admin_artist_edit.php)
To get to the admin_artist_edit.php page, the user clicked the hyperlink of an artist listed in the previous Figure A.1 Line 4 of Example A.1 shows that the hyperlink is sending the id for that artist via a URL The
admin_artist_edit.php page (Example A.2) uses the id to determine which artist to update (You can see the value of the id in the URL because the GET method is being used) The id for the artist is stored in a hidden field (see
Trang 2line 6 in Example A.2) If this is the first time the page is displayed, a SQL SELECT statement (see line 5) is executed to retrieve all the data for that artist from the database The user is presented with a self-processing HTML form containing the artist information, such as the name, e-mail address, phone, and so on, for the particular artist he or she selected for update Once the user has updated the information in the form, it is passed into the PHP portion of the page and extracted from the $_REQUEST superglobal array (see line 1), The variables resulting from the extract() function are used to
“SET” the new values for the artist in the SQL UPDATE command on line 3 (Be sure when you test this script that you update line 2 and provide the correct server, username, and password to connect to your version of MySQL.)
// Connect to the database and insert the new artist
3 $sql = "UPDATE Artist SET name='$name', "
"email='$email', phone='$phone', bio='$bio'"
5 $sql = "SELECT * from Artist WHERE id='$id'";
$resultset = mysql_query( $sql )or die(mysql_error());
$row = mysql_fetch_assoc( $resultset );
extract( $row ); // Retrieve/extract all info on artist by
ID
}
?>
<? include("admin_header.php") ?>
<h1>Artist Update Screen</h1>
<form action="<?=$_SERVER['PHP_SELF']?>" method="GET">
6 <input type="hidden" name="id" value="<?=$id?>">
<table>
<? if (isset($status)) {?>
<tr><td colspan="2"><b><?=$status?></b><br><br></td></tr> <? } ?>
Trang 4Adding a New Artist to the Gallery (admin_artist_insert.php)
The page for adding a new artist to the database, admin_artist_insert.php, is basically the same as the
admin_artist_edit.php page except that it performs a SQL INSERT statement (see line 1 in Example A.3) instead
of an UPDATE and does not require an ID to be passed into the page via a URL The user will enter the name of the new artist and all the requested information in a simple HTML form presented as a table (see line 5) An ID, primary key, will automatically be generated by the database for each new artist that is added (When testing this page, make sure to enter the correct information when connecting to the database; that is, host, username, and password are supplied for the mysql_connect() function on line 2.)
// Connect to the database and insert the new artist
1 $sql = "INSERT INTO Artist (name, email, phone, bio)" "VALUES ('$name', '$email', '$phone', '$bio')";
2 mysql_connect("localhost", "root", "password")
<h1>Artist Insert Screen</h1>
4 <form action="<?=$_SERVER['PHP_SELF']?>" method="GET">
5 <table>
<? if (isset($status)) {?>
<tr><td colspan="2"><b><?=$status?></b><br><br></td></tr> <? } ?>
Trang 6Adding and/or Editing a Piece of Art (admin_art_edit.php)
The page for adding a new art piece is slightly different from the pages previously shown where one page added a new artist and another page updated an existing artist The process of inserting and updating a new piece of art is handled on a single page A drop-down menu will present the user with a list of artists from which to choose The art is linked to the artist who owns it by the artist’s ID, id in the “Artist” table and a foreign key in the “Art” table, artist_id, a one-to-many relationship in which one artist can have multiple pieces of art The drop-down menu displays a list of artists by name and the value of the option is the artist’s ID (see Example A.4)
<option value="">Please Select</option>
<option value="10" >Todd Brown</option>
<option value="11" >stuART Sheldon</option>
<option value="12" >Elliott Easterling</option>
<option value="13" selected="SELECTED" >Laura Blair</option> </select></td>
</tr>
After selecting an artist from the drop-down list (line 5 in Example A.5), the page simply checks whether the art ID has been set If it has, the matching art record is selected for update (line 1) Otherwise, the script inserts a new record (line 2) into the database and the database determines the new ID
if( $title=="" ) { // Must provide an art title
$status = "Please enter the art title.<br>";
} else {
// Connect to the database and insert the new art
if( isset( $id) && $id!="" ) { // Update art for artist
1 $sql = "UPDATE Art SET title='$title', "
"price='$price',
description='$description',
image='$image', artist_id='$artist_id'"
"WHERE id='$id'";
} else { // Insert new art for artist
2 $sql = "INSERT INTO Art (title, price,
Trang 7<h1>Art Update Screen</h1>
4 <form action="<?=$_SERVER['PHP_SELF']?>" method="get">
<input type="hidden" name="id" value="<?=$id?>">
<table>
<? if (isset($status)) {?>
<tr><td colspan="2"><b><?=$status?></b><br><br></td></tr> <? } ?>
<tr><td>Title</td><td><input type="text" name="title"
6 $sql = "SELECT * FROM Artist";
$resultset = mysql_query( $sql )or die(mysql_error()); while( $artist = mysql_fetch_assoc( $resultset ) ) {
Trang 8id
Trang 9Figure A.4 The user selected the Title Dragonfly from the admin_art_list.php file for update (Note the id is
passed in the URL.)
A.3.3 Public Pages
The public pages are the pages a user can view without being required to log in The public pages for the Art Gallery are are index.php, artist_detail.php, and contact.php All these pages include header.php and
footer.php at the beginning and at the end of the page
The Header Page (header.php)
The header.php page is an HTML page included to provide the navigation menu, consisting of links to the other pages for the site (see Example A.6 and Figure A.5) Typically, the links to the administration section would not be included for security reasons, but we include them here for this demo Web site to make it easier to navigate between the private and public pages Session data verifies whether or not the user has successfully logged in, and if not, redirects him or her to a login page called admin_login.php, discussed in detail in Chapter 16, “Cookies and Sessions.”
Trang 10<link href="style.css" rel="stylesheet" type="text/css">
</head>
<body bgcolor="#FFFFFF" leftmargin="0" topmargin="0"
marginwidth="0" marginheight="0"
<table cellSpacing=0 cellPadding=0 align=center
border=0 borderColor="#CCCCCC" width="563"
Figure A.5 The header.php page
The Index Page (index.php)
The initial public page is index.php (see Figure A.6) This page will be opened by default when the user comes to the Canvas Gallery Web site The SQL SELECT statement (see line 1 in Example A.7) retrieves all the information for each artist by name, in sorted order, from the database A function called art_for_artist is called for each record and is passed the id of the artist Art for each artist is selected (line 3) and limited to one piece of art for each artist That piece
of art is returned by the function and used as the image to display with the artist’s information
Trang 11Figure A.6 The index.php page (default page)
Trang 12If the user clicks the artist’s name, the hyperlink will pass along the id of the artist and send it to another page called by artist_detail.php (line 5) If the user clicks the link with the artist’s e-mail address, a “mailto” box will appear where an e-mail message can be composed and sent to the artist (line 6)
Example A.7
<?php
1 $sql = "SELECT * FROM Artist ORDER BY name";
mysql_connect("localhost", "root", "password")
or die(mysql_error());
mysql_select_db("test") or die(mysql_error());
$recordset = mysql_query( $sql ) or die(mysql_error());
2 function art_for_artist( $artist_id ) {
3 $sql = "SELECT * FROM Art WHERE artist_id='$artist_id'
LIMIT
1 ;";
$recordset = mysql_query( $sql ) or die(mysql_error());
$row = mysql_fetch_assoc( $recordset);
return $row['image'];
}
?>
<? include("header.php") ?>
<h1>Welcome To The Canvas Gallery</h1>
<p> Welcome to The Canvas Gallery Please choose an artist from the list below to view the details </p>
<table cellpadding="15">
<?
while( $row=mysql_fetch_assoc($recordset) ) {
4 $image = art_for_artist( $row["id"] );5 print
'<tr><td><a href="artist_detail.php?id=' $row['id']
'"><img src="'.$image.'" width="150"
border="0"><br></td>';
print '<td><strong><a href="artist_detail.php?id='
$row["id"] '">'
.$row["name"] '</a></strong><br>'
6 $row["phone"] "<br><a href=\"mailto:\""
$row["email"] "\">" $row["email"] "</a>\n";
The Detail Page (artist_detail.php)
The link to the atist’s detail page (see Figure A.7) contains the ID of the particular artist so that page can determine what artist was requested The first SQL statement (see line 1 in Example A.8) selects all the information about the selected artist by his or her id number to be displayed on the page (line 2) with the artist’s name centered over the text area
containing his or her bio information, and under that his or her e-mail address as a link, and his phone number The next SQL statement (line 2) links the art to the artist and retrieves all the art information for the selected artist by joining the two tables based on the artist’s id If the art has an image(s) associated with it, the image(s) (line 6) will be displayed below the other information about the art, such as the name or price (line 7) All of the artwork for the artist is displayed at the bottom of the page
Trang 13Figure A.7 The artist_detail.php page (The ID of this artist is 12, as shown in the URL.)
Trang 14$resultset = mysql_query( $sql )or die(mysql_error());
$row = mysql_fetch_assoc( $resultset );
3 $sql = "SELECT Art.id, Art.title, Art.price, Art.image,
Art.description, Artist.name " "FROM Art Art, Artist Artist " "WHERE Artist.id='$id' AND Artist.id=Art.artist_id";
$recordset = mysql_query( $sql ) or die(mysql_error());
// Display the image if one exists
6 if ( isset($row['image']) && $row['image'] != "" ) {
print '<br><br><img src="' $row['image']
The Contact Us Page (contact.php)
Finally, the Contact Us page (see Figure A.8), contact.php, asks the user to enter the contact information in a form and submit it After the user clicks the submit button, the data is formatted and e-mailed to the administrator of the Web site, manager@The CanvasGallery.com (see line 1 in Example A.9), as well as a copy to the user to confirm that the e-mail was sent (line 2) This page also displays the status information confirming that the e-mail has been sent (line 3)
Trang 15Figure A.8 The contact.php page
Example A.9
<?php
extract($_REQUEST);
if(isset($submit)) {
$body = "\r\nContact Requested:\r\n\r\n $Name\r\n "
"$Phone\r\n $Email\r\n $Message\r\n";
1 mail( "manager@TheCanvasGallery.com", "Contact Form",
$body, "From: form@TheCanvasGallery.com" );
2 mail( $Email, "Contact Form", $body,
"From: form@TheCanvasGallery.com" );
3 $status = '<br><strong><font color="red">'
'Your message has been sent Thank you!</font><br><br>'; }
?>
Trang 16A.3.4 Securing Pages with Login
To secure the administration pages from unauthorized access, we require the user to log in Because every administration page will include the admin_header.php, this is a good place to check if the user has already logged in
The following example script is taken from admin_header.php, which starts the session and gets the value of the variable 'authorized' If this value is not 'yes', the script redirects the user to the admin_login.php page
Example A.10
<?php
session_start();
// Check if the user is logged in
if( !isset($_SESSION['authorized']) || $_SESSION['authorized'] != 'yes' ) {
header( "Location: admin_login.php" );
Trang 17Figure A.9 At the same time, the user is redirected to the page to administer the list of artists
Example A.11
<?php
extract($_REQUEST);
if( isset($login) && $login=="admin" &&
isset($password) && $password="guess" ) {
Trang 18<html>
<head><title>Art Gallery Administration</title>
<link href="style.css" rel="stylesheet" type="text/css">
A.4 Installing the Art Gallery
To install the art gallery on your computer, you must have successfully installed and configured PHP and MySQL
A.4.1 Where to Find the Files for the Canvas Gallery Site
To install the PHP files on your computer, unzip and copy the entire art gallery directory into your Web root—the default directory that is opened when you go to http://localhost/ on your computer The files can all be found on the CD
A.4.2 Installing the MySQL Database
Next, you need to install the database To do this, log into MySQL using either the mysql.exe command prompt (as shown in Figure A.10) or a GUI such as the MySQL Query Browser (see Figure A.11) We will use the “test” database If you choose the gallerydb.sql script to populate the database (see Figure A.12), there will be no initial data, and you will be responsible for adding the artists and their art work If you use the db.sql script, you will be provided with some demo art and artists
Figure A.10 Logging into the MySQL “test” database
Trang 19Figure A.11 Using the Query Browser, rather than the mysql.exe command prompt
Figure A.12 Once you log in, you could simply copy and paste the contents of the gallerydb.sql file into the
SQL field and click the Execute button
Example A.12
1 mysql> use test;
Database changed
mysql> \ db.sql
Query OK, 0 rows affected, 1 warning (0.00 sec)
Query OK, 0 rows affected (0.02 sec)
Query OK, 0 rows affected, 1 warning (0.00 sec)
Query OK, 0 rows affected (0.00 sec)
Query OK, 17 rows affected (0.03 sec)
Records: 17 Duplicates: 0 Warnings: 0
Trang 20Query OK, 0 rows affected (0.00 sec)
Query OK, 0 rows affected, 1 warning (0.02 sec)
Query OK, 0 rows affected, 1 warning (0.00 sec)
Query OK, 0 rows affected (0.00 sec)
Query OK, 0 rows affected, 1 warning (0.00 sec)
Query OK, 0 rows affected (0.00 sec)
Query OK, 4 rows affected (0.00 sec)
Records: 4 Duplicates: 0 Warnings: 0
Query OK, 0 rows affected (0.00 sec)
Query OK, 0 rows affected, 1 warning (0.00 sec)
mysql> show tables in test;
A.4.3 Editing the PHP Pages
The art gallery application assumes that the data is stored in the MySQL database called “test”, that the username is root, and the password is password root running on the localhost If this is not the case, you will have to update all the pages presented here and change the mysql_connect() parameters at the top of each page
If you do not have short_tabs set to “On” in the php.ini file, you will need to start each php script with: <?php
If your images are not loading properly, check that they are located in a place where your server recognizes them, usually under the document root directory
Once this is done, you can open up your browser and go to http://localhost/art_gallery/ and the list of the artists will appear
A.5 Conclusion
The purpose of presenting the Canvas Gallery Web project was to give you a chance to see the features of both PHP and MySQL working together as a team as described in Chapter 15, “PHP and MySQL Integration.” Although there is much that could be added to this site, it serves as an example to demonstrate how to organize the pages and to use what you have learned to build a working, viable Web site
Trang 21Appendix B PHP and E-Mail
B.1 The Mail Server
For a PHP script to be able to send e-mail, it must be able to talk to a mail server that is willing to accept its request and deliver the e-mail to the Internet
A mail server, sometimes referred to as the Simple Mail Transfer Protocol (SMTP) server, is a software process that takes
an e-mail message for delivery and forwards it to other mail servers on the Internet until the message reaches its final destination
To set up PHP to talk to your mail server, first you must know the IP or the Internet address of your mail server Typically, your local Internet Service Provider (ISP) will provide this information to you The mail server for SBC DSL, for example,
is mail.sbcglobal.net Next, you need to update the SMTP property in the php.ini file to point to this server The default value of this property is localhost because all UNIX-based machines already have a mail server installed locally at IP address 127.0.0.1 Windows, on the other hand, does not have a local mail server set up by default
In the past, any mail server would accept a request to deliver any message by anyone to anyone However, because
spammers abused this loophole, almost all mail servers are protected now, the most common protection being a mail server, provided by an ISP, that will only accept messages originating from its own network
Some ISPs require that the mail server request a login and password If this is the case, you can use the mail function provided by PHP Extension and Application Library (PEAR) PEAR’s Mail package defines an interface and functions for sending e-mail See http://pear.php.net/package/Mail You always have the option of setting up your own mail server to take delivery requests, a topic outside the scope of this book
B.2 MIME (Multipurpose Internet Mail Extensions)
MIME, as the name implies was an extension to the e-mail standard protocol for sending e-mail messages In the early days of the Internet, e-mail messages consisted of plain text The extension allowed e-mail content to contain HTML tags embedded in the message text, images, links, graphics, and logos, as well as e-mail attachments Most e-mail messages sent today use MIME
An e-mail containing different types of content, such as HTML text and images, is called a multipart MIME message When setting up this type of e-mail, the content type and encoding type is sent in MIME headers as you will see in the following examples
B.3 Runtime Configuration Options
The following list describes all e-mail–related properties in the php.ini configuration file
SMTP (Simple Mail Transfer Protocol)
This is the main property for e-mail It specifies where the server is that will accept and deliver the messages sent from a PHP program By default it is set to localhost, which will work on most UNIX-based systems, but can be configured
to point to your local ISP’s mail server
smtp_port
The SMTP port is, in most cases, port 25, the default value The SMTP standard specifies that all SMTP servers must use port 25 for incoming mail In most situations, you should not change this property or you might not be able to receive incoming mail from the Internet
sendmail_from
If you are relying on sendmail, a local program on UNIX-based systems to deliver e-mail, you can specify your default
“From” value for your messages in this field By default it is empty
sendmail_path
This property is used to set up the path to the local sendmail program It is typically a path such as /usr/sbin/sendmail or /usr/lib/sendmail on UNIX systems
B.4 The mail() Function
The built-in PHP mail function makes sending e-mail quite simple It uses the following format
Format
bool mail ( string to, string subject, string message [, string additional_headers [, string additional_parameters]] )
Trang 22B.5 Sending a Simple E-Mail Message
In the following example, PHP sends a simple e-mail message In this example, the data is supplied, but you might want to use an HTML form to submit the information from a Web page, validate the form fields, and then send e-mail based on user input
Example B.1
<?php
1 $Recipient = "marko@marakana.com";
2 $MsgSubject = "Message subject";
// You must set sender through message header
3 $MsgHeader = "From: Joe Smith <joe@yahoo.com>\r\n";
4 $MsgBody = "Message body.";
5 mail($Recipient, $MsgSubject, $MsgBody, $MsgHeader);
?>
Explanation
From
Trang 23The e-mail message will look like that shown in Figure B.1 Notice that the Subject, From, and To fields correspond to the values entered in the PHP script (This script does not output any HTML data to the browser—you will get a black page on running it.)
Figure B.1 Sending an e-mail
B.6 Example: Sending an HTML Message
Sending an HTML message is very similar to sending a plain text message The advantage of sending an HTML e-mail message is that you can gain greater control over the presentation of the message by including hyperlinks, images, tables, colors, fonts, and so on
The important difference between sending plain text and HMTL text is in the message header Headers are
meta-information passed to the mail server to tell it how to treat the message; for example, what type of content is being sent, or which encoding is used These headers are similar to the HTML headers used to redirect the user to another Web site Because this e-mail includes HTML text and or images, sound, and so on, it is formatted using the MIME format This type of e-mail includes three extra headers:
1 MIME-Version
2 Content-Type
3 Content-Transfer-Encoding The message body consists of plain text and HTML tags, images, links, and so on
Example B.2
<?php
1 $Recipient = "marko@marakana.com";
2 $MsgSubject = "Message subject";
// You must set a sender through message header
3 $MsgHeader = "From: Joe Smith <joe@yahoo.com>\r\n";
Trang 24// These two lines are required
Figure B.2 An HTML e-mail
Trang 25B.6.1 Sending a Message with an Attachment
An e-mail message sent with an attachment consists of different types of content, called a multipart MIME message The message is divided into at least two parts, one for the message and one for the attachment To allow this type of e-mail to
be sent, the MIME Content-Type header must be specified as multipart/mixed to identify the different parts, called chunks,
of the e-mail message This allows the e-mail program to read the separate parts correctly Each part has its own type of content and will need its own headers to identify that content The different parts are separated by a boundary parameter, a user-defined unique word enclosed in two hyphens
In the following example, an HTML message will be sent with an attachment included The content of the attachment is read from a file, and converted to an encoding format that allows it to be transferred by the mail program The HTML message and the attachment text are divided into two parts and sent as multipart/mixed content separated by a boundary and each containing its own MIME headers
Example B.3
<?php
// Reading file content
1 $FilePathName = "/tmp/golden_gate.gif"; // e.g
$MsgSubject = "Golden Gate Bridge";
// You must set sender through message header
$MsgHeader = "From: Joe Smith <joe@yahoo.com>\n";
// These two lines mark message as multipart