1. Trang chủ
  2. » Công Nghệ Thông Tin

Practical PHP and MySQLBuilding Eight Dynamic Web Applications phần 4 pdf

52 293 1

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Định dạng
Số trang 52
Dung lượng 6,65 MB

Các công cụ chuyển đổi và chỉnh sửa cho tài liệu này

Nội dung

■ The redirection trick in which a user clicks a page that requires a login andit redirects to the page after the login page is also used here.. For the user logout page, create a new fi

Trang 1

Create a new file called login.php and add the form:

<form action="<?php echo pf_script_with_get($SCRIPT_NAME); ?>"

Don't have an account? Go and <a href="register.php">Register</a>!

In the preceding code, you might have noticed something odd in the actionattribute of the <form>tag A function called pf_script_with_get()has been used

to process the script name ($SCRIPT_NAME) to detect which GETvariables are added

to the current page and then bolt them on to the action of the form You need to addtheGETvariable to the action if you want to access it in the code that processes theform This is fine if you know the name of the GETvariable, but if the variables couldvary, you need to detect them and add them

The reason you need this function is a result of the redirects When a userclicks a link that requires her to be logged in (such as the New Topic link), the siteshould redirect to the login page When the user has logged in, she should then beredirected to the original link This would be simple enough if there was just a sin-gleGETvariable (such as redirect=page.php), but if you are trying to add a topic to

a specific forum and are passing the Add Topic page an id, there are two GETables—the page and the id of the forum Instead of trying to hard code this, itmakes far more sense to detect which GETvariables exist and add them automati-cally to the action part of the forum

vari-Thepf_script_with_get()function is a custom function Create a file called

functions.php and add the following code:

Trang 2

$page = $page $key "=" $val "&";

The function then pulls out the GETvariables by using the foreach()function totear open the $_GETarray and loop through it In the foreach, you treat the key as

$keyand the value as $val and then glue them together in the format key=val&.Finally, you need to remove the final &from the link To do this, use the substr()function to pass it $page, determine the length with strlen(), and then remove thelast character (achieved with the –1part)

With the function complete, process the form:

$sql = "SELECT * FROM users WHERE username = '"

$_POST['username'] "' AND password = '"

Trang 3

$_SESSION['USERNAME'] = $row['username'];

$_SESSION['USERID'] = $row['id'];

It’s now time to perform any necessary redirection Remember that pages ing a user to be logged in redirect to the login page and then should be redirected to

requir-the original page To handle this redirection, requir-the page that redirects to login.php will

also pass it therefGET variable This variable can have one of two possible values:

■ newpost The user has tried to make a new post This should redirect to

newtopic.php.

■ reply The user has tried to reply to a post This should redirect to reply.php.

The next block reacts to these different options:

"/newtopic.php");

} else { header("Location: " $config_basedir

"/newtopic.php?id=" $_GET['id']);

} break;

case "reply":

if(isset($_GET['id']) == FALSE) { header("Location: " $config_basedir

"/newtopic.php");

} else { header("Location: " $config_basedir

"/newtopic.php?id=" $_GET['id']);

} break;

Trang 4

echo "This account is not verified yet You were emailed a link

to verify the account Please click on the link in the email to

continue.";

}

echo "This account is not verified yet You were emailed a link

to verify the account Please click on the link in the email to

Finally, add the footer:

Don't have an account? Go and <a href="register.php">Register</a>!

<?php

}

require("footer.php");

?>

Trang 5

Logging In the Administrator

The login page for the administrator is fundamentally the same as the preceding

page Create a new file called admin.php and add the code shown in Example 5-3.

EXAMPLE 5-3 The administrator login page is virtually identical to the user

Trang 6

The code here differs in only two ways:

■ When the admin is successfully identified, the session variable registered isADMIN, as opposed to USERNAME

Trang 7

■ The redirection trick (in which a user clicks a page that requires a login and

it redirects to the page after the login page) is also used here The difference

is that the three options are add(redirects to addforum.php),cat(redirects to

addcat.php), and del(redirects to delete.php).

With the ability for an administrator to log in, add the administrator links above

the table on index.php:

<?php

require("header.php");

if(isset($_SESSION['ADMIN']) == TRUE) {

echo "[<a href='addcat.php'>Add new category</a>]";

echo "[<a href='addforum.php'>Add new forum</a>]";

}

$catsql = "SELECT * FROM categories;";

$catresult = mysql_query($catsql);

Another piece of code to add are the Login and Logout links in footer.php The

same technique used in the header file for checking if the user is logged in and playing the relevant link is used here, but on this page, you check the ADMINsessionvariable as opposed to the USERNAMEvariable:

To log out the user or admin, you simply use session_unregister()to unregisterthe relevant session variable

Trang 8

For the user logout page, create a new file called logout.php and the following code:

To create the admin Logout link, create a new page called adminlogout.php and

add the following code:

P OSTS AND R EPLIES

A fundamental feature in the forum software is the capability to post new content to

a chosen forum or to reply to existing conversations This process should be as ple and intuitive as possible, and it should be convenient to read a discussion andthen post a reply

sim-The process of posting a new message and replying are fairly similar To post anew message, a topic must first be created and then the id of the topic can be usedwhen creating the message It is important to remember that a new thread must

include both a topic and a message If you will create a reply, you simply need to

know the id of the existing topic and then add a new entry to the messages table

Posting a New Topic

To post a new topic, the page must essentially have two potential ways of working:

■ The forum idis passed to the page as an idGET variable This idcan beused to determine to which forum the topic will be added

Trang 9

The user has clicked the main New Topic link in the header.php file, and as

such, no forum idis passed to the page The New Topic page should display

a drop-down combo box on the form that contains a list of forums that the

user can select to post the topic

The only part of the page that is different is that no id is passed to it to mine whether the combo box with the forums should be displayed

deter-Create a new file called newtopic.php and add the following code:

<form action="<?php echo pf_script_with_get($SCRIPT_NAME); ?>"

Trang 10

The usual suspects are present in this forum: the subject, body, and Submit ton At the top of the form, a check is made to see if $validforumis equal to 0 If it

but-is, the combo box is created with the forums inside it This $validforumvariable isthe result of the usual validation that exists at the top of the page

Again, the pf_script_with_get()function is used on this page

Add the code at the top of the page:

Theifcheck redirects the page if there are no rows

Validate the GETvariable:

Trang 11

■ If the page was not passed the variable, use the idfrom the drop-down

combo box that was added to the form

Here is the code:

$topicsql = "INSERT INTO

topics(date, user_id, forum_id, subject) VALUES(NOW()

Trang 12

In this code, the if checks to see if $validforum is equal to 0 (no variablepassed to the page), and if it is, one SQL statement is defined; otherwise, the SQLstatement in the elseis defined.

Run the query:

$topicsql = "INSERT INTO topics(date, user_id, lastpostuser_id, forum_id,

subject) VALUES(NOW()

, " $_SESSION['USERID']

", " $_SESSION['USERID']

", " $validforum ", '" $_POST['subject']

$messagesql = "INSERT INTO messages(date,

user_id, topic_id, subject, body) VALUES(NOW()

Trang 13

header("Location: " $config_basedir "/viewmessages.php?id="

Here you check if the $validforumvariable is not equal (!=) to 0(a valid forum

idwas passed to the page) This idis used to get the name of the forum and add theheadingPost new message to the <forum>forum If $validforumis equal to 0(novalidid GET variable was posted to the page), the generic Post a new messageheading is added

Finally, add the closing code:

Trang 14

FIGURE 5-10 Posting a new message

Replying to Threads

Writing a page to reply to threads is fairly simple The page is passed the topic id as

anidGET variable, and this is used to take the content from the form and insert it

into the messages table.

Create a file called reply.php and add the form:

<form action="<?php echo

Trang 15

Move to the start of the file and add the introductory code:

Trang 16

if($_POST['submit']) {

$messagesql = "INSERT INTO messages(date,

user_id, topic_id, subject, body) VALUES(NOW()

C REATING A DMINISTRATOR -S PECIFIC P AGES

With the user-accessible pages complete, you can now create the specific pages These pages deal with the management of the forums and allow you

administrator-to add and remove categories, forums, and threads

Trang 17

Incorporating these administrative features into the forums involves two steps.

First, for the addition of content, specific pages are created (addcat.php and rum.php) Next, for the deletion of content, X links are added next to categories,

addfo-forums, and threads when the administrator is logged in Clicking the link deletesthe content

Adding Categories

This page is a simple form and inserts a query script First, create a file called cat.php and add the form:

add-<h2>Add a new category</h2>

<form action="<?php echo

Trang 18

In this code, the database connection details are added and an INSERTquery is

made to the categories table in which the data from the form is added The query is

executed, and the page redirects

Add the elsethat contains the form:

<h2>Add a new category</h2>

<form action="<?php echo

Trang 19

sim-Create a new file called addforum.php and add the following code:

<h2>Add a new forum</h2>

<form action="<?php echo pf_script_with_get($SCRIPT_NAME); ?>"

Trang 20

<h2>Add a new forum</h2>

<form action="<?php echo pf_script_with_get($SCRIPT_NAME); ?>"

method="post">

Finally, place the closing code below the form:

</table>

</form>

Trang 21

At the start of the project, you used the InnoDB table type when creating yourtables With this type of table, you can enforce referential integrity, but it is not cur-rently switched on.

To turn on referential integrity, specify the relationships between the tables inSQL In this project, the intention is to allow all dependent records in other tables

to be deleted This is called a cascading delete Before writing the SQL to do this,

take a moment to understand how these relationships are defined:

FIGURE 5-11 Adding a forum

Trang 22

■ Thetopic_idfield in the messages table stores the same value as the idfield

in the topicstable

■ Theforum_idfield in the topics table stores the same value as the idfield in

the forums table.

■ Thecat_idfield in the forums table stores the same value as the idfield in

the categories table.

To create the first relationship, go to phpMyAdmin, click the SQL tab, and addthe following code:

ALTER TABLE messages ADD FOREIGN KEY(topic_id)

REFERENCES topics (id) ON DELETE CASCADE;

Here you change the messages table (ALTER TABLE messages) and specify that thetopic_id(ADD FOREIGN KEY (topic_id)) relates to theidfield in thetopicstable(REFERENCES topics (id)) with cascading deletes enabled (ON DELETE CASCADE).Run a very similar statement, but with different tables and fields for the secondrelationship:

ALTER TABLE topics ADD FOREIGN KEY(forum_id)

REFERENCES forums (id) ON DELETE CASCADE;

And, finally, for the third relationship:

ALTER TABLE forums ADD FOREIGN KEY(cat_id)

REFERENCES categories (id) ON DELETE CASCADE;

Before you write the SQL code to actually delete the records, you need to addsome controls for the administrator to select what to delete To do this, you will put

a small X next to an item, and if the administrators clicks it, it will be deleted First, add a delete button just before the category is added Fire up index.php

and look for the line in which the category is outputted Just before the line, add thefollowing code:

while($catrow = mysql_fetch_assoc($catresult)) {

echo "<tr><td colspan=2>";

if($_SESSION['ADMIN']) { echo

Trang 23

This code links to a page that has two GET variables: funcand id The funcvariable is passed either cat,forum, or threadas a value, and these options deter-mine what is deleted The second variable, id, provides the idof the resource to bedeleted.

Move further down where the forum is outputted and add the following code:

echo "[<a href='delete.php?func=thread&id="

$topicrow['topicid'] "?forum=" $validforum "'>X</a>] - ";

Validate the idGET variable as usual:

$db = mysql_connect($dbhost, $dbuser, $dbpassword);

mysql_select_db($dbdatabase, $db);

if(isset($_GET['id']) == TRUE) {

if(is_numeric($_GET['id']) == FALSE) {

$error = 1;

Trang 25

The delete SQL syntax is fairly simple: DELETE FROM<table>WHERE id =<the id

of the thing you want to delete> After the delete is made, the page redirects to the

next level up in the page hierarchy As an example, when you delete a topic, theforum topics page will be deleted See Figure 5-12

In addition to learning new topics, the repetition of existing skills furthers yourunderstanding of these skills As an example, each time you issue a SQL query, youare cementing your knowledge of this element of PHP more and more Before youknow it, you will no longer need to refer to the book or existing code to connect toMySQL—you will be able to do it automatically

Without further ado, it’s time for the next project

Trang 27

Creating a Shopping Cart

For many developers, the humble shopping cart holds a special place in theirhearts Although PHP and MySQL are the fodder for a range of Web applications,many developers learned their trade with the ambition to write the ubiquitous shop-ping cart If there is a Zen to Web development, it is likely to be experienced whilewriting a shopping cart

Although a common sight on the Web, shopping carts do come in a variety ofdifferent flavors The various incarnations typically differ in ways that are specific

to the type of business using the software For example, the sale of items such asbooks, CDs, and DVDs differs from the sale of cables, food, building materials, andjanitorial products The core difference is quantity; you generally buy only a singlebook or DVD at time, but it is not uncommon for a restaurant to buy 10 packs ofdinner rolls

Trang 28

10 boxes of teabags and adds them to his shopping cart The page nowrefreshes, and he sees the contents of his shopping cart John then buys cof-fee, and his cart is updated again John realizes he does not need the coffeeafter all, so he clicks the X link to delete the coffee from his cart John fin-ishes choosing items and clicks the Go to the Checkout link He is promptedfor his address, which he fills in, and is taken to the payment screen Johncan choose to pay with PayPal or by check John clicks the PayPal buttonand taken to the PayPal payment screen at paypal.com, where he pays for theorder.

Pauline needs some teabags, too Pauline already has an account on the site,

so she logs in She adds the items she needs to her cart and clicks the Go tothe Checkout link At the address page, she can choose between a newaddress and the address stored with her user account She chooses theaccount address and is taken to the payment screen Pauline chooses to pay

by check and is given instructions about where to send the check and towhom to make it payable

Ken runs the Web site and wants to see all current orders He logs in with hisadministrator username and password and is provided with a list of orders.Ken looks at each item, packages the order, and writes the address on theparcel To confirm the completion of the order, Ken clicks the Confirm Pay-ment link The order is now complete

The shopping cart you build in this chapter satisfies all of the features cussed in the preceding use case, but there is still a huge scope for development.Shopping carts can become huge and complex systems, and an entire book would

dis-do the subject of building shopping carts justice This project will provide a solidfoundation in which you can continue to build in extra features

Ngày đăng: 12/08/2014, 21:21

TỪ KHÓA LIÊN QUAN