Creating a Database Driven Web Site

colonteeSoftware and s/w Development

Nov 4, 2013 (3 years and 7 months ago)

91 views




page

1

Creating a Database Driven Web Site


Table of Contents

DYNAMIC WEB SITE?

................................
................................
................................
................................
................................
........

1

INTRODUCTION TO PHP

................................
................................
................................
................................
................................
...

2

V
ARIABLES

................................
................................
................................
................................
................................
...........................

3

A
RRAYS

................................
................................
................................
................................
................................
................................

4

P
ASSING A VARIABLE IN

A LINK

................................
................................
................................
................................
............................

5

F
ORMS

................................
................................
................................
................................
................................
................................
..

7

C
ONDITIONAL
S
TATEMENTS

................................
................................
................................
................................
................................
.

8

M
ORE
L
OOPS

................................
................................
................................
................................
................................
........................

8

L
OOPS AND ARRAYS

................................
................................
................................
................................
................................
..............

9

USING PHP WITH MYSQL

................................
................................
................................
................................
...............................

10

BRIEF REVISION OF DA
TABASES

................................
................................
................................
................................
................

10

CONNECTING TO MYSQL

................................
................................
................................
................................
...............................

11

SQL (STRUCTURED QUER
Y LANGUAGE)

................................
................................
................................
................................
..

13

C
ONNECTING TO THE DAT
ABASE

................................
................................
................................
................................
.........................

13

DELETE

................................
................................
................................
................................
................................
........................

16

S
ELECT DATA IN A
M
Y
SQL

TABLE

................................
................................
................................
................................
.....................

17

PHP PDO
-

PREPARE AND EXECUTE

................................
................................
................................
................................
..........

18

P
ASSING INFORMATION T
HROUGH THE NAVIGATIO
N LINKS
................................
................................
................................
.................

21

C
REATING A RECORDSET
FROM THE DATA PASSED

IN THE
URL

QUERY STRING

................................
................................
..................

22

D
ISPLAYING
(
ECHOING
)

DATA FROM THE DATABA
SE

................................
................................
................................
..........................

22

D
IS
PLAY DATA FROM A REC
ORDSET

................................
................................
................................
................................
....................

26

D
ISPLAY AN IMAGE
.

................................
................................
................................
................................
................................
............

27

I
NCLUDE
F
ILES

................................
................................
................................
................................
................................
....................

28

S
EARCHING FOR ACTIVIT
IES

................................
................................
................................
................................
................................

29

A
DDING A FORM TO MAIL

OR ENQUIRY PAGE

................................
................................
................

E
RROR
!

B
OOKMARK NOT DEFINED
.



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

2


Introduction to PHP


PHP code is embedded into HTML (just like javascript). JavaScript is interpr
eted by the Web browser
once the Web page that contains the script has been downloaded

(a client
-
side scripting language)
.
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 firs
t PHP script. Type out the following code using a text editor that can save the file as plain text.


<!doctype html>

<html lang="en">

<head>

<meta charset="utf
-
8">

<title>
PHP Test

</title>

<meta name="description" content="">

<meta

name="author" content="Your Name">

</head>

<body>

<?php echo
'
<p>
Hello World
</p>
'
; ?>

<body>

</html>


Save the file as test.php.


Most of this is normal HTML code but the line between
<?php
and
?>
is written in PHP.
<?php
means
“begin PHP code,” and
?>
m
eans “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.


<!docty
pe html>

<html lang="en">

<head>

<meta charset="utf
-
8">

<title>
PHP Test

</title>

<meta name="description" content="">

<meta name="author" content="Your Name">

</head>

<body>

<p>Hello World</p>

<body>

</html>


and display it as

Hello World


For this to
happen w
e need to upload the file to our webserver so that we can view it using a
browser.

(Normally we would use a FTP program). To Upload our files we need to map our
webserver
.




page

3

In Finder, click Go, Connect to Server, choose Data_01, web, your class and

your name.

Create a folder called php_exercises and save test.php in it.

Now to “view” test.php,
open a browser and
enter the url

For example:
http://php.mmc.school.nz/301/james
bond/php_exercises/test.php



(NOTE replace jamesbond with your own username.)


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 tex
t, 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 as
signment 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
test
.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
view it in the browser.


<!
doctype html>

<html lang="en">

<head>

<meta charset="utf
-
8">

<head>

<title>PHP Test
ing
</title>

</head>

<body>

<?php echo '<p>
Hello World</p>';

$test1 = 'PHP';

echo '$test1 is great

<
br>
'; // this would output $test1 is great




page

4

echo

"$test1 is great"; // would output PHP is grea
t

?>

</body>

</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’


To create and then loop through and print the $MyCl
ass array we could use a
for

loop.


Copy the

code
below and save it as

array1.php.


Note

the use of
the break tag <br>, a html tag, and how it is

formatted within the php code.


<!doctype html>

<html lang="en">

<head>

<meta charset="utf
-
8">


<title>PHP Test</title>


</head>


<body>


<?php


$MyClass=array(
'Henry','Max','Tim');

$arrlength = count($MyClass);

/* starting at 0 ($x=0), while $x is less than


the array length ($arrlength) loop through

the code in curly brackets adding 1 to $x

each time ($x++) */


for ($x=0;$x<$arrlength;$x++)

{


echo $MyClass
[$x];


echo "<br>"
;


}

?>

</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
create

an
associative
array to assign grades to each person.


$examgrade = array('Tim' => 'merit', 'Max' => 'achieved'
, 'Henry' => 'not achieved'); ?>

To loop through and print each element of our associative array $examgrade we could use a
foreach




page

5

loop.


<?php

$examgrade=array("Tim"=>"35","Max"=>"37","Henry"=>"43");


foreach($examgrade as $x=>$x_value)


{


echo "Key="
. $x . ", Value=" . $x_value;


echo "<br>";


}

?>


(For further information on the foreach loop refer
http://www.w3schools.com/php/php_looping_for.asp

)


Save this code

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.


Passing a variable in a link

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 acti
vity.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 s
tring using an
echo
statement
.


However

there is a security hole in this code.

The security issue here stems from the fact that the
activity
.php

script is generating a
page
containing content that is under the control of the user


in this case, the $
first_
name variable.



page

6

Although the $
first_
name

variable will normally receive its value from the URL

query string in the link
on the
querystring.php

page, a malicious user could edit the URL

to send a different value for the
name variable.

To see how this would work, click the link in
querystring.php

again. Wh
en you see the
resulting page
(with the welcome message containing the
first_
name “
James
” ), take a

look at the URL in the
address bar of your browser. It should look similar to this:


http://localhost/activity.php?first_name=James


Edit the URL to insert a <b> tag before the name, and a </b> tag following the name:


http://localhost/activity.php?first_name=<b>James</b
>


You will get this:




The user can type
any HTML code into the URL, and
your PHP script includes it in the code of the
generated page without question. If

the code is as innocuous
as a <b> tag there’ s no problem, but a
malicious user could

include sophisticated JavaScript code that performed some low action like
stealing

the user’ s password. All the attacker would have to do is publish the modified link

on some
other site under t
he attacker’s control, and then entice one of your users

to click it. The attacker could
even embed the link in an email and send it to your

users. If one of y
our users clicked the link, the
attacker’
s code would be included

in your page and the trap would

be sprung!


H
ow can we generate a page containing the
first_
name without opening it up

to abuse by attackers?
The solution is to treat the value supplied for the $
first_
name variable as plain text to be displayed on
your pag
e, rather than as HTML to be in
cluded in the page’ s code.


Open activity.php and edit it to be:

Note the . before and after
htmlspecialchars($firstname,
ENT_QUOTES, 'UTF
-
8')

concatenates (joins) Welcome to the wesite to $firstname and !


<?php

$firstname = $_GET['first_name'];

echo

"Welcome to the website, " .htmlspecialchars($firstname, ENT_QUOTES, 'UTF
-
8') . "!";

?>


If the user tries to pass the <b> </b> tags again they get



Welcome to the website, <b>James</b>!


h
tmlspecialchars function did its job and converted the < and >

characters present in the provided
name into the &lt; and &gt; HTML character entities, respectively. This prevents malicious users from
injecting unwanted code into your site. If they try anything like that, the code is harmlessly displayed
as plain text

on the page.




page

7

Forms

So we have passed
a
first 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 $_POS
T arrays.


If we use $_GET the values are passed in the URL query string. However, it is not always desira
ble
to pass information in a url, especially if the information is particularly long.

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>

<html lang="en">

<head>

<meta charset="utf
-
8">

<title>Form Post Example</title>

</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>


The page will look like this (note: you can style your form using css.



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;

?>


Enter values for first name and second name and press GO to test your form.




page

8

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 (conditio
n) {

//code to be executed if condition is true

} else {

//code to be executed if condition false

}


Change the pa
ge called form_processed.php to :


<?php

$firstname = $_POST['first_name'];

$lastname = $_POST['last_name'];

if ($firstname == "James" and $
lastname =="Bond") {

echo "Welcome 007 super smooth secret agent";

} else {

echo "Welcome to the 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.


More
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 numbe
rs 1 to 10 across the screen.


The first line creates a variable $tally and assigns it a value of 1




page

9

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 eq
ual 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 exe
cuted once at the beginning of the
loop)


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 a
t 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");

fo
r($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






page

10

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.



Brief revision of

databases


We have looked at MySql, Sequential Query Language, in detail in an earlier part of the course.

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 ac
tivities, 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 username
_
datab
asename
.

W
e will start with a
databasename

called mount
(e.g. jamesbond_mount)
and set up 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.

Note:
for this exercise we are using a single table
for activities, an example of a flatfile database. (Later, we will introduce other tables and create a
relational database.)



id

activity

theme

description

website

image

1

Tasting Tour

relax

Tauranga Tasting
Tours specialise in
personally
customised wine
-
tasting tours for
small groups (up
to

19 people), of
various winemaking
regions. Relax in air
-
conditioned comfort
and enjoy wines and
sightseeing with the
personal service of a
guide who is st
ill
professionally
involved in the wine
industry. Enjoy the
countryside, talk to
the winemakers and
sample their wines.

http://www.tastingtours.co
.nz

tasting.jpg

2

Walking
Mauao

relax

Enjoy a relaxing walk
with beautiful views.
http://www.bayofplenty.co
.nz/whattoseeinthebop.as
walking.jpg




page

11

Walking tracks are
provided

on Mauao
Historic Reserve; it
takes about half an
hour to reach the
summit.

p


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.




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://php
.mmc
.school.nz/phpmyadmin

2.

In the login screen enter
your

username and password for MySql.
In this case I am using
jamesbond as my user and his password apple.

Click the Databases tab when logged in.


3.

This should give you a screen similar to this.





4.

Note

that all your databases will start with username_

So to create a database called
mount

I

would delete the 3 dots and type
mount

and click
Create. Jamesbond_
mount

will appear in the left panel. Click it and type activities as the name
of the table and 6 as the number of columns (fields).


5.

Enter the fields, type, and length/values as below. In
the
id
field

choose primary for
the index
property on the right and click A
_
I for auto increment.





page

12


Then click save.





6.

To enter data click
on activities (in the left column) then click
Insert.
Now

enter your data (from
the
table above)



Click Go.

Then enter the second record and so on.


7.

However, to save time we have provided a text file, activity.sql, which you can import.

First, click
username_mount (link up the top)
, select the activities table and
drop

it.


Then

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.






page

13

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.


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 (`
activ
ity` LIKE '%swimming%' OR
`
description` LIKE '%swimming%' );


This would select all (* = all) records in the table activities where swimming i
s “contained” in the fields
activity OR
description.
Note:

% is called a ‘wildcard’. If we ran the query,


SELECT
* FROM `activities` WHERE

`
activity` LIKE 's%';


it would give us all
the records where the field
activity starts with s.


Web Site Tutorial Setup



Connect to the Webserver
(php.mmc.school.nz/301/username)
and copy the folder
mount_example

into your
webserver
folder
.

mount
_example

contains the file index.php, a folder with images in it and a folder called includes.

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
.

We will learn how t
o use the PDO (PHP Data Object)

extension to connect to a database
.

T
he PDO
extension that we’
ll use to connect to and work with a MySQL database is designed in the object
oriented programming style. What this means is that rather than simply calling a function to connect
to MySQL and then calling other functions that use that connection, we must f
irst create a PDO
(
PHP
Data Objects)
object that will represent our database connection, and then use the
features of that
object to work
with the database.

Creating an object is a lot like calling a function.


Here’ s how you use PDO to establish a
connection to a MySQL server:


$pdo = new PDO('mysql:host=localhost;dbname=
username_
mount', '
username', 'password
');


In any case, PDO
has
three arguments:

1.

A string specifying the type of database (mysql: ), the hostname of the server


(host=localhost;
), and the name of the database (dbname=
username_
mount ).

2.

The MySQL username you want PHP to use.

3.

The MySQL password for that username.



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).

This would cause a PHP
Exception error.


If you don

t catch an exception, PHP will stop running your PHP script and display a spectacularly
ugly error message. That error message will
even reveal the code of your script that threw the error.
In this case, that code contains your MySQL username and password, so it

s especially important to



page

14

avoid the error message being seen by users!

To catch an exception, you should surround the code
that might throw an exception

with a try
-
catch statement :


try

{


do something risky

}

catch (ExceptionType $e)

{


handle the exception

}


You can think of a
try

-
catch

statement like an
if

-
else

statement, except that the second block of
code is what happens if the first block of code fails to run.


Here is the code to connect. Open your text editor, enter this code and save it in the includes folder
as connect.php.

(Note: use your own username n
ot jamesbond)

<?php

try

{


$pdo = new PDO('mysql:host=localhost;dbname=
jamesbond_
mount', '
jamesbond
',
'
apple
'
);

}

catch (PDOException $e)

{


echo

'Unable to connect to the database server.';

exit;

}


echo

'Database connection established.';

?>


check the connection by putting
a url similar to
this url into your browser.

php.mmc.school.nz/301/username/mount_example/includes/connect.php


We don’t want the text
'Database connection established.'

a
ppearing every time we connect to the
database.
So delete
echo

'Database connection established.';

from
the connect.php code and save
it.


Inserting Data into and
Selecting Data from a Table


After the connection to
the
database is successfully created and the PDO object instance is set, the
object can

be used to perform SQL queries.

The SQL queries with PDO can be made in two ways:

-

directly using "exec()", and "query()" methods,

-

or with the

prepare() ... execute()

statement.

The first is simpler, in this
tutorial

we’ll look at the

exec

method.


The

queries that modify rows in the table, but do not return a result set with rows and columns
(INSERT, UPDATE, and DELETE), are sent with exec(), this method returns the number of
affected rows, or FALSE on error.


e.g. $count = $pdo
-
>exec("SQL Query");





page

15

Qu
eries that select rows (SELECT) and return a result set with rows and columns are sent with
the query() method. In case of error, returns FALSE.

$res = $pdo
-
>query("SQL Query");


As

an example let’
s insert 2

record
s

into our activities table (in the userna
me_mount database)


Open
a new file

in a text editor and
save it as tutorial_1.php in the mount_example folder on the
webserver.

Copy the following code into tutorial_1.php
:


<?php

//first connect to the database

require_once('includes/connect.php');

//
Define an insert query

$sql = "INSERT INTO `activities` (`activity`, `theme`, `description`, `website`, `image`)
VALUES


('Stand Up Paddleboard', 'on the water', 'learn to paddle in our pristine harbour
...','http://www.sup.co.nz','sup.jpg'),


('
Wind Surfing', 'on the water', 'Fly and surf over the waters by Fergusson
Park','http://windsurf.co.nz','windsurf.jpg')";


$count = $pdo
-
>exec($sql);


// If data added ($count not false) displays the number of rows added

if($count !== false) echo 'Number

of rows added: '. $count;


?>


When run in the webserver you will get something similar to this:


ß


Check your activities table. It should have these 2 records added at the end.
Note:

we didn’t
insert an id. Because id is set to auto increment when we a
dd rows (records) to the table mysql
automatically numbers the records.


To get the last auto
-
inserted "id" (in a AUTO_INCREMENT PRIMARY KEY column), use the
lastInsertId() method.

$pdo
-
>lastInsertId();


-

When you add multiple rows in the same INSERT query,

this method will return the ID of
the first added row.


UPDATE, and DELETE a
re SQL instructions that change

data in a table, but not return a result
set with rows and columns. They can be executed in the same way as INSERT, with the exec()
method.


UPDATE


The data in the rows of a MySQL table can be modified with the SQL command INSERT.




page

16

Syntax:


$objPDO
-
>exec("UPDATE table_name SET column1
='value1', column2
='value2' WHERE
condition");


The next examp
le changes data in the columns
activity

and
website
, whe
re id is 3; in the
activities

tab
le
.


Copy the code below and save it as tu
t
orial_2.php:


<?php

//first connect to the database

require_once('includes/connect.php');


// changes data in "activity" and "website" colummns, where id=3


$sql = "UPDATE activities


SET activity='Mount Main Beach', website='http://www.bestoftauranga.com/mount
-
maunganui
-
main
-
beach.html'


WHERE id=3";


$count = $pdo
-
>exec($sql);

// If the query is succesfully performed ($count not false)

if($count !== f
alse) echo 'Affected rows : '. $count; // Shows the number of affected rows

?>


This is a screen shot of this script after it has been run



Now check you
r

activities table to see the change.


DELETE

The

DELETE

instruction deletes rows in a table.

Syntax:

$objPDO
-
>exec("DELETE FROM table_name

WHERE
condition
");

In this example we will delete the rows we inserted earlier.


Save this code as tutorial_3.php and run it.


<?php

//first connect to the database

require_once('includes/connect.php');


// Delete rows in activities, according to the value in the activity column




page

17


$sql = "DELETE FROM activities WHERE activity IN('Stand Up Paddleboard', 'Wind
Surfing')";


$count = $pdo
-
>exec($sql);

// If the query is succesfully performed ($count not fal
se)

if($count !== false) echo 'Affected rows : '. $count; // Shows the number of affected rows

?>


Check
in activities table
to see the rows (records) are deleted.


Next we will learn how to select and get data stored in a MySQL table, using the PDO
query()
method.


Select data in a MySQL table

Once you have created and added some data in a MYSQL table, you can use a

SELECT

query, with
the PDO

query()

method to get that

data.

The query() method returns a result set with data returned by MySQL, o
r
FALSE in case of error.

In this example

we will use the activities table.


Save the following code as tutorial_4.php


<?php

//first connect to the database

require_once('includes/connect.php');


// Define and perform the SQL SELECT query


$sql = "SELECT *
FROM activities WHERE id IN(1, 3)";


$result = $pdo
-
>query($sql);


// If the SQL query is succesfully performed ($result not false)


if($result !== false) {


$cols = $result
-
>columnCount(); // Number of returned columns



echo 'Number of re
turned columns: '. $cols. '<br />';



// Parse the result set


foreach($result as $row) {


echo $row['id']. '
-

'. $row['activity']. '
-

'. $row['description']. '
-

'. $row['website']. '<br />';


}


}

?>


The "columnCount()" method returns
the number of columns in the result set. Notice that this
method is applied at the instance which performed the query (in this case, the $result variable).




Note:
The data is not formatted in columns as it is in the database table. You would use html
and
css code to layout the page effectively.

At this point we are only interested in the php code.


The result set can also be parsed with the WHILE statement, but in this case you should apply
the

fetch

method:




page

18


while($row = $result
-
>fetch()) {

// ... PHP

code

}

Copy the code below and save as tutorial_5.php


<?php

//first connect to the database

require_once('includes/connect.php');


// Define and perform the SQL SELECT query


$sql = "SELECT * FROM activities";


$result = $pdo
-
>query($sql);


// Parse the result set


while($row = $result
-
>fetch(PDO::FETCH_ASSOC)) {


echo $row['id']. '
-

'. $row['activity']. '
-

'. $row['description']. '
-

'. $row['website']. '<br />';


}

?>

PHP PDO
-

prepare and execute

With the exec() and query(
) methods the SQL command is automatically executed.

There is another variant, too. With PDO it's posible to "prep
are" a SQL command without
executing
it immediately.

This is accomplished with the

prepare()

method.

-

The

prepare()

method takes as argument
an SQL statement and returns a

PDOStatement

object. This
object contains an

execute()method that will execute the SQL statement when it is called.

-

The

execute()

returns TRUE, or FALSE in case of error.


So,

prepare()

can prepare an SQL statement to be ex
ecuted by the

execute()

method, using this
syntax:

$sqlprep = $PDOconnection
-
>prepare("SQL statement");

$sqlprep
-
>execute(Array
);

-

The "SQL statement"
-

can be any valid SQL statement: INSERT, SELECT, UPDATE, DELETE.

-

The

Array

argument from the execute
() method
-

is optional. It's an array of values with as many
elements as there are bound parameters in the SQL statement being executed, specified in the
prepare().


The prepared SQL instruction can be used to be executed multiple times, with different va
lues.

You
will see this

illustrated in

the
code

below.


The examples presented it this tutorial use the
activities

table

as

in the previous
tutorials.


Save this as tutorial_6_prepare.php


<?php

//first connect to the database

require_once('includes/connect.php');

// Define the SQL statement that will be applied in prepare()


$sql = "SELECT id, activity FROM activities WHERE id = :id OR activity = :activity";


$sqlprep = $pdo
-
>prepare($sql); // Prepares and stores the S
QL statement in $sqlprep


// The array with values that must be added in the SQL instruction (for ':id', and ':activity')




page

19


$ar_val = array('id'=>2, 'activity'=>'Baywave');



// If the prepared SQL is succesfully executed with execute()


if($sqlprep
-
>e
xecute($ar_val)) {


// gets and displays the data returned by MySQL


while($row = $sqlprep
-
>fetch()) echo $row['id'].'
-

'.$row['activity'].'<br />';


}


/* Execute again the prepared SQL, with other values */


echo 'The 2nd select<br />';



// The a
rray with values that must be added in the prepared SQL (for ':id', and ':category')


$ar_val = array('id'=>8, 'activity'=>'Kayaking');


// Execute the SQL instruction


if($sqlprep
-
>execute($ar_val)) {


// gets and displays the data returned by MySQL


while($row = $sqlprep
-
>fetch()) echo $row['id'].'
-

'.$row['activity'].'<br />';


}

?>

In this statement:


$sql = "SELECT id, activity FROM activities WHERE id = :id OR activity =
:activity";
,
":id" and ":
activity
" are parameter markers for the values

added in the Array passed
in the execute(). Each parameter marker is associated with the value of the Array element with
the same key
-
name ('id' and
'
activity
'
).

-

You must include a unique parameter marker for each value you wish to pass in to the
statement when you call the "execute()" method.


Due to this notation you can use the same prepared SQL command multiple times, with
different values. This technique optimizes the performance of your application, and helps to
prevent SQL injection

because
the "prepare()" method eliminate
s

the need to manually
quote the parameters.


Note:
The SQL statement is sent to the database server when you do prepare(), and the
parameters are sent separately when you do execute().



Another Prepare example using the
bindValue method

We can bind values to queries and at the very least reduce the risk of sql injection.


We include a variable name within a query and we bind a value to that.

Do this by preparing an sql query. We use the prepare method of the PDO object a
nd store this in
$result


Consider this code:


<?php

//first connect to the database

require_once('includes/connect.php');

// Define the SQL statement that will be applied in prepare()


$sql = "SELECT * FROM activities


WHERE (activity LIKE '%swimming%' OR description LIKE '%swimming%' );";

$result = $pdo
-
>prepare($sql);

?>


The $sql will return all rows that have swimming in the activity or description columns.





page

20

Prepare, much like the query method, returns the pdo s
tatement object and allows us to make use of
the methods that object has. For example we are going to use the bindvalue method.


Enter this code and save into mount_example folder on the webserver as tutorial_6_prepare_2.php


<?php

//first connect to the
database

require_once('includes/connect.php');

// Define the SQL statement that will be applied in prepare()


$sql = "SELECT * FROM activities


WHERE (activity LIKE '%swimming%' OR description LIKE '%swimming%' );";

$result = $pdo
-
>prepare($sql); //pre
pares and stores the SQL statement in $result



$rows=$result
-
>fetchALL(pdo::FETCH_ASSOC);


// Parse the result set

foreach($result as $row) {


echo $row['id']. '
-

'. $row['activity']. '
-

'. $row['theme']. '
-

'. $row['website']. '<br />';

}

?>


Whe
n we run this script we get a blank page because the prepare method doesn’t actually execute
the query.

There is another method that is part of the pdo statement object called execute()


Instead of having our wildcard %swimming% we are going to replace it
with a parameter variable
called :search. Here is our SQL now:


$sql = "SELECT * FROM activities


WHERE (activity LIKE :search OR description LIKE :search );";


And add these two lines after $result= …


$result
-
>bindValue(
'
:search
'
,

'
%swimming%
'
,PDO::PA
RAM_STR);

$result
-
>execute();


Here is the complete code to enter and run.


<?php

//first connect to the database

require_once('includes/connect.php');

/* Define the SQL statement that will be applied in prepare() note the use of :search parameter
*/


$sql = "SELECT * FROM activities WHERE (activity LIKE :search OR description LIKE
:search) ";

$result = $pdo
-
>prepare($sql); //prepares and stores the SQL statement in $result

/*we use the bindValue method of the pdo statement object to bind a value (%swimming%)

to the parameter :search and then use the execute method to execute the query stored in
$result */

$result
-
>bindValue(':search','%swimming%',PDO::PARAM_STR);

$result
-
>

execute();


// Parse the result set




page

21

foreach($result as $row) {


echo $row['id']. '
-

'. $row['activity']. '
-

'. $row['theme']. '
-

'. $row['website']. '<br />';

}

?>


The resulting dataset is



Using our mount_example website


In mount_example

m
ake 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?
theme=relax">relax</a></li>

<li><a href="activity.php?
theme=on the water">on water </a></li>


<li><a href="activity.php?
theme=in the water">
in water</a></li>


<li><a href="activity.php?
theme=on land">on land</a></li>


<li><a href="activity.php?
theme=in the sky">in the sky</a></li>


<li><a href="activity.php?
theme=culture">culture</a></li>


Let’s look at one of the links

<a
href="activity.php?
theme=on the water">on water </a></li>

when the user clicks this link to request the page activity.php it passe
s the information that the t
heme
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 and

add the following code to what is already there so you have
this PHP code at the top.




page

22

Creating a recordset from the data passed in the URL query string

<?php

require_once('includes/connect
.php');

//

this gets the
theme that was passed in

the URL and places it in $link

$link=$_GET['
theme'];

//this helps to prevent sql injection

$link=htm
lspecialchars($link,ENT_QUOTES,

'
UTF
-
8
'
);

//prepare the navigation result set

$navigation_sql = "SEL
ECT * FROM activi
ties WHERE
theme LIKE
:
theme
";

$r
esult
Navigation =
$pdo
-
> prepare(
$navigation_sql
)
;

//bind the query

$result
Navigation
-
>bindValue(':
theme','%'.$link
.'%',PDO::PARAM_STR);

//execute the query

$result
Navigation

-
> execute();

?>



Displaying (echoing) data
from the database

To display the dat
a contained in the recordset $result
Navigation we

could
use a
foreach

loop .

foreach($result
Navigation

as $row) {


echo $row['id']. '
-

'. $row['activity']. '
-

'. $row['theme']. '
-

'. $row['website']. '<br />';

}


This would display id, activity,

theme and website
.
This loop will occur as many times as there are
rows in the result set, with $r
e
s
ult
Navigation 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 $r
e
s
ult
Navigation variable each time the
loop runs.

Rows of the

recordset returned are represented as associative arrays. The indices are named after
the table columns in the recordset. If $r
e
s
ult
Navigation is a row in our recordset, then
in the
above
loop $row['
act
ivity'] is the value in the
activity column of that row.



In activities.php
we will create a navigation sub menu
, called “activity menu”,

to hold
a link to
each
theme’s activities.
.

Copy this code into activities.php under the line:


<div id ="content">


<nav id="activity_menu">



<ul>



<?php foreach($resultNavigation as $row) { ?>



<li><?php echo $row['activity'];?></li> <br /><?php

} ?>


</ul>

</nav>


If

you click the relax link
in index.php

it passes theme=“relax” to
activity
.php.

The php script at the top
of activity.php Gets “relax” from the URL and puts it into a variable called $link. htmlspecialchars
then removes any malicious code. The activities table in the database is then queried to
find all
rows (records) that have a “re
lax” theme. The prepare method of the PDO is then used to prepare
the resulting dataset ($resultNavigation). The bindValue method is then used to “bind” the query
to the parameter. (This helps prevent sql injection). The execute method is then used to actu
ally
put the results into the variable $resultNavigation). So far nothing is displayed on the webpage.





page

23

When we click relax on the index.php page the activities page will give us something like this:



The activities that have relax as a theme appear down

the left with
out

bullet points. We actually want
these to be links that will display the activity’s description etc when we click it. Also

we need to
style this sub menu so it doesn’t push the other columns down the page.

(Remember this is part
of testing

to see if our code works. Then we can pretty it up).

Change the style.css
code

(#activity_menu and any bold code is new or changed)


#activity_menu {


display:table
-
cell;


width: 15
%;


vertical
-
align: top;


padding
-
top: 50px;

}


section {


display:table
-
c
ell;


vertical
-
align: top;


width:50%;


background
-
color: #11A298;


padding:10px;


font: 14px Domine,Verdana, Arial, Helvetica, sans
-
serif;

}



article {


display:table
-
cell;


vertical
-
align: top;


width: 30%;


background
-
color:#5c85c3;


color:white;


font
-
size:14px;


margin:0px;


padding:10px;

}

Save these changes to style.css and view your page now.





page

24



The relax activities all appear now in the navigation bar.

Now co
nsider this code:


<li><?php echo $row['activity'];?></li> <br />

But
we want each list element to be a hyperlink so change the code
above
to:

<li><a href="activity.php"><?php echo $row['ac
tivity'];?></a></li> <br />



This will give this:




Notice how the same styling is applied to the activity_menu as the main menu.

However, it needs a bit of styling.

First, the white border seems to be doubled up.

Put this code in style.css in
#activity_menu
,
border
-
top:none;

And add in this code to style the activity_menu


#activity_menu ul li{


padding:25px 0px;


font
-
size: 1em;

}



Now
when we click relax from index.php
we get:




page

25



You need to c
hange the colour of the activity links for a better design look.

Now we need to display the appropriate information about the activity that is clicked and also display
default information
about an activity (In this case when the user clicks relax from index.php we
need to go

to the activity page and have information abou
t Tasting Tour in the first column (
the
section element)




A way to do this is
to pass two variables; an id in the URL so

the appropriate data for that link can be
retr
ieved and displayed and the
theme so we can display the initial activity for each theme.


In Index.
php and activity.php replace this content

of the main navigation element

with this code:


<li><
a href="activity.php?theme=relax&amp;id=1">relax</a></li>


<li><a href="activity.php?theme=on the water&amp;id=6">on water </a></li>


<li><a href="activity.php?theme=in the water&amp;id=2">in water</a></li>


<li><a href="activity.php?theme=on land&amp;i
d=12">on land</a></li>


<li><a href="activity.php?theme=in the sky&amp;id=16">in the sky</a></li>


<li><a href="acti
vity.php?theme=culture&amp;id=18
">culture</a></li>


We

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 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=$_GE
T['
theme'];

and add
:


// this gets the theme that was passed in the URL and places it in $link

if (isset($_GET['theme'])) {


$link = $_GET['theme'];

} else {


$link='relax';




page

26

}

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 let’s find the requested data.

To do this we need another recordset. We will call this $r
esult
Activity. Enter this code after the
line
$resultNavigation
-
> execute();

in the php code at the top of activi
ty.php.


/* check to see if the URL contains the id if not give it a default value */

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


$id = $_GET['id'];

} else {


$id=4;

}

$id=htmlspecialchars($id,ENT_QUOTES, 'UTF
-
8');

// get the activity recordset

$activity_sql="SELECT * from

activities WHERE id=:id";

$resultActivity = $pdo
-
> prepare($activity_sql);

//bind the query

$resultActivity
-
>bindValue(':id',$id,PDO::PARAM_STR);

//execute the query

$resultActivity
-
> execute();

When a user clicks a link on the acti
vity.php page it pass
es the id (and the
theme) back to the
act
ivity.php page. We use this
id to access all the data held in the activities table that relates to that
id.

The lines

$activity_sql="SELECT * from activities WHERE id=:id";

$resultActivity = $pdo
-
> prepare($activi
ty_sql);

//bind the query

$resultActivity
-
>bindValue(':id',$id,PDO::PARAM_STR);

//execute the query

$resultActivity
-
> execute();


finds the record that corresponds to the id passed in the URL query string and assigns it to the
recordset $r
e
s
ult
Activity
as an array that we can use to display the data from the activities table.

Display data from a recordset

Now we have the links going we need to dynamically display their data. We will d
isplay this data in
the section element

of
activities
.php. Find the
sec
tion element

and
delete all
content so that you
have only;



<section>




</section>

Add this code so that the section element


<section>






<?php foreach($resultActivity as $row) {




echo '<h1>'.$row['activity'].'</h1>'.$row['description'];



} ?>





</section>

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’ they would get:





page

27




The data is there in a very basic way. But we have tested the links and they work.
From
here you
could improve the layout
.


Display an image.

Add
the bold

code in
to the section element
:



<section>






<?php foreach($resultActivity as $row) {




echo '<h1>'.$row['activity'].'</h1>'.$row['description'];








$
image_name

= $row['image'];




} ?>



<p><img src="images/<?php echo $image_name; ?>" alt="<?php echo
$image_name;?>" /></p>



</section>

$row[
'
image
'
], in the php foreach loop gets the image name from the activities table. This is then
stored in $image_name.
($image_name =
$row['image'];)

Outside of the php foreach loop we use html and php code to display the image in the webpage.

<p><img src="images/<?php echo $image_name; ?>" alt="<?php echo $image_name;?>" /></p>

If the picture doesn’t display or a reader is used for a bl
ind person the alt tag displays or reads the
image name.


Random Information

in the information column.

Next we will pull data randomly from an information table.

Import the information.sql file into your username_mount database.


First we will generate a random number and get information from the database for this number.


Open index.php and
before
<!DOCTYPE html>

insert this code.


<?php

//first connect to the database

require_once('includes/connect.php');

?>




page

28



In the
article

element

of index.php delete everything from <article> to </article> and enter this code

so that we now have
:


<article>



<?php



//generate a random number from 1 to 3



$random=rand(1,3);



//query the information table using the random number chosen



$information_sql="SELECT * FROM information WHERE id = ".$random;




$result = $pdo
-
>query($information_sql);



//if we get a result set display the heading and data



if($result !== false) {




// Parse the result set




foreach($result as $row) {




echo '<h2>'.$row['heading'].'</h2>'.'<br />'. $row['text'];




}





}



?>

</article>

so each time we go to the “home” page random data will appear in the article element.

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
mount_example

folder; this contains our file for connecting to the database,
connect
.php.

As we wil
l 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
mount_example
/includes
folder.

In the
article element of the
ind
ex.php page
cut

the text;





<?php




//generate a random number from 1 to 3




$random=rand(1,3);




//query the information table using the random number chosen




$information_sql="SELECT * FROM information WHERE id = ".$random;





$result = $pdo
-
>
query($information_sql);




//if we get a result set display the heading and data




if($result !== false) {








// Parse the result set





foreach($result as $row) {





echo '<h2>'.$row['heading'].'</h2>'.'<br />'. $row['text'];





}






}




?>

and paste it into information.php


Save the information.php file in the includes folder.




page

29


On the index.php page
in the article element
add in the code in bold.


<article>

<?php include('includes/information.php'); ?>

</article>


Now go to
the

activity.php page do the same to the article element there.


<article>

<?php include('includes/information.php'); ?>

</article>


Test each page to see that the “information” column changes randomly.

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
search
_
result.php
. Delete the content of the
<section>
element.


Using your
text editor add the following code to inde
x.php in the navigation section under


<li><a href="activity.php?theme=culture&amp;id=18">culture</a></li>



<div id="search">

<form action="search_result.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>


</div>

In
style
.css add
a this code for the search div


#search form{


padding
-
top: 50px;


font
-
family:verdana, arial, helvetica, sans
-
serif;


font
-
size:13px;


font
-
style: bold;

}


Add the following code to the top of the searchresult.php page

under
require_once('includes/
conn
ect
.php');


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




page

30


Next

we need to query our database using a SQL query string for the value of $search.

We will look in the activities
table in the fields activity or
description that contains the word entered
by the user. Enter this code after $search=$_POST[‘search’];


/* De
fine the SQL statement that will be applied in prepare() note the use of :search parameter */


$sql = "SELECT * FROM activities WHERE (activity LIKE :search OR description LIKE :search) ";

$search_result = $pdo
-
>prepare($sql); //prepares and stores the
SQL statement in $result

/*we use the bindValue method of the pdo statement object to bind a value (%swimming%)

to the parameter :search and then use the execute method to execute the query stored in $result */

$search_result
-
>bindValue(':search','%'.$sea
rch.'%',PDO::PARAM_STR);

$search_result
-
> execute();

Now we have our recordset we will display the search results on the search
_
result.php page. These
will be displayed as a link to the appropriate information on the activity.php page.


In the search
_
result page enter the following code in the
section element.




<section>




<h2>Search Results</h2>



<p>Please click a link for more detailed information</p>



<ul>



<?php



// Parse the result set



foreach($search_result as $row) { ?>



<li><a
href="activity.php?id=<?php echo $row['id'];?>&amp;t
heme=<?php echo
$row['theme']?>;
&amp;from_search=2
">




<?php echo $row['activity'];?></a></li> <br /><?php



} ?>




</ul>



</section>

This code will display the links to the
rows (
records
)

that contain

the search item.

The code


?id=<?php echo $row['id'];?>&amp;t
heme=<?php echo $row['theme']?>;&amp;from_search=2
">


will pass to the activity pag
e as a URL query string the
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.


Add this code to the
<na
v id="activity_menu">

navigation

element

in the
activity.php

page to look
like this:

<nav id="activity_menu">



<ul>



<?php foreach($resultNavigation as $row) { ?>



<li><a href="activity.php?id=<?php echo $row['id'];?>&amp;theme=<?php echo
$row['theme'];?>">




<?php echo $row['activity'];?></a></li> <br />




<?php



}





if(isset($_GET['from_search'])) { ?>



<li><a href="javascript:history.back(
-
1);">Back to search results</a</li>



<?php } ?>





</ul>


</nav>

?>


</ul>

</div>


Note, in
bold
, the use of a piece of javascript to link back to the search results.





page

31

When we view this in a browser all the text is underlined.



To remove this underline place this code in style.css under the body rule.

a:link {


text
-
decoration: none;

}


This is just one way to handle the search. It is not that eloquent. It would be better to disp
lay the
search results within the search_result.php page. Also there are other links showing that have
nothing to do with what we are searching for.

As an
exer
cise/challenge

develop a more efficient way of handling our simple search.