Building Web Sites All-in-One For Dummies® (86 page)

BOOK: Building Web Sites All-in-One For Dummies®
3.95Mb size Format: txt, pdf, ePub

Listing 3-6: Validating the Form in PHP

$fname=$_POST[‘fname'];

$lname=$_POST[‘lname'];

if ($fname==”” Or $lname==””){

print ‘';

}

?>

The variable
$fname
is set equal to the information entered in the form field
fname
, and the variable
$lname
is set equal to the information entered in the
lname
form field. The information is retrieved by using the
POST
method. The conditional statement uses the logical operator
“Or”
. The comparison operator (
==
) is used to see whether either variable contains no information.

Quotation marks with nothing between them indicate that the variable is null. If either variable contains no information, the next line of code refreshes the browser to the form. However, if information is in both fields, you need additional code; otherwise, the user is stuck on the
validate.php
page.

Enter the
else
statement. Listing 3-7 shows the PHP code with the addition of an
else
statement.

Listing 3-7: Creating a Fork in the Road

$fname=$_POST[‘fname'];

$lname=$_POST[‘lname'];

if ($fname==”” Or $lname==””){

print ‘';

} else {

print ‘';

}

?>

The addition of the
else
statement creates another course of action when both variables do contain data. A third statement can be added to evaluate a condition:
elseif
. This statement enables you to add an alternative outcome if the
elseif
statement evaluates to be true. You can add as many
elseif
statements to cover any possible scenario. Listing 3-8 shows an example in PHP of an
elseif
statement added to evaluate another possible outcome.

Listing 3-8: Using an elseif Statement

$password=$_POST[‘password'];

$fname=$_POST[‘fname'];

$lname=$_POST[‘lname'];

if ($password==”” Or $fname==”” Or $lname=””){

print ‘';

} elseif ($password!= “letmein”) {

print ‘';

} else {

print “Welcome $fname $lname “;

}

?>

This scenario evaluates a login form for a Web site. The code creates three variables, retrieving the first name, last name, and the password submitted by the user. The
if
statement checks to be sure the user entered data in each form field. The
elseif
statement evaluates whether the password does not equal
letmein
. If the
elseif
statement evaluates as true, the visitor is redirected to Google. The final scenario is what happens when the previous statements evaluate as false and welcome the visitor to the Web site.

Using comparison operators

Comparison operators
test for equality, inequality, or whether a value is greater than or less than another value. You use comparison operators in conditional statements to compare elements, such as whether a variable contains certain information. Comparison operators are often confused with assignment operators. For example, when you create a variable, you use the assignment operator
=
. When you create a conditional statement and want to verify whether the content of a variable is equal to a specific value, you use the comparison operator
==
. Table 3-1 shows the comparison operators you can use when creating conditional statements.

Table 3-1 Comparison Operators

Operator

Example

Operator Name

Result

==

$a==$b

Equal

True if the value of
$a
equals the value of
$b

!=

$a!=B

Not equal

True if the value of
$a
does not equal the value of
$b

Using logical operators

You use
logical operators
when you want to evaluate multiple conditions. When you evaluate multiple conditions, you can specify whether a statement is true if all conditions are met or if only one condition is met. Table 3-2 shows the logical operators you can use when creating conditional statements.

Table 3-2 Logical Operators

Operator

Example

Result

And

$a==”Jack” And $b==”Jill”

True if both sides of the statement evaluate as true

Or

$a==”Jack” Or $b==”Jill”

True if either side of the statement evaluates as true

Xor

$a==”Jack” Xor $b==”Jill”

True if either side of the statement evaluates as true, but false if both sides of the statement evaluate as true

Repeating Lines of Code, Using Loops

Loops are very handy when you need to repeat certain lines of code for a specified number of times. You can loop through a database while searching for certain data. A
loop
continues as long as a given condition is true. There are different types of loops you can add to your PHP code. We show you how to get loopy in the upcoming sections.

Using a while loop

A
while
loop is a loop in its simplest form. The loop executes while a given condition is true. As soon as the condition is false, the next lines of code are executed. Listing 3-9 shows an example of a
while
loop.

Listing 3-9: Using a while Loop

$MyNum = 1;

while ($MyNum <= 10)

{

print (“$MyNum”);

$MyNum++;

}

?>

The code in Listing 3-9 will print the numbers
1
through
10
. The loop continues as long as the value of the
$MyNum
variable is less than or equal to
10
. The line of code that reads
$MyNum++;
increases the value of
$MyNum
by a value of
1
every time the loop executes.

Using a for loop

A
for
loop executes code for a given set of iterations. The value by which the loop increments can vary. For example, you can use a
for
loop to search every record in a database or every other record in a database. Listing 3-10 shows a
for
loop.

Listing 3-10: Using a for Loop

for ($MyNum = 1; $MyNum <= 10; $MyNum+=2) {

print $MyNum;

}

?>

This loop also executes as long as the value of
$MyNum
is less than or equal to
10
. The
for
loop has three statements that are separated by semicolons. The first statement in the loop sets the value of
$MyNum
to
1
; the second statement tells the PHP compiler to execute the loop as long as the value of
$MyNum
is less than or equal to
10
; and the third statement specifies the loop to increment the value of
$MyNum
by a value of
2
. The code will print the following:
13579
.

Generating a Random Image

The previous sections give you a look at PHP code. If you read through them, you might now be interested in seeing a real-world application using PHP code. You can find plenty of applications on the Web. For that matter, you can even find examples of code on the Web. This chapter is but a brief introduction showing you some of the building blocks of PHP code. If your interest is piqued, consider picking up a copy of
PHP 5 For Dummies,
by Janet Valade (Wiley). And now, on to the real-world example of PHP in action.

When people visit a Web site, they like to see new and different things. One way to ensure that they do is to generate a random image on the home page. If you have ten or more images that are generated randomly, the visitor is likely to see a different image every time he visits the site. To generate a random image on a home page, follow these steps:

1.
Rename the images and add a number suffix, starting with 1.

We recommend using Adobe Bridge to rename the images to
IMG_
, followed by a number. You end up with a folder of images named
IMG_1.jpg
,
IMG_2.jpg
, and so on.

2.
Open the PHP document in which you want to display a random image each time the page loads.

3.
Position your cursor where you want the image to appear.

To constrain the position of the image, put the PHP code in a table row.

4.
Enter the following code:

$image = rand(1,30);

print ‘';

?>

You get a lot of bang for your buck with just a few lines of code. The first line tells the server it is parsing PHP code. The second line of code creates a variable named
$image
and sets it equal to a random number between
1
and
30
(the number of images renumbered to display randomly). The third line of code uses an HTML image tag (
)
to add the random image to the page. The
$image
variable is used to append the number to the
image
filename.

5.
Upload the file to your server and preview it in your Web browser.

The script causes an image to be displayed randomly. (See Figure 3-4.) Refresh the browser a few times to test the script.

Figure 3-4:
Is it a bird? Is it a plane? No, it's a random image generated by PHP code.

Chapter 4: MySQL and PHP

In This Chapter

Building a mailing list form

Creating a MySQL database

Transferring data to the database

Reading data from the database

MySQL and PHP are almost like a marriage made in heaven. PHP likes to send stuff to MySQL, and MySQL accepts it with open arms, er, fields. Like Batman and Robin, MySQL and PHP are a dynamic duo. So dynamic, in fact, that quite a few applications out there use the combination to good effect. Blogs, bulletin boards, and calendar applications are good examples of the dynamic duo at work. You can write a PHP script in a PHP document that sends information to and plucks data from a MySQL database. MySQL databases keep the information safely locked away until its good buddy PHP comes calling.

In case you rushed right to this chapter expecting to find out everything you need to know about MySQL and PHP, well, you almost came to the right place. To learn everything about integrating MySQL databases with PHP pages would require a bigger book. However, in this chapter, on these very pages written with tender loving care, with blisters on your authors' fingers, we show you how to use PHP and MySQL to create a mailing list from visitors who submit a form with their contact information.

You can choose from many applications for managing mailing lists. The applications enable you to easily manage a mailing list, send information to people who have opted in to the mailing list, and so on. However, if you have a client who doesn't need all the bells and whistles, why give them to him? If your client's only need is to store a limited number of names and e-mail addresses in a database and occasionally retrieve the information, you can easily accomplish this by creating a form for your client's Web site visitors, a MySQL database on your client's Web server, and then the PHP code to send and retrieve information from the database.

Creating a Mailing List Form

The first step in the process of creating a mailing list is setting up a mailing list form. In case you haven't read the chapter on creating forms, the following steps lead you through the process. It's easy. Really. The results from the form are what populates the database.

To create a mailing list form:

1.
In your favorite HTML editor (ours is Dreamweaver), open the document into which you want to insert a mailing list form.

Make sure you're working in Design view.

Some designers have the audacity to create a pop-up window on the home page, asking the visitor to sign up for a mailing list. Really, how can you tell if you want to sign up for a mailing list when you haven't even seen the site yet? We'll jump off the soapbox now, leaving the absolute location to you and your client.

2.
Position your cursor where you want to insert the form.

3.
Choose Insert
⇒
Form
⇒
Form.

Dreamweaver inserts the first building block for a form.

4.
Choose Window
⇒
Properties.

The Property inspector opens.

5.
In the Action field, enter
addrecord.php
.

This is the document you create to add the information to the database. The action tells the Web browser to launch the page when the visitor clicks the Submit button.

6.
Position your cursor within the form (the red border) and then choose Insert
⇒
Table.

The Table dialog box appears. Using a table for a form enables you to keep text and form fields segregated. For a simple e-mail collection, you need three rows and two columns.

7.
Enter
3
in the Rows field and
2
in the Columns field. Set the other parameters to suit the page in which you're inserting the form.

8.
Click OK.

Dreamweaver creates a table.

9.
Enter the desired text in the first column of the first row.

Entering
Name
and
E-Mail
makes a lot of sense to us.

10.
Position your cursor in the second column in the first row and then choose Form
⇒
TextField.

Dreamweaver inserts a text field in the table cell.

11.
Choose Window
⇒
Properties.

The Property inspector appears.

12.
Label the TextField
Name
.

The default name of the first text field in a document is Text. Highlight the default name and type the desired name in its place. In this case, type
Name
. (See Figure 4-1.)

Figure 4-1:
Setting the parameters for the text field.

13.
Enter a value of
40
in the Char Width and Max Chars fields.

These values size the text field and limit the maximum number of characters users can input to 40. If your client has visitors with long names, you might want to increase these values.

14.
Position your cursor in the second column of the second row and repeat Steps 10–13.

This time, name the TextField
E-Mail
.

15.
Position your cursor in the first column of the third row.

16.
Choose Insert
⇒
Form
⇒
Button.

Dreamweaver inserts a button in your form. If desired, you can change the button text in the Property inspector. Your finished form should resemble Figure 4-2.

Figure 4-2:
The completed form.

Creating the Database

After you know what fields you want in your database, you're ready to create it. Now, we could show you a whole lot of complex code that creates a new database, but why work harder when you can work smarter? Most Web hosting services that have MySQLAdmin installed also have a little gem called PHPMyAdmin, which enables you to create databases from within the service's control panel. This dynamic duo gives you the power to define and create a database. Here's how to do it:

1.
Log in to your Web server.

If you're not sure how to do this, check with your hosting service's technical support.

2.
Create a new MySQL database.

Your Web hosting service probably has something like a MySQLAdmin icon. Click the icon and create a new database. You'll submit a username and password. Jot these down because you'll need them to connect to the database. Also, make sure that you choose the DBA User option, which means
database administrator.
If you're unsure, check with your Web hosting service's technical support.

3.
After you create the database, launch PHPMyAdmin.

There should be an icon for this on your server's control panel. If you're not sure of how to launch PHPMyAdmin, check with your Web hosting service's technical support.

4.
Select the database you just created.

5.
Click Operations.

The Operations section of the PHPMyAdmin dialog box appears. (See Figure 4-3.)

6.
Enter a name in the Name text box (underneath Create New Table on Database).

You can have multiple tables in a database. However, for a simple database like this, you need only one table. Give the database a name that reflects its purpose. Don't create a name that has spaces.

7.
Enter a value in the Number of Fields text box.

For this database, you need three fields.

Figure 4-3:
Configuring the database.

8.
Click the Go button.

The dialog box refreshes, and you're faced with the task of naming your fields. (See Figure 4-4.)

Figure 4-4:
Setting the field character-istics.

9.
Enter the names and characteristics for your fields.

•
First field:
Name the first Field
ID
, choose INT from the Type drop-down menu, enter
5
in the Length/Values field, choose Auto_Increment from the Extra drop-down menu, and then select the Primary radio button. The Web hosting service you're using may have different options. When all else fails, call tech support.

•
Second field:
Name the second Field
Name
, accept the default VARCHAR (
variable characters,
which means the field will accept text and numbers, which are read as text data and can't be used for arithmetic operations) option for Type, and then enter
40
in the Length/Values field.

•
Third field:
Name the third Field
E-Mail
, accept the default VARCHAR option for Type, and then enter
40
in the Length/Values field.

Other books

Trapped Under Ice by Schiller, M. J.
Haven 3: Forgotten Sins by Gabrielle Evans
Havisham: A Novel by Ronald Frame
Sky's Lark by Cheyenne Meadows
Mercury Man by Tom Henighan
When Johnny Came Marching Home by William Heffernan