Tutorial for php

advertisement
Creating a Database Driven Web Site
Table of Contents
DYNAMIC WEB SITE? ........................................................................................................................................................................ 1
INTRODUCTION TO DATABASES ................................................................................................................................................... 2
CONNECTING TO MYSQL ................................................................................................................................................................. 3
SQL (STRUCTURED QUERY LANGUAGE) .................................................................................................................................... 4
INTRODUCTION TO PHP ................................................................................................................................................................... 5
VARIABLES ........................................................................................................................................................................................... 6
ARRAYS ................................................................................................................................................................................................ 7
FORMS .................................................................................................................................................................................................. 8
CONDITIONAL STATEMENTS ................................................................................................................................................................. 9
LOOPS ................................................................................................................................................................................................. 10
LOOPS AND ARRAYS ............................................................................................................................................................................ 11
USING PHP WITH MYSQL ............................................................................................................................................................... 11
CONNECTING TO THE DATABASE......................................................................................................................................................... 12
PASSING INFORMATION THROUGH THE NAVIGATION LINKS................................................................................................................. 13
CREATING A RECORDSET FROM THE DATA PASSED IN THE URL QUERY STRING .................................................................................. 13
DISPLAYING (ECHOING) DATA FROM THE DATABASE .......................................................................................................................... 14
DISPLAY DATA FROM A RECORDSET .................................................................................................................................................... 16
DISPLAY AN IMAGE. ............................................................................................................................................................................ 17
INCLUDE FILES .................................................................................................................................................................................... 17
SEARCHING FOR ACTIVITIES ................................................................................................................................................................ 18
ADDING A FORM TO MAIL OR ENQUIRY PAGE ...................................................................................................................................... 20
Dynamic web site?
What is a dynamic web site?
Classical hypertext navigation, with HTML alone, provides "static" content, meaning that the user
requests a web page and simply views the page and the information on that page.
A dynamic web site provides an "interactive experience". That is the content (text, images, etc.) on a
web page can change, in response to different user input. These sites contain scripts that query a
database or program on a web server.
What we need
A web server such as Apache web server.
Php (Hypertext Preprocessor) a web application scripting language.
a database system such as Mysql (Structured Query Language)
page 1
Before we look at our web site we need to do some work in the background on setting up our
database tables.
Introduction to databases
MySQL, a database server is a program that can store large amounts of information in an organized
format that can be accessed through scripting languages like PHP. For example, you could tell PHP
to look in the database for information on Tourist Activities that would appear on your web site.
Instead of having to write an HTML page for each of your activities, you could write a single PHP file
that was designed to fetch any activity from the database and display it. Second, adding an activity to
your Website would be a simple matter of inserting the activity’s data into the database. The PHP
code would take care of the rest, automatically displaying the new activity along with the others when
it fetched the list from the database.
A database is composed of one or more tables, each of which contains a list of
things. Your database is your first name and so we will start with a table called activities that would
contain a list of activities. Each table has columns which are called fields, and each row or in this
case activity, is called a record.
act_id act_activity act_theme act_description
1
Tasting Tour
relax
2
Walking
Mauao
relax
Tauranga Tasting
Tours specialise in
personally
customised winetasting tours for
small groups (up
to 19 people), of
various winemaking
regions. Relax in airconditioned comfort
and enjoy wines and
sightseeing with the
personal service of a
guide who is still
professionally
involved in the wine
industry. Enjoy the
countryside, talk to
the winemakers and
sample their wines.
Enjoy a relaxing walk
with beautiful views.
Walking tracks are
provided on Mauao
Historic Reserve; it
takes about half an
hour to reach the
summit.
act_website
act_image
http://www.tastingtours.co
.nz
tasting.jpg
http://www.nzlive.com/tau
ranga-city-council/mtmaunganui-mauao
walking.jpg
The fields are id, activity, theme, description, website and image and each row (or record) contains
data about each activity organized into each of the fields.
page 2
Connecting to MySQL
The standard interface for working with MySQL databases is to connect to the
MySQL database server software and type commands one at a time. To make this connection to the
server, you’ll need the MySQL client program (for windows) or Terminal for Mac Os X. However we
are going to use PhpMyAdmin instead. (Because PhpMyAdmin has a nice graphical interface to work
with).
1. In a browser, enter the following URL, http://phpclass.local/~martinb/phpmyadmin/index.php
Note: we chose to put only one copy of PhpMyAdmin into user martinb’s sites folder on the
webserver called phpclass.
2. In the login screen enter the username and password for MySql. In this case I am using
jamesbond as my user and his password apple.
3. This should give you a screen similar to this.
4. Note user jamesbond has no privileges to create a new database. This is because jamesbond
is the name of the database. Select the database by clicking jamesbond(0), top left of screen.
5. Enter activities as the name of the table and 6 as the number of fields. (as below) and click
Go.
6. Enter the fields, type, and length/values as below. in the act_id field click the primary key icon
on the right.
page 3
Then click save.
7. To enter data click Insert. Then enter your data.
Click Go. Then enter next record and so on.
8. However, to save time we have provided a text file, activity.sql, which you can import.
here are the steps
In PhpMyAdmin click Import, in the File to import section click choose file, choose activity.sql,
and click Go. The table activities should appear in your database.
SQL (Structured Query Language)
SQL is the standard language for working with most databases. Commands in SQL are also referred
to as queries. We use SQL to query the MySQL database server software.
Open the file activity.sql. This file was created by Exporting the jamesbond database. It
consists of various SQL commands that create the activities table and an information table
and their data when the file is imported by you.
CREATE TABLE IF NOT EXISTS `activities` (
`act_id` int(3) NOT NULL,
`act_activity` varchar(30) NOT NULL,
`act_theme` varchar(30) NOT NULL,
`act_description` text NOT NULL,
`act_website` varchar(30) NOT NULL,
`act_image` varchar(30) NOT NULL,
PRIMARY KEY (`act_id`)
);
page 4
This line would insert the second record into our activities table.
INSERT INTO `activities` VALUES (2, 'Walking Mauao', 'relax', 'Enjoy a relaxing walk with beautiful
views. Walking tracks are provided on Mauao Historic Reserve. It takes about half an hour to reach
the summit. ', 'http://www.nzlive.com/tauranga-city-council/mt-maunganui-mauao', 'walking.jpg');
Let’s use some SQL queries to find data in our activities table.
Click the SQL tab and enter in this command
SELECT * FROM `activities` WHERE (`act_activity` LIKE '%swimming%' OR
`act_description` LIKE '%swimming%' );
This would select all (* = all) records in the table activities where swimming is “contained” in the fields
act_activity OR act_description. Note: % is called a ‘wildcard’. If we ran the query,
SELECT *
FROM `activities` WHERE `act_activity` LIKE 's%';
it would give us all the records where the field act_activity starts with s.
Introduction to PHP
PHP code is embedded into HTML (just like javascript). JavaScript is interpreted by the Web browser
once the Web page that contains the script has been downloaded. Server-side scripting languages
such as PHP are interpreted by the Web server before the page is even sent to the browser. And,
once it’s interpreted, the results of the script replace the PHP code in the Web page itself—all the
browser sees is a standard HTML file. The script is processed entirely by the server; hence that’s
why PHP is called a server-side scripting language.
Our first PHP script. Type out the following code using a text editor that can save the file as plain text.
Save the file to your webserver’s root document folder. (in our example for jamesbond, jamesbond
logs into the phpclass server and saves the file as hello.php into the jamesbond\sites folder. Or in
C:\inetpub\wwwroot\ in IIS, or C:\Program Files\Apache Group\Apache\htdocs\ in Apache for
Windows).
Note that if you view the file on your own machine, you cannot use the File > Open… feature of your
browser, because your Web server must intervene to interpret the PHP code in the file. Instead to
view your page type this as the URL into your browser. http://phpclass.local/~jamesbond/hello.php.
<html>
<head>
<title>PHP Test</title>
</head>
<body>
<?php echo '<p>Hello World</p>'; ?>
</body>
</html>
Most of this is normal HTML code but the line between <?php and ?> is written in PHP. <?php means
“begin PHP code,” and ?> means “end PHP code.” The Web server is asked to interpret everything
between these two tags, and to convert it to regular HTML code before it sends the Web page to the
browser requesting the page.
The web browser will receive the following code.
<html>
page 5
<head>
<title>PHP Test</title>
</head>
<body>
<p>Hello World</p>
</body>
</html>
Variables
Think of variables as letter boxes, each letter box has a unique address, each variable has a unique
name, letterboxes and variables are used to store values.
When a variable is declared, it can be used over and over again in your script.
All variables in PHP start with a $ sign symbol.
The correct way of declaring a variable in PHP:
<?php
$txt="Hello World!";
$x=16;
?>
Note that all PHP statements end with a semi-colon (;).
PHP is a Loosely Typed Language
In PHP, a variable does not need to be declared before adding a value to it.
This means that a single variable may contain any type of data; a number, a string of text, or some
other kind of value.
$test = 3; would put the number 3 in the variable $test.
$test = “Hello World”; would then store the string of text contained within the quotes, i.e. Hello World.
So the information in the variable $test has changed type from a number to a string.
For those with little programming experience the equals sign is an assignment operator. Consider
this PHP statement
$test =$var + 1; // this means add 1 to what is in $var and “assign” it to $test (put it in $test)
Note the // after the ; this means that the rest of the line is a comment. Comments describe what your
code is doing. /* */ can be used as well, /* starts the comment and */ ends it.
Open your hello.php file in a text editor and add in the following lines (the ones in bold). Save the file
as quotes.php into your root folder and
<html>
<head>
<title>PHP Test</title>
</head>
<body>
<?php echo '<p>Hello World</p>';
$test1 = 'PHP';
echo '$test1 is great'; // this would output $test1 is great
echo "$test1 is great"; // would output PHP is great
?>
</body>
page 6
</html>
The difference is the use of double quotation marks.
Arrays
An array is a special type of variable that contains multiple values. We described a variable being like
a letter box with a unique id (the address). An array is like an apartment block with many residences.
$MyClass=array(‘Henry’,’Max’,’Tim’);
This code creates an array called $MyClass that will contain the values Henry, Max and Tim.
To access a value in an array we need to know its index. In this case;
echo $MyClass[0]; // outputs ‘Henry’
echo $MyClass[1]; // outputs ‘Max’
echo $MyClass[2]; // outputs ‘Tim’
The code $MyClass[1] = ‘Fred’; would replace ‘Max’ with ‘Fred’
Add this code to your quotes.php file and save it as array1.php.
Note the use of paragraph tags <p> </p> to force the output down the page, otherwise it would be
on one line across the page. As <p> is an HTML tag so we need to go in and out of PHP and HTML.
<html>
<head>
<title>PHP Test</title>
</head>
<body>
<?php echo '<p>Hello World</p>';
$test1 = 'PHP';
echo '<p> $test1 is great </p>'; // this would output $test1 is great
echo "<p>$test1 is great</p>"; // would output PHP is great
$MyClass=array('Henry','Max','Tim');
?>
<p><?php echo $MyClass[0]; // outputs ‘Henry’ ?></p>
<?php echo $MyClass[1]; // outputs ‘Max’
echo $MyClass[2]; // outputs ‘Tim’
?>
<p><?php $MyClass[1] = 'Fred';
echo $MyClass[1]; ?></p>
</body>
</html>
Array indices don’t always have to be numbers; that’s just the most common choice. You can also
use strings as indices to create what is called an associative array. This type of array is called
associative because it associates values with meaningful indices. In this example, we associate an
exam grade with each of three names:
First we will use an array to assign grades to each person.
$examgrade = array(‘Tim’ => ‘merit’,’Max’ => ‘achieved’, ‘Henry’ => ‘not achieved’);
Now if we want to know Max’s grade
echo 'Max\'s exam grade is ' .$examgrade['Max']; // Note to get the apostrophe we need to put
a backslash next to it
page 7
Add the code above into your array1 file, save it as array2.php and view it in your browser.
Associative arrays are very important when it comes to user interaction in PHP.
User interaction in server side scripting languages such as PHP is limited to back and forth between
the user and server. The user sends requests to the server, and the server replies with dynamically
generated pages.
By using the URL query string we can request a page and send information at the same time.
If you see a URL in which a question mark followed the file name, you’ve witnessed this simple
method in use.
Consider this example:
In your array2.php page add the following code for a hyperlink and save the file as querystring.php.
<a href="activity.php?first_name=James">send first name</a>
This is a link that loads the activity.php page and informs the php code that the first_name equals
James.
We have passed a variable called first_name with a value of James using the query string (part of the
URL that follows the question mark).
Our activity.php file would “Get” the value of the variable first_name and store it in the variable
$firstname. It can then be used where needed in the page.
Open your text editor, add the code below and save it as activity.php (you don’t need any HTML code
in the file, just the PHP code).
<?php
$firstname = $_GET[‘first_name’];
echo "Welcome to the website $firstname!!";
?>
PHP automatically creates an array variable called $_GET that contains any values passed in the
query string. $_GET is an associative array, so the value of the first_name variable passed in the
query string can be accessed as $_GET['first_name’]. Our script in activity.php assigns this value to
an ordinary PHP variable ($firstname), then displays it as part of a text string using an echo
statement.
You can pass more than one value in the query string. Change the link in the querystring.php file to
read as follows
<a href="activity.php?first_name=James&last_name=Bond”>send first and last name to
activity page”</a>
Save the file as querystring2.php
Change the code in activity.php to read:
<?php
$firstname = $_GET['first_name'];
$lastname = $_GET['last_name'];
echo "Welcome to the website $firstname $lastname 007";
?>
Forms
So we have passed first name and last name but we need to pass data based on user input. A way
of getting user input is through the use of HTML forms. When the form is submitted, PHP can access
the inputted values from the form using $_GET or $_POST arrays.
page 8
If we use $_GET the values are passed in the URL query string. However, it is not always desirable
to pass information visibly. So we use the $_POST array to pass the values invisibly.
Make a form page like the one below and save it as form_post.php
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Form Post Example</title>
<meta http-equiv="content-type" content="text/html; charset=iso-8859-1" />
</head>
<body>
<form action="form_processed.php" method="post">
First Name: <input type="text" name="first_name" /><br />
Last Name: <input type="text" name="last_name" /><br />
<input type="submit" value="GO" />
</form>
</body>
</html>
When the user clicks GO the values entered for First Name and Last Name are passed to
form_processed.php as first_name and last_name.
Make another page called form_processed.php and type the following.
<?php
$firstname = $_POST['first_name'];
$lastname = $_POST['last_name'];
echo "Welcome to the website $firstname $lastname 007";
?>
Conditional Statements
So far our PHP statements execute one after another. We need to look at code that allows us to
choose different options based on whether conditions are true or false.
You can use conditional statements in your code to do this.
IF statement:
IF (condition) {
//code to be executed if condition is true
} else {
//code to be executed if condition false
}
Change the page called form_processed.php to:
<?php
$firstname = $_POST['first_name'];
$lastname = $_POST['last_name'];
if ($firstname == ‘James’ and $lastname ==’Bond’) {
page 9
echo 'Welcome 007 super smooth secret agent';
} else {
echo "Welcome to our Website, $firstname $lastname”;
}
Remember to type the double-equals, because if you were to use a single equals sign you’d be using
the assignment operator which would assign James to the variable $firstname and Bond to
$lastname rather than compare whether $firstname equals James and $lastname equals Bond.
Loops
Sometimes we want to repeat executing statements while a condition is true. This is called a While
loop and it’s syntax is
do {
// statement(s) to execute over
// and over as long as condition
// remains true
} while (condition)
This is very useful for getting information out of a database, as we will see later. But first an example;
Enter this code and save it as while_example1.php
<?php
$tally =1;
while ($tally <11) {
echo "$tally" ;
++$tally;
}
?>
When viewed in the browser this code prints the numbers 1 to 10 across the screen.
The first line creates a variable $tally and assigns it a value of 1
The second line says that while the value of $tally is less than 11 execute the statements between
the curly brackets
The third line says print the value on the screen
The fourth line adds 1 to $tally. (This is a shortcut for $tally = $tally +1; )
Change the third line to: echo "$tally".'<br />' ; save as while_example2.php and view in your
browser.
Now we have the numbers printing 1 per line. The addition of ".'<br /> gives us this line break.
Notice we used less than, <, in the while condition. Other comparison operators you can use are; less
than or equal to, <=, greater than, >, greater than or equal to, >=,not equal, !=
The for loop is used when you know in advance how many times the script should run.
The for loop syntax is
for (init; condition; increment) {
code to be executed;
}
init: Mostly used to set a counter (but can be any code to be executed once at the beginning of the
loop)
page 10
condition: Evaluated for each loop iteration. If it evaluates to TRUE, the loop continues. If it
evaluates to FALSE, the loop ends.
increment: Mostly used to increment a counter (but can be any code to be executed at the end of the
loop)
enter this example, save it as for_loop1.php and view it in your browser.
<?php
for($tally=1;$tally<11;++$tally) {
echo “$tally<br />”;
}
?>
Loops and arrays
Loops are an easy way to access arrays because you can access each element of an array using its
key number. enter this example, save it as loops_arrays1.php and view it.
<?php
$activities=array("surfing","swimming","water skiing","fishing","walking");
for($i=0;$i<5;++$i) {
$x=$i+1;
echo 'activity '.$x.' is '.$activities[$i].'<br />';
}
Because arrays start at 0 we have to add a variable $x so we can have our output starting at 1 not 0.
activity 1 is surfing
activity 2 is swimming
activity 3 is water skiing
activity 4 is fishing
activity 5 is walking
Using PHP with MySql
So far we haven’t connected to a database. The object of this resource is to construct a website that
dynamically pulls its content out of a database to be viewed by the browser user.
We have a visitor to your site expecting to see a regular HTML page through their browser. You have
the content for your site in a table or tables residing in a MySql database that responds only to SQL
commands.
The “glue” that makes communication possible is PHP.
Back on page 2 we used a program called phpmyadmin to set up a table called activities in the
‘jamesbond’ database. We will now work with that database using PHP.
First let’s get our tutorial site setup.
Connect to the Webserver and copy the folder php_start into your sites (webserver root document)
folder.
php_start contains the file index.php, a folder with images in it and a folder called includes. In
includes there should be a CSS file called dtg_scroll.css
page 11
In this folder we will keep files that all the pages of our site might want to include. More later.
Connecting to the database
Before we can get content out of our MySQL database for inclusion in our Web page, we must first
know how to establish a connection to MySQL. PHP has no need of any special program, however;
support for connecting to MySQL is built right into the language. The following PHP function call
establishes the connection:
mysql_connect(<address>, <username>, <password>);
Where <address> is the IP address or hostname of the computer on which the MySQL server
software is running ("localhost") if running on the same computer as the Web server software), and
<username> and <password> are the same MySQL user name and password you used to connect to
the MySQL server through phpmyadmin previously.
To connect jamesbond to his database I would use mysql_connect(‘localhost','jamesbond','apple');
The mysql_connect function returns a number that says whether connection has been established.
we would then store this in a variable called $dbconn
$dbconn = mysql_connect(‘localhost','jamesbond','apple');
Because the MySql server is a different piece of software we need to check if it is available (there
could be a network problem or the MySql server might not be running).
Open your text editor, enter the following and save it into php_start\includes folder as dbconn.php
<?php
$dbconn=@mysql_connect(‘localhost','jamesbond','apple');
if (!$dbconn) {
echo 'PHP could not connect to the database server';
exit;
}
mysql_select_db('jamesbond',$dbconn);
?>
The @ symbol stops strange error messages appearing when there is no connection and we can
then display our own error message. The ! means not, so if we are not connected we echo a
message and exit.
So we have a connection to the MySql server and the line
mysql_select_db('jamesbond',$dbconn);
selects the database called jamesbond (Remember in our setup each username is the database
name).
First we will look at our home page. Open index.php in a text editor and at the top of the page
type:
<?php
require_once('includes/dbconn.php');
?>
page 12
this connects the page to the database.
Make a copy of index.php and call it activity.php.
Passing information through the navigation links
As mentioned earlier in the notes, By using the URL query string we can request a page and send
information at the same time.
Open index.php in your text editor change this code:
<li><a href="index.html">home</a></li>
<li><a href="#">relax</a></li>
<li><a href="#">on water </a></li>
<li><a href="#">in water</a></li>
<li><a href="#">on land</a></li>
<li><a href="#">in the sky</a></li>
<li><a href="#">culture</a></li>
to
<li><a href="index.php">home</a></li>
<li><a href="activity.php?act_theme=relax">relax</a></li>
<li><a href="activity.php?act_theme=on the water">on water </a></li>
<li><a href="activity.php?act_theme=in the water">in water</a></li>
<li><a href="activity.php?act_theme=on land">on land</a></li>
<li><a href="activity.php?act_theme=in the sky">in the sky</a></li>
<li><a href="activity.php?act_theme=culture">culture</a></li>
Let’s look at one of the links
<a href="activity.php?act_theme=on the water">on water </a></li>
when the user clicks this link to request the page activity.php it passes the information that the
act_theme for this link is on the water.
We then need to GET that information in the activity.php page. Open activity.php in your text editor.
add the following code to what is already there so you have this PHP code at the top.
Creating a recordset from the data passed in the URL query string
<?php
require_once('includes/dbconn.php');
$link=$_GET['act_theme'];
$navigation_sql = "SELECT * FROM activities WHERE act_theme LIKE '%".$link."%'";
$navigation_query = mysql_query($navigation_sql) or die(mysql_error());
$rsNavigation = mysql_fetch_array($navigation_query);
$navigation_check = mysql_num_rows($navigation_query);?>
$link=$_GET['act_theme']; this gets the act_theme that was passed in the URL and places it in $link.
For example if the user clicked relax on the index.php page then this would be passed to the
activity.php page and put in $link.
$navigation_sql = "SELECT * FROM activities WHERE act_theme LIKE '%".$link."%'";
$navigation_query = mysql_query($navigation_sql) or die(mysql_error());
page 13
these 2 lines query the database for act_themes’ that match the theme in $link and the result is
placed in $navigation_query.
$rsNavigation = mysql_fetch_assoc($results_query);
puts the row(s) of data found into the record set $rsNavigation as an associative array.
Displaying (echoing) data from the database
To display the data contained in the recordset $rsNavigation we use a While loop .
do {
// process the row...
} while ($rsNavigation = mysql_fetch_array($navigation_query))
A while loop will keep looping until its condition evaluates to false. This loop will occur as many times
as there are rows in the result set, with $rsNavigation taking on the value of the next row each time
the loop executes. We need to know how to get the values out of the $rsNavigation variable each
time the loop runs.
Rows of a recordset returned by mysql_fetch_array are represented as associative arrays. The
indices are named after the table columns in the recordset. If $rsNavigation is a row in our recordset,
then $rsNavigation['act_activity'] is the value in the act_activity column of that row. So here’s what our
while loop should look like if we want to print all the activities in our database:
do {
echo '<p>' . $rsNavigation['act_activity'] . '</p>';
} while ($rsNavigation = mysql_fetch_array($navigation_query))
$navigation_check = mysql_num_rows($navigation_query); This line counts the number of rows in
the record set. We use this line to check if any results were found.
In activities.php find and delete this code in the navigation div element.
<li><a href="activity.php?act_theme=relax">relax</a></li>
<li><a href="activity.php?act_theme=on the water">on water </a></li>
<li><a href="activity.php?act_theme=in the water">in water</a></li>
<li><a href="activity.php?act_theme=on land">on land</a></li>
<li><a href="activity.php?act_theme=in the sky">in the sky</a></li>
<li><a href="activity.php?act_theme=culture">culture</a></li>
leaving only this.
<div id="navigation">
<ul>
<li><a href="index.php">home</a></li>
</ul>
</div>
Now, enter this code after <li><a href="index.php">home</a></li>
<?php do { ?>
<li><?php echo $rsNavigation['act_activity']; ?></li>
<?php } while ($rsNavigation = mysql_fetch_array($navigation_query)) ?>
page 14
When you click the relax link your activity page’s navigation bar should look like
this picture on the left.
However these are not links to the other pages. To link these change the while
loop to:
<?php do { ?>
<li><p><a href ="activity.php"><?php echo $rsNavigation['act_activity']; ?></a></p></li>
<?php } while ($rsNavigation = mysql_fetch_array($navigation_query)) ?>
The relax activities all appear now in the navigation bar. But, when they are clicked we need to pass
two variables; an id in the URL so the appropriate data for that link can be retrieved and displayed
and the act_theme so we can display the initial activity for each theme.
Add the code in bold type
<li><p><a href ="activity.php?act_id=<?php echo $rsNavigation['act_id']; ?>
&act_theme=<?php echo $rsNavigation['act_theme'];?>"><?php echo
$rsNavigation['act_activity']; ?></a></p></li>
We also need to do some tidying up. If a user doesn’t link to the activity.php page from index.php and
comes directly to it, e.g. from a bookmark,the value of the act_theme variable is not passed to the
page and we get errors. We add in some code to take care of this. Remove the line
$link=$_GET['act_theme']; and add:
if (isset($_GET['act_theme'])) {
$link = $_GET['act_theme'];
} else {
$link='relax';
}
Basically, this code says: if there is a value present then assign it to $link, if not (else) assign $link
the value of relax.
Now we have the links going we need to dynamically display their data. We will display this data in
the main div of activities.php. Find the main div and delete all content so that you have only;
<div id="main">
</div>
Now let’s find the requested data.
To do this we need another recordset. We will call this $rsActivity. Enter this code after the navigation
recordset.
/* check to see if the query string contains the act_id if not give it a default value */
if (isset($_GET['act_id'])) {
$a_id = $_GET['act_id'];
} else {
$a_id=$rsNavigation['act_id'];
}
// get the activity recordset
$activity_sql="SELECT * from activities WHERE act_id=$a_id";
$activity_query= mysql_query($activity_sql) or die(mysql_error());
page 15
$rsActivity = mysql_fetch_array($activity_query);
$activity_check=mysql_fetch_array($activity_query);
When a user clicks a link on the activity.php page it passes the act_id (and the act_theme) back to
the activity.php page. We use this act_id to access all the data held in the activities table that relates
to that id.
The lines
$activity_sql="SELECT * from activities WHERE act_id=$a_id";
$activity_query= mysql_query($activity_sql) or die(mysql_error());
$rsActivity = mysql_fetch_array($activity_query);
finds the record that corresponds to the id passed in the URL query string and assigns it to the
recordset $rsActivity as an array that we can use to display the data from the activities table.
Display data from a recordset
Enter this code in the main div of the activities.php page.
<div id="main">
<?php
echo $rsActivity['act_id'];
echo $rsActivity['act_description'];
?>
</div>
This displays the data relating to the act_id that was passed to the page.
If on the home page the user clicked a theme of ‘on water’ then clicked fishing on the activities page
they would get:
The data is there in a very basic way. But we have tested the links and they work. Now we can
improve the layout of the data a little.
page 16
Change the main div code to:
<div id="main">
<center><h1><?php echo $rsActivity['act_activity'];?></h1></center>
<p><?php echo $rsActivity['act_description'];?></p>
</div>
Display an image.
Add this code in:
<div id="main">
<center><h1><?php echo $rsActivity['act_activity'];?></h1></center>
<p><?php echo $rsActivity['act_description'];?></p>
<img src="images/<?php echo $rsActivity['act_image'];?>" alt="<?php echo $rsActivity['act_activity'];?> " class
="right"/>
<p>For more information visit: <a href="<?php echo $rsActivity['act_website'];?>"><?php echo
$rsActivity['act_website'];?></a></p>
</div>
This gets the image name from the activities table and gets the image from the images folder. We
also dynamically set the alt attribute as well and using the class right from the CSS we float the
image right. Also we get the website URL from the database and link it. At this point you can look at
tidying up the “look” i.e. display the link under the description and image.
Random Information in the information column.
Next we will pull data randomly from an information table. First we will generate a random number
and get information from the database for this number.
Open index.php and after
<?php
require_once('includes/dbconn.php');
?>
Enter this code:
<?php
$random=rand(1,3);
$information_sql="SELECT * FROM information WHERE inf_id = ".$random;
$information_query=mysql_query($information_sql) or die(mysql_error());
$rsInformation= mysql_fetch_array($information_query);
The recordset $rsInformation now contains the data for one of our information records. Next we will
display it.
In the <div id=”title”> section select the text Early History of Tauranga and Mauao and replace it with;
<?php echo $rsInformation['inf_title'];?>
In the <div id=”data”> section delete all the text and replace it with;
<?php $rsInformation['inf_text'];?>
Include Files
Often PHP-based Websites need the same piece of code in several places. Include files (also known
as just includes) save you from having to write the same code over and over again. Note we have an
includes in our php_start folder; this contains our CSS code and our file for connecting to the
database, dbconn.php.
page 17
As we will have our information section on every page we will put it in here as information.php and
include it when needed.
In your text editor create a file called information.php and save it in the php_start/includes folder.
In the index.php page cut the text;
<?php
$random=rand(1,3);
$information_sql="SELECT * FROM information WHERE inf_id = ".$random;
$information_query=mysql_query($information_sql) or die(mysql_error());
$rsInformation= mysql_fetch_array($information_query);
?>
and paste it into information.php
Save the information.php file.
On the index.php page add in the code in bold.
<div id="title"><h2><?php include('includes/information.php'); echo $rsInformation['inf_heading'];
?></h2></div>
Now go to the activity.php page and make the <div id =”information”> section the same as it is in
index.php. Like this;
<div id="information">
<div id="title">
<h2><?php include('includes/information.php'); echo $rsInformation['inf_heading'];
?></h2></div>
<div id="data">
<?php echo $rsInformation['inf_text'];?>
</div>
</div>
Searching for activities
Now we will add a search that will let the user query our activity table for information and the results
page will return links in the site that might help the user.
Make a copy of index.php and name it searchresult.php. Delete the content of the <id=”main”>
section.
Using your text editor add the following code to index.php in the navigation section;
<form action="searchresult.php" method="post" id ="searchform">
<label>Search for an activity or click a link: <input type="text" size ="18" maxlength="30"
name="search" /></label><br />
<input type="submit" name="submit" value="Search" />
</form>
In dtg_scroll.css add
color: #FFFFFF; to #navigation.
Add the following code to the top of the searchresult.php page under
require_once('includes/dbconn.php');
page 18
if (!$_POST['search']) {
echo 'Please return to the home page and enter a search query';
exit;
} else {
$search=$_POST['search'];
}
This code checks to see if any data has been posted to the page from the search text field in
index.php.
If data has been posted it is assigned to the variable $search
Next we need to query our database using a SQL query string for the value of $search.
We will look in the activities table for any of the fields act_activity or act_description that contains the
word entered by the user. Enter this code after $search=$_POST[‘search’];
$result_sql="SELECT * FROM activities WHERE act_activity LIKE '%".$search."%' OR
act_description LIKE '%".$search."%'";
$result_query=mysql_query($result_sql) or die(mysql_error());
$rsResult=mysql_fetch_array($result_query);
$result_check=mysql_num_rows($result_query);
Now we have our recordset we will display the search results on the searchresult.php page. These
will be displayed as a link to the appropriate information on the activity.php page.
In the searchresult page enter the following code in the <id=”main”> section.
<h2>Search Results</h2>
<p>Please click a link for more detailed information</p>
<?php
do {?>
<li><a href="activity.php?act_id=<?php echo $rsResult['act_id'];?>&act_theme=<?php echo
$rsResult['act_theme'];?>&from_search=2"><?php echo $rsResult['act_activity']; ?></a></li>
<?php
} while ($rsResult=mysql_fetch_array($result_query))?>
This code will display the links to the records that contain the search item.
The code
?act_id=<?php echo $rsResult['act_id'];?>&act_theme=<?php echo
$rsResult['act_theme'];?>&from_search=2"
will pass to the activity page as a URL query string the act_id so the activity’s information can be
displayed. The URL also passes from_search=2 to the activity page. The activity page checks to see
if this code is present and if so it displays a back to search link in the navigation bar.
Edit the navigation div code in the activity.php page to look like this:
<div id="navigation">
<ul>
<li><a href="index.php">home</a></li>
<?php
if(isset($_GET['from_search'])) { ?>
<li><a href="javascript:history.back(-1);">Back to search results</a</li>
<?php } else {
do { ?>
page 19
<li><p><a href ="activity.php?act_id=<?php echo
$rsNavigation['act_id'];?>&act_theme=<?php echo $rsNavigation['act_theme'];?>"><?php
echo $rsNavigation['act_activity']; ?></a></p></li>
<?php } while ($rsNavigation = mysql_fetch_array($navigation_query));
if ($navigation_check == 0) {
echo "<p>Sorry no results were found, please try again.</p>";
}
}
?>
</ul>
</div>
Note, in bold, the use of a piece of javascript to link back to the search results.
Now using CSS we will remove the underline and bullet point from the links, and make them white
with a black rollover colour.
Add this code to dtg_scroll.css
#main ul li {
list-style-type:none;
}
#main ul li a {
color:#FFFFFF;
text-decoration:none;
}
#main ul li a:hover {
color:#000000;
}
Adding a form to mail or enquiry page
We wish to have a form on an enquiry page in which the user can enter information, submit it and
receive an email in response.
Copy the index.php page and rename it enquiry.php.
Delete the form for the search code in the navigation section and all the code in the main section.
Enter this code into the main section.
<h2>Enquiries</h2>
<form action="enquiry_process.php" method="post" name="fmEnquiry" id="fmEnquiry">
Name:<input name="name" type="text" id="name" /><br/>
Email:<input name="email" type="text" id="email" maxlength="30" /><br/>
Enquiry:<br/><textarea name="enquiry" cols="60" rows="10" id="enquiry"></textarea><br />
<input type="reset" name="Reset" value="Reset" />
<input type="submit" name="Submit" value="Submit inquiry" />
</form>
basically the form asks the user for their name, email address and an enquiry. The user would then
click the submit button to POST name, email and enquiry to be processed by the
enquiry_process.php page.
Copy the enquiry.php page and rename it enquiry_process.php.
page 20
Open enquiry_process.php and delete the form. Change the title to <h2>Enquiry sent</h2>. Add this
code underneath.
<p>Thank you for your enquiry <?php echo $name;?>.</p><br/>
<p>Your enquiry has been sent to <?php echo $mailto;?>.</p> <br/>
<p>Please email us at info@mtiscool.co.nz if you don't receive a response within 30 minutes.</p>
<p>Please continue browsing the site</p>
At the top of the page add this code. (This code assigns the form data ‘posted’ from enquiry.php to
the variables $name, $email and $enquiry. It then checks to see if the user has completed all fields
on the form and if they haven’t it sends them back to redo the form.
<?php
$name=$_POST['name'];
$email=$_POST['email'];
$enquiry=$_POST['enquiry'];
if ($_POST['name']== "" || $_POST['email']== "" || $_POST['enquiry']== "" ) {
header("Location: enquiry.php?error=true");
exit;
}
$mailto="martinb@mmc.school.nz"; //use your own email address here for testing
$subject="Website enquiry";
$message="Hi, my name is $name.\n\n
My email address is $email.\n\n
My enquiry is \n $enquiry";
mail($mailto,$subject,$message);
?>
The code mail($mailto,$subject,$message); does the work here.
mail is a special function in PHP that sends mail. The first parameter to mail is supposed to contain
the email address you want the form contents to be sent to, such as your own email address. The
second parameter is the "Subject" of the email message. The last parameter is the content of the
message.
Note the formatting character; \n, it means new line. Another is, \t, it means tab. You can use these
to format your message so it is easy to read.
The if(…) statement checks to see if all the fields in the form have been filled in. If the form has not
been completed the next line
header("Location: enquiry.php?error=true");
sends that error is true in the URL string.
We then add this code in the enquiry.php page to $_GET the error variable if it has been sent and
display a suitable message.
After <h2>Enquiries</h2> in the main section add
<?php if (isset($_GET['error'])) {
echo "<p>Please fill in all the fields and submit your form again</p>";}?>
page 21
Download