Sei sulla pagina 1di 34

Guide 106

Version 2.4

Accessing databases from


the World Wide Web
The ITS provides a computer on which databases can be stored. If you
provide a WWW page that displays a form, then, when the user clicks on the
form’s submit button, a request can be sent to the database computer that
queries a table of the database. The results that are returned can be displayed
on a WWW page. Such WWW pages need to be written in a mix of the
languages HTML, PHP and SQL.
This document introduces the HTML that is necessary to produce a form; the
PHP that is necessary to submit a request to a database and interpret the
results that the request generates; and the SQL that is necessary to specify a
query to a database.
Although it is necessary to use HTML, PHP and SQL to allow a person
anywhere in the world to use a browser to query a database, the document
indicates ways in which Microsoft Access can be used to update a database
that is stored on the database server.

Contents
1. Introduction
2. Using PHP to generate WWW pages dynamically
3. Using WWW pages that create and manipulate databases
4. Using SQL in PHP scripts to manipulate MySQL databases
5. Using Microsoft Access with MySQL databases
6. Resources
Document code: Guide 106
Title: Accessing databases from the World Wide Web
Version: 2.4
Date: 04/03/2010
Produced by: University of Durham Information Technology Service

Copyright © 20102010 University of Durham Information Technology


Service

Conventions:
In this document, the following conventions are used:
A typewriter font is used for what you see on the screen.
A bold typewriter font is used to represent the actual characters you type at
the keyboard.
A slanted typewriter font is used for items such as filenames which you should
replace with particular instances.
A bold font is used to indicate named keys on the keyboard, for example,
Esc and Enter, represent the keys marked Esc and Enter, respectively.
A bold font is also used where a technical term or command name is used in
the text.
Where two keys are separated by a forward slash (as in Ctrl/B, for example),
press and hold down the first key (Ctrl), tap the second (B), and then release
the first key.
Contents
1 Introduction ...................................................................................................... 1
1.1 Accessing large amounts of data from the WWW ......................................... 1
1.2 Providing a Microsoft Access database on the WWW .................................. 1
1.3 The drawbacks of providing a .mdb file......................................................... 1
1.4 An alternative approach ................................................................................ 1
2 Using PHP to generate WWW pages dynamically.......................................... 2
2.1 What is PHP? ............................................................................................... 2
2.2 A simple example of a PHP script................................................................. 3
2.3 Using variables in PHP ................................................................................. 3
2.4 Using a for command to create loops ........................................................... 3
2.5 Using an HTML form to supply data ............................................................. 5
2.6 Using an if command to make decisions ....................................................... 6
2.7 Calling pre-defined functions ........................................................................ 7
2.8 Providing output in the form of tables ........................................................... 7
2.9 Using literal HTML and combining print commands .................................... 10
3 Using WWW pages that create and manipulate databases ......................... 11
3.1 Introduction ................................................................................................ 11
3.2 Choosing to use MySQL for storing databases ........................................... 11
3.3 Administering MySQL from the web ........................................................... 11
3.4 Creating a database ................................................................................... 12
3.5 Creating a table within a database.............................................................. 12
3.5.1 Supplying the type for a column........................................................... 13
3.5.2 Supplying other attributes for a new column ........................................ 13
3.6 Displaying the headings of the columns of a table ...................................... 14
3.7 Adding a new column ................................................................................. 14
3.8 Inserting a new row into a table .................................................................. 14
3.9 Displaying data in a table............................................................................ 14
3.10 Dropping a table ......................................................................................... 14
3.11 Dropping a database .................................................................................. 14
4 Using SQL in PHP scripts to manipulate MySQL databases ....................... 14
4.1 The basics of SQL ...................................................................................... 14
4.1.1 What is SQL? ...................................................................................... 14
4.1.2 Accessing MySQL directly ................................................................... 15
4.1.3 Creating, dropping and using databases ............................................. 15
4.1.4 Creating, altering and dropping tables ................................................. 15
4.1.5 Inserting a new row of data into a table ............................................... 16
4.1.6 Querying a database ........................................................................... 16
4.1.7 Removing rows from a database ......................................................... 16
4.2 Accessing a MySQL server from PHP ........................................................ 16
4.3 Providing a WWW page to query a table .................................................... 17
4.4 Providing a WWW page to insert a new row ............................................... 20
4.5 Providing a WWW page to delete a row ..................................................... 21
5 Using Microsoft Access with MySQL databases ......................................... 23
5.1 Introducing the two ways in which Access can be used .............................. 23
5.2 Installing a MySQL ODBC driver on a Windows PC ................................... 24
5.3 Transferring a table to a MySQL database from Access ............................. 24
5.3.1 Creating a database in Microsoft Access 2007 .................................... 24
5.3.2 Creating a database in Microsoft Access 2003 .................................... 25
5.3.3 Creating a MySQL database ............................................................... 26

Guide 106: Accessing databases from the World Wide Webb i


5.3.4 Transferring a table from Access to a MySQL database...................... 26
5.3.5 Updating a table that already exists .................................................... 27
5.4 Using a MySQL table from Access ............................................................. 28
6 Resources ...................................................................................................... 29
6.1 PHP ........................................................................................................... 29
6.2 SQL ........................................................................................................... 29
6.3 MySQL ....................................................................................................... 30
6.4 Using PHP and MySQL .............................................................................. 30

ii Guide 106: Accessing databases from the World Wide Web


1 Introduction

1.1 Accessing large amounts of data from the WWW


Conventional WWW pages (written in HTML) are an inappropriate way of
storing large amounts of data. Such data is often stored in a database, and
so the question arises as to whether it is possible to put the database on
the WWW and have it queried by browsers anywhere in the world.

1.2 Providing a Microsoft Access database on the WWW


If you maintain the database using Microsoft Access, it is possible to put
the .mdb file alongside the HTML files that are in your public_html
directory. When the user of a WWW browser clicks on a link to this .mdb
file, the browser will ask the user what they want to do with the file.
The actual behaviour at this point depends on the browser and how it has
been configured. With Internet Explorer on the Networked PC service, the
user will be asked whether they want to open the file (in Microsoft Access)
or save it. For example, you can examine the Access database at the URL
http://www.dur.ac.uk/resources/its/info/guides/106/stucol.mdb (users
of Access 2007 will have to add the location of the database to their
Trusted Locations in the Microsoft Access Trust Centre).
As the user is working with a copy of the database, any changes that they
inadvertently make to it will not affect the actual .mdb file that is in your
public_html directory. And, whenever you use Access to update your
database, you will need to re-transfer the .mdb file to your public_html
directory in order to make the new version available on the WWW.
By this means, you can easily make a database available to anyone
browsing the WWW (provided you are familiar with Microsoft Access).

1.3 The drawbacks of providing a .mdb file


Although this looks like an attractive solution, there are three drawbacks.
Firstly, it assumes that the person accessing the .mdb file has Microsoft
Access on their computer. This will not be the case if they have a Mac or a
computer running Linux or Unix. And even if they have an appropriate
computer they may not have a copy of Microsoft Access. The second
drawback concerns different versions of Access: if a database is produced
using the latest version of Access, it is likely to be inaccessible to a person
who has an earlier version. The third drawback concerns the size of the
database: as the .mdb file has to be downloaded to the visitor’s PC, this
will be an issue if it is a large database.
Of course, the first two drawbacks are unimportant in situations where you
know that the people accessing the .mdb file have the appropriate version
of Access. For example, if you are a lecturer at the University of Durham
wanting a database to be accessible by your students, you can provide an
Access database in your public_html directory because Access is
accessible from Internet Explorer on the Networked PC service.

1.4 An alternative approach


If you do not wish to rely on the user having Microsoft Access, and an
appropriate version of Access, you need to move away from providing the
data of the database in a .mdb file. The ITS has a computer that acts as a

Guide 106: Accessing databases from the World Wide Webb 1


database server (using some software called MySQL), and it is possible for
you to store databases on this database server.
So, an alternative approach is to provide an HTML form on the WWW for
the user to complete, and when the user clicks on the form’s Submit button,
the data on the form is used to create a query which is sent to this
database server. One way in which you can get this to work is to write your
WWW pages in a mixture of HTML and a server-side scripting language
called PHP that generates a query in SQL (a database query language).
Section 2 of this document looks at PHP and how to include PHP
instructions in a WWW page, and the first part of Section 4 of this
document looks at how to write SQL.
If you adopt this alternative approach, there are three methods by which
you can update the database on the database server. First, you can
produce an appropriate HTML form on the WWW and then, when you click
on the form’s Submit button, an update request is sent to the database
server. The HTML, PHP and SQL needed to accomplish this is looked at in
the second part of Section 4 of this document.
Both of the other two methods involve the use of Microsoft Access. Either
you maintain the data in Access on your PC and transfer the tables to the
database server whenever you update them on the PC, or you can arrange
for the tables in Access to be linked to those on the database server so that
whenever you make a change in Access you are updating the live data,
i.e., the data that is accessible from the WWW. We look at these two
methods in Section 5 of this document.
So you have a choice of these three methods for updating the data that
people see from the WWW.
However, you will need to become familiar with HTML and PHP and SQL in
order to provide the means by which people can query your databases from
the WWW. Any forms you have for a Microsoft Access database will be of
no use to you.

2 Using PHP to generate WWW pages dynamically

2.1 What is PHP?


PHP is what is known as a server-side scripting language. When a visitor to
a WWW page visits a page that is a PHP page, the WWW server gets a
PHP interpreter to examine the page. The PHP interpreter will produce
some HTML which is then shipped by the WWW server to the visitor's
computer and is interpreted by his/her WWW browser.
PHP’s manual says that “PHP’s syntax is borrowed primarily from C. Java
and Perl have also influenced the syntax”.
As well as the usual constructs that most languages have, in PHP:
you can read from files, write to files and execute system commands;
you can produce graphics output;
you can do sophisticated mathematical calculations;
you can send mail; you can interrogate an IMAP server;
you can access LDAP servers; you can access XML documents;

2 Guide 106: Accessing databases from the World Wide Web


you can access most of the popular database servers including
Oracle, Generic ODBC, Microsoft SQL Server and MySQL.

2.2 A simple example of a PHP script


Here is a simple example of a script written in the PHP language:
1: <?php
2: print "<p>Hello Fred. I hope you are OK.</p>\n";
3: ?>

Note: the line numbers (and the trailing colon) do not form part of the script.
They are just included to enable these notes to refer to specific lines of the
scripts.
Suppose that the file hello1.php contains the above script. It can be
executed by passing it to a WWW server that understands PHP. This can
be done by using a WWW browser with the URL
http://www.dur.ac.uk/resources/its/info/guides/106/hello1.php
Because the filename ends in .php, the WWW server will pass this to a
PHP interpreter which understands the bits inside the <?php and ?>
brackets. The print command of PHP just outputs the string that follows
print. The string ends with \n which means move to a new line (in the HTML
output). So the PHP interpreter will output the following HTML and this is
what the user’s browser sees:
4: <p>Hello Fred. I hope you are OK.</p>

2.3 Using variables in PHP


There are many facilities in PHP besides the print command. We first look
at how you can use variables in a PHP script.
In many ways, a variable is like the memory location of a phone, an entry in
an address book of a mailer, or a bookmark used with a WWW browser: it
is a place where a value can be stored. So we could set up a variable
containing a person’s name as shown in this PHP script (which you will find
in the file hello2.php):
5: <?php
6: $firstname = "Fred";
7: print "<p>Hello $firstname. I hope you are OK.</p>\n";
8: ?>

When the PHP interpreter sees this, it will execute the assignment
command that stores the string "Fred" in the variable firstname and then it
will obey the print command. In the print command, it will replace the
$firstname by the value of the variable. So the result is the same piece of
HTML that was produced by the hello1.php script, i.e.:
9: <p>Hello Fred. I hope you are OK.</p>

You can execute the above script using


http://www.dur.ac.uk/resources/its/info/guides/106/hello2.php

2.4 Using a for command to create loops


Scripts are very boring if they just consist of a sequence of commands
where each command is always executed and is always executed once.
PHP has two kinds of commands that make scripts more exciting! Later, we

Guide 106: Accessing databases from the World Wide Webb 3


will look at if commands, used to make decisions in a script. However, we
first consider for commands, which are used to execute a group of
commands a number of times.
For example, suppose we want to output four paragraphs of HTML each of
which contains the hello paragraph that was given above. One way of doing
this is shown by the following PHP script (which is in the file hello3.php):
10: <?php
11: print "<p>Here is an introductory paragraph.</p>\n";
12: $firstname = "Fred";
13: for ($paranum = 0; $paranum<4; $paranum++)
14: {
15: print "<p>Hello $firstname. I hope you are OK.</p>\n";
16: }
17: print "<p>Here is a final paragraph.</p>\n";
18: ?>

You can execute the above script using


http://www.dur.ac.uk/resources/its/info/guides/106/hello3.php
In the middle of this script, there is a for command. It consists of a line that
starts with for followed by some lines that are surrounded by a pair of curly
brackets:
14: {
15: print "<p>Hello $firstname. I hope you are OK.</p>\n";
16: }

The lines that are surrounded by a pair of curly brackets form the body of
the for command. It is these lines that are repeatedly executed. The other
part of a for command contains something like:
13: for ($paranum = 0; $paranum<4; $paranum++)

Although there are many possibilities for this part, most for commands
introduce a variable that is initialized to either 0 or 1 and is increased by 1
just before each re-execution of the body. How does the loop terminate?
Well, each time, just before executing the body, a condition is checked, and
the loop terminates if the condition is false.
So, in the above example, the $paranum = 0 is the bit that causes a variable
called paranum to be initialized to 0. The $paranum<4 is the condition, the bit
that checks, in this case, whether the variable paranum has a value less
than 4. And $paranum++ is a bit of shorthand that increases the value of
paranum by 1.
As mentioned earlier, the WWW server gets a PHP interpreter to
understand the text that is in a PHP script. After the PHP interpreter has
done its job, the WWW server sends the HTML that the PHP interpreter
has produced to the WWW browser. For this example, the browser would
see:
19: <p>Here is an introductory paragraph.</p>
20: <p>Hello Fred. I hope you are OK.</p>
21: <p>Hello Fred. I hope you are OK.</p>
22: <p>Hello Fred. I hope you are OK.</p>
23: <p>Hello Fred. I hope you are OK.</p>
24: <p>Here is a final paragraph.</p>

4 Guide 106: Accessing databases from the World Wide Web


Because the string of each print command includes a \n, this HTML
appears on 6 lines. If the occurrences of \n were to be omitted, only one
(rather long) line of HTML would be produced.
Instead of having the 4 appear in the text of the for command, we could use
a variable that has the value 4. This is shown in the hello4.php script that
is given here:
25: <?php
26: print "<p>Here is an introductory paragraph.</p>\n";
27: $firstname = "Fred";
28: $numparas = 4;
29: for ($paranum = 0; $paranum<$numparas; $paranum++)
30: {
31: print "<p>Hello $firstname. I hope you are OK.</p>\n";
32: }
33: print "<p>Here is a final paragraph.</p>\n";
34: ?>

You can execute the above script using


http://www.dur.ac.uk/resources/its/info/guides/106/hello4.php

2.5 Using an HTML form to supply data


Often the author of a WWW page will want to get data for his/her PHP
script from the person visiting the WWW page. This can be done by using
an HTML form (e.g., hello5.htm):
35: <form method="post" action="hello5.php">
36: Type in a person's name:
37: <input type="text" name="firstname" />
38: <br />
39: Type in the number of paragraphs to be generated:
40: <input type="text" name="numparas" />
41: <br />
42: <input type="submit" value="submit form" />
43: </form>

When a WWW page containing these HTML instructions is accessed, the


browser will display a page containing a form. This form includes two boxes
and asks the person visiting the page to fill these boxes with a person’s
name and the number of paragraphs to be generated.
A page with this form is at
http://www.dur.ac.uk/resources/its/info/guides/106/hello5.htm
When the user clicks on the submit form button, the program mentioned in
the form’s action attribute will get executed. With this example, this means
that the PHP script hello5.php gets executed.
The values that the user has typed in the two boxes can be accessed in the
PHP script by using the $_POST array and names that the boxes have
been given in the form. So, because the form has used the names firstname
and numparas for these boxes, a PHP script can access these as
$_POST['firstname'] and $_POST['numparas'].
A script that does this is the hello5.php script shown here:

Guide 106: Accessing databases from the World Wide Webb 5


44: <?php
45: $firstname = $_POST['firstname'];
46: $numparas = $_POST['numparas'];
47: print "<p>Here is an introductory paragraph.</p>\n";
48: for ($paranum = 0; $paranum<$numparas; $paranum++)
49: {
50: print "<p>Hello $firstname. I hope you are OK.</p>\n";
51: }
52: print "<p>Here is a final paragraph.</p>\n";
53: ?>

2.6 Using an if command to make decisions


What happens if the person visiting the page types the value 0 in the
numparas box? When the for command of the PHP script gets executed,
paranum will be given the value 0 and then the condition
$paranum<$numparas will be checked. Because numparas also has the
value 0, this condition will be false. This means that the loop will terminate.
So the for command is finished and the command of the body never got
executed.
If you want, you can detect that the user typed in an inappropriate value by
using an if command. The hello6.php script demonstrates this:
54: <?php
55: $firstname = $_POST['firstname'];
56: $numparas = $_POST['numparas'];
57: print "<p>Here is an introductory paragraph.</p>\n";
58: if ($numparas<=0)
59: {
60: print "<p>That is a silly value for the number of paragraphs!</p>\n";
61: }
62: else
63: {
64: for ($paranum = 0; $paranum<$numparas; $paranum++)
65: {
66: print "<p>Hello $firstname. I hope you are OK.</p>\n";
67: }
68: }
69: print "<p>Here is a final paragraph.</p>\n";
70: ?>

This script assumes that it is triggered into action by an HTML form similar
to the hello5.htm given above. A page with this form is at
http://www.dur.ac.uk/resources/its/info/guides/106/hello6.htm
Here is how this if command works. First, the condition $numparas<=0 is
evaluated; this is being used to check whether the value of numparas is less
than or equal to zero. If it is, then the command(s) inside:
59: {
60: print "<p>That is a silly value for the number of paragraphs!</p>\n";
61: }

get executed; otherwise those of:

6 Guide 106: Accessing databases from the World Wide Web


63: {
64: for ($paranum = 0; $paranum<$numparas; $paranum++)
65: {
66: print "<p>Hello $firstname. I hope you are OK.</p>\n";
67: }
68: }

get executed.

2.7 Calling pre-defined functions


When a sequence of commands do some well-defined task, it is useful to
put them together and give them a name: if we do this we are creating a
function.
As has already been indicated, PHP allows you to access a lot of different
things. Because of this, PHP has a large number of functions that are built
into the language. This is the main reason why the manual for PHP is
enormous. Section 6 (of this document) contains details of how you can
access this manual. However, most of the sections of the manual you can
ignore until you need the topic described by the section.
We now look at a simple example of a pre-defined function. There is a pre-
defined function, called date, that can return a string containing a date and
time. Obviously, you will not want it to always return the same date and
time, and you will want the string describing the date and time to be in a
format that you choose. The way in which you can vary what a function
does each time you use it is to provide arguments (or parameters) to the
function.
When you use the date function, you provide as a first argument a string
describing the particular format in which you are interested. An optional
second argument gives the point in time in which you are interested.
However, when date is used with only one argument, it returns details about
the current date and time. The following script is in today1.php:
71: <?php
72: $today = date("Y-m-d");
73: print "<p>Today's date is $today.</p>\n";
74: ?>

This example uses the format "Y-m-d". This particular format gives a string
like 2008-04-21. The call of the function appears on the right-hand side of
an assignment command, and the string that is produced is assigned to the
variable called today. You can execute the above script using
http://www.dur.ac.uk/resources/its/info/guides/106/today1.php

2.8 Providing output in the form of tables


One of the things we are going to do with functions is to query databases.
For example, we might be querying a database that contains details about
people. Such a query may lead to more than one person satisfying the
query. If so, we may want to output a table of information, each line of
which describes one of the people. Before moving on to how we can query
databases, we first look at the HTML instructions that are needed to output
information in the form of tables.
The HTML instructions used to indicate that you want to display information
in the form of a table are the <table> and </table> tags. At the start and end

Guide 106: Accessing databases from the World Wide Webb 7


of each row of the table, you need <tr> and </tr> tags. And you need to
surround each cell of the table with <td> and </td> tags.
So, if you wanted to output a three line table, you could use HTML
instructions like:
75: <table>
76: <tr> <td> degrees fahrenheit </td> <td> degrees centigrade </td> </tr>
77: <tr> <td> 175 </td> <td> 80 </td> </tr>
78: <tr> <td> 200 </td> <td> 100 </td> </tr>
79: </table>

Here is one other useful bit of HTML which we will use when displaying
tables: if instead of <td> you use <td bgcolor="yellow"> you can arrange for
that cell to be output with a yellow background.
So, suppose we want to calculate and output a table giving the Centigrade
equivalent of the Fahrenheit temperatures in the range 175 to 525 at steps
of 25 degrees Fahrenheit, with the Centigrade values rounded to the
nearest 10 degrees. Such tables used to appear in cookery books.
As we need to calculate a Centigrade figure for each of the Fahrenheit
figures, it makes sense to use a for command which looks a bit like this:
foreach Fahrenheit figure
{
calculate the Centigrade figure
output the Fahrenheit figure
output the Centigrade figure
}

Here is the complete code of the PHP script cookery1.php:

8 Guide 106: Accessing databases from the World Wide Web


80: <?php
81: $numrows = 15;
82: $fahrenheit = 175;
83: print "<html>\n";
84: print "<head>\n";
85: print "<title>A conversion table for cooking</title>\n";
86: print "</head>\n";
87: print "<body>\n";
88: print "<table>\n";
89: print "<tr>";
90: print "<td bgcolor=\"yellow\">";
91: print "degrees fahrenheit";
92: print "</td>";
93: print "<td bgcolor=\"yellow\">";
94: print "degrees centigrade";
95: print "</td>";
96: print "</tr>\n";
97: for ($rownum = 0; $rownum<$numrows; $rownum++)
98: {
99: $centigrade = ($fahrenheit - 32.0)*5.0/9.0;
100: $centigrade = 10.0*round($centigrade/10.0);
101: print "<tr>";
102: print "<td>";
103: print $fahrenheit;
104: print "</td>";
105: print "<td>";
106: print $centigrade;
107: print "</td>";
108: print "</tr>\n";
109: $fahrenheit = $fahrenheit + 25;
110: }
111: print "</table>\n";
112: print "</body>\n";
113: print "</html>\n";
114: ?>

You can execute the above script using


http://www.dur.ac.uk/resources/its/info/guides/106/cookery1.php
This script outputs a table where the first row acts as a heading for the
other rows. Because we want the background of these headings to be in
yellow, we need to use <td bgcolor="yellow">. However, because we are
using PHP’s print command to output these characters, and because we
have to put these characters in a string, each occurrence of " in the string
has to be replaced by \". So the script uses:
90: print "<td bgcolor=\"yellow\">";

rather than:
115: print "<td bgcolor="yellow">";

The script uses a function called round. This function returns a value which
is the nearest integer to the value of its argument.
Besides generating the HTML instructions for the table, the script also
generates the instructions:

Guide 106: Accessing databases from the World Wide Webb 9


116: <html>
117: <head>
118: <title>A conversion table for cooking</title>
119: </head>
120: <body>

at the start, and:


121: </body>
122: </html>

at the end. To save space, in the previous examples given in these notes,
we have failed to provide these instructions. Although most WWW
browsers will accept the minimal set of HTML instructions shown in earlier
examples, it is better style to provide the fuller set shown in this example.

2.9 Using literal HTML and combining print commands


When generating plain HTML in a PHP script, it can be inconvenient to use
large numbers of print commands. An alternative is to place literal HTML
outside of <?php … ?> sections. The script cookery2.php achieves the
same effect as the previous script, but using literal HTML, and combining
together some of the remaining print commands, making it shorter and
easier to read.
Here is the complete code of the PHP script cookery2.php:
123: <html>
124: <head>
125: <title>A conversion table for cooking</title>
126: </head>
127: <body>
128: <table>
129: <tr>
130: <td bgcolor="yellow">degrees fahrenheit</td>
131: <td bgcolor="yellow">degrees centigrade</td>
132: </tr>
133: <?php
134: $numrows = 15;
135: $fahrenheit = 175;
136: for ($rownum = 0; $rownum<$numrows; $rownum++)
137: {
138: $centigrade = ($fahrenheit - 32.0)*5.0/9.0;
139: $centigrade = 10.0*round($centigrade/10.0);
140: print "<tr><td>$fahrenheit</td><td>$centigrade</td></tr>\n";
141: $fahrenheit = $fahrenheit + 25;
142: }
143: ?>
144: </table>
145: </body>
146: </html>

You can execute the above script using


http://www.dur.ac.uk/resources/its/info/guides/106/cookery2.php

10 Guide 106: Accessing databases from the World Wide Web


3 Using WWW pages that create and manipulate databases

3.1 Introduction
In Section 4 of these notes, we will look at how we can manipulate
databases from a PHP script triggered from an HTML form on a WWW
page. We will produce the files containing the HTML forms and PHP scripts
ourselves.
However, to give you some idea about what can be done, in this section of
the notes, we will create a database, add a table to the database, insert
some values into this table, remove a row of the table, and so on. We will
do this by accessing some WWW pages that have already been created:
they have HTML forms and PHP scripts that do this work for us.

3.2 Choosing to use MySQL for storing databases


Although Microsoft’s Access is ubiquitous on PCs, it is an inappropriate
product for making databases accessible from the WWW. Anyway, you
probably would not want anyone anywhere in the world to be accessing
your PC. For more robust and intense use, there are other database
products such as Oracle, Microsoft SQL Server, and so on. Some (such as
Microsoft’s SQL Server) that run on Windows only, others run on
computers that use Unix or Linux.
Besides the products listed above which cost money, there are a number of
database products which are free. One of these is called MySQL (not to be
confused with a rival product called MSQL). MySQL is a robust up to date
implementation which can handle large databases.
So in this course we will be storing our data in MySQL databases. These
databases are looked after by a MySQL server that is running on one of the
ITS Unix computers. The computer that is used for this is known as
myeusql.dur.ac.uk.
Having said all that, do not worry if your data is already in a Microsoft
Access database: in Section 5 of this document, we will see how we can
interoperate between Access databases and MySQL databases.

3.3 Administering MySQL from the web


You will need a username and password in order to use the MySQL server.
You can request these from the IT Service Desk. The username is likely to
be the same as the username that is used to access most of the other IT
systems at the University. However, for security reasons, the password
should be kept different from the password you use to access other IT
systems at the University (such as the one you use to access NPCS or
Unix).
So, assuming you know your MySQL username and password:
1 Go to
https://www.dur.ac.uk/php.myadmin/password/phpMyAdmin/
and enter your ITS username and password if required.

Guide 106: Accessing databases from the World Wide Webb 11


2 Enter your MySQL username and password, and choose
mysql.dur.ac.uk or myeusql.dur.ac.uk from the drop-down list,
then click Go.
A list of databases can be obtained by clicking on the Databases link;
clicking on one of the databases allows administrative functions to be
performed. At all times, you can return to the phpmyadmin home page by
clicking the icon of a house on the top left of the screen. The following
sections will assume that you have logged into phpmyadmin as described
above.

3.4 Creating a database


By default, the MySQL server has been configured so that you can create
any databases you want provided that the name of the database begins
with Pdxy3fab_ where dxy3fab is replaced by your username. Each of
these databases can be updated by you from anywhere in the world
provided you give your MySQL password. Also, each of these databases
can be queried by anyone anywhere in the world (without the need to
supply a password).
1Enter the name of the database you want to create in the box under
Create new database.
Although this must start with a capital letter P followed by your username
(in lower-case), followed by an underscore character (i.e., _), the remaining
characters may be chosen by you. This name can only contain letters,
digits, underscores and dollars, and it must not be more than 64 characters
long. The name is case sensitive: this means that for any letters of the
name you must be consistent on whether you use a capital letter or a small
letter for every use of that name.
2 Click on the Create button.
3 The WWW page should be replaced by one saying that the
database has been created.

3.5 Creating a table within a database


Firstly, select the database to which you want to add a table (section 3.3). If
the database already contains some tables, they will be listed. To the right
of each table are a number of icons which allow you to perform
administrative functions on the table. Underneath any listed tables, there is
a box to create a new table. You will need to give the table a name. The
names of tables have the same restrictions as those for databases.
However, unlike database names, table names do not have to begin with
something like Pdxy3fab_.
1 Fill in the Name box with the name you have chosen.
2 Fill in the number of fields you wish the table to have (this can
always be changed later on).
3 Click Go.
You will be taken to a screen where you need to enter column details. The
Field row allows you to give the columns names. Click Save when you
have added your column details.

12 Guide 106: Accessing databases from the World Wide Web


3.5.1 Supplying the type for a column
The types that are supported can be grouped into three categories: numeric
types, date and time types, and string (or character) types. For the time-
being, all you really need to know is:
The type VARCHAR can be used to represent a variable-length string
of up to a specified number of characters in the range 1 to 255. You
should note that values stored in such columns have any trailing
spaces removed, and that (unless you specify otherwise) they are
sorted and compared in case-insensitive fashion.
The type INT can be used for whole number values.
The type DOUBLE can be used for floating point values,
i.e., numerical values that have a decimal point.
As values of type DOUBLE are only stored approximately, use a type
like DECIMAL for monetary values and fill in a length like 10,2 in the
Length/Values field. The values 10 and 2 mean that a total of
10 characters are used with 2 after the decimal point. Values other
than 10 and 2 can be used to suit your requirements.
There are several types for representing dates and times: they
include DATE, DATETIME, TIMESTAMP, TIME and YEAR.

3.5.2 Supplying other attributes for a new column


Besides giving the name and the type of a column, you may give some
other attributes:
A column is called a NOT NULL column if it has the attribute NOT
NULL. If there is no NOT NULL attribute, the column is said to be a
NULL column.
A DEFAULT attribute such as ' ' or 0 or 0.0 specifies the default value
the column should have it is not given a value. If no DEFAULT value is
given for a column and the column is a NULL column, the default
value is the value NULL. If no DEFAULT value is given for a column
and the column is declared as a NOT NULL column, the default value
for the column is: the empty string for string types; the next value for
AUTO_INCREMENT columns; the value 0 for numeric types; and an
appropriate zero for date and time types.
An integer column may have the additional attribute
AUTO_INCREMENT (found in the Extra drop-down box). When you
insert a value of NULL into an AUTO_INCREMENT column, the column
is set to one more than the largest value that is currently used for this
column. Note that a table can have only one AUTO_INCREMENT
column, and that the column must be indexed.
A column can have the PRIMARY KEY attribute, selected by choosing
the radio button on the primary key row (marked with an icon of a
table with a key on top). A table can have only one column with this
attribute. An error occurs if you try to add a new row to a table with a
key that matches an existing row.

Guide 106: Accessing databases from the World Wide Webb 13


3.6 Displaying the headings of the columns of a table
We now move on to see how we can query or update the table that you
have just created. Select your database and click the Structure icon next
to your table (the second icon along next to the table name); if you have
just created a new table you will already be on this page. The screen will
display a list of columns, their types and some extra information.

3.7 Adding a new column


Underneath the list of columns is an option to add fields to the database
table. Enter the number of fields you wish to add and click Go, then follow
the instructions in section 3.5.

3.8 Inserting a new row into a table


Select your database and click the Insert icon next to your table (the fourth
icon along next to the table name). The page asks you to fill in a Value for
each of the fields that you have in your table. By default, you will be taken
back to the previous page after entering your data; if you want to continue
adding data, select Insert another new row from the drop-down list above
the Go button. Click Go to add your new data to your table.

3.9 Displaying data in a table


Select your database and click the Browse icon next to your table (the first
icon along). The data in your table will be displayed, with the options of
editing or deleting each row.

3.10 Dropping a table


To remove a table from your database, the table needs to be dropped. To
do this, select your database, and click the Drop icon next to your table
(shown as a red X). You will be asked if you really want to drop the table;
click OK to do so. The table (and any contents) will be removed from the
database.

3.11 Dropping a database


To drop, or delete, an entire database, select your database, and click the
red Drop link from right of the links on the top of the screen. You will be
asked to confirm if you want to destroy the whole databases; click OK to do
so. Phpmyadmin will confirm that your database has been dropped, and
return you to its home page.

4 Using SQL in PHP scripts to manipulate MySQL databases

4.1 The basics of SQL

4.1.1 What is SQL?


The Structured Query Language (or SQL) is a language for use with
relational databases. It has been evolving since the early 1980’s. There is a
standard version of SQL known as SQL:2003. Although SQL’s name
implies that it is just used for querying databases, it actually also has
facilities for creating new databases and modifying the data of existing
databases.

14 Guide 106: Accessing databases from the World Wide Web


SQL is a very comprehensive language and this document will only have
room to describe a small part of it.

4.1.2 Accessing MySQL directly


It is possible to issue SQL commands directly to MySQL using the MySQL
monitor. To access this from a Unix or Linux system (such as vega), enter:
mysql –h myeusql –u dxy3fab –p

where dxy3fab is replaced by your username. MySQL will then prompt you
for your password. Any SQL statements you type in here must finish with a
semicolon.

4.1.3 Creating, dropping and using databases


Here is the SQL statement to create a database called Pdxy3fab_prices:
CREATE DATABASE Pdxy3fab_prices

And the SQL statement to drop (i.e., destroy) the database


Pdxy3fab_prices is:
DROP DATABASE IF EXISTS Pdxy3fab_prices

where the IF EXISTS part is optional.


If you want to perform a number of transactions on a database, it is useful
to issue the SQL statement:
USE Pdxy3fab_prices

This means that, by default, subsequent transactions are to take place on


Pdxy3fab_prices.

4.1.4 Creating, altering and dropping tables


The SQL statement to create a new table in a database is the CREATE
TABLE statement. Besides giving the name of the table, you also have to
describe the columns of the table. For each column, you need to give a
name and a type, and you can also give some attributes. Some brief details
about types and attributes were given in Sections 3.5.1 and 3.5.2. Here is
an example of a CREATE TABLE statement:
CREATE TABLE consum (ID INT NOT NULL PRIMARY KEY,
goods VARCHAR(40) DEFAULT ' ',
price DECIMAL(8,2) DEFAULT 0.0)

Here a table called consum is created: it has three columns, called ID, goods
and price. The first column can contain an integer value, the second can
contain strings up to 40 characters long, whereas the third can contain a
numerical value.
Later, you can alter the design of the table, e.g., by adding an extra column,
dropping a column, changing the type of a column, and so on. For example:
ALTER TABLE consum ADD COLUMN number_in_stock INT DEFAULT 0

The SQL statement to drop a table is:


DROP TABLE IF EXISTS consum

where, once again, the IF EXISTS part is optional.

Guide 106: Accessing databases from the World Wide Webb 15


4.1.5 Inserting a new row of data into a table
Having created a table, it is then possible at any time to add rows
containing data to the table. This is done using the INSERT statement:
INSERT INTO consum SET ID=12, goods='3.5 inch Floppy disk', price=0.3

Because we have not supplied a value for the number_in_stock column, this
row will have a number_in_stock value of 0, because an attribute for this
column (that was given earlier) said that the default value is 0.

4.1.6 Querying a database


One of the most used SQL statements is the SELECT statement: it is used
to inspect a table of information. The statement:
SELECT goods, price FROM consum

would look at the table consum and produce (a new table containing) the
goods and prices from all the rows of the table consum. If you want the
values of all of the columns, use:
SELECT * FROM consum

A where definition can be added to a SELECT statement to constrain what


rows get returned. For example:
SELECT goods FROM consum WHERE price <1.0

would just deliver the names of those products whose price is less than 1.0.
Another example is:
SELECT * FROM consum WHERE goods='3.5 inch Floppy disk'

would deliver all the columns that have a goods column having the value
'3.5 inch Floppy disk'. If you wish to give the option of supplying only part of a
value (or you are uncertain as to what the column contains!), you can
instead use:
SELECT * FROM consum WHERE goods LIKE '%Floppy%'

where the % means that any characters may appear at this point.
And it is possible to use a SELECT statement that accesses more than one
table. Suppose the usernames table has columns labelled employeenumber,
surname, initials and username, and the phones table has columns labelled
employeenumber and phonenumber. You could then use:
SELECT surname, initials, username, phonenumber FROM usernames, phones
WHERE usernames.employeenumber=phones.employeenumber

4.1.7 Removing rows from a database


SQL has a DELETE statement that can be used to remove one or more
rows from a table. An example is:
DELETE FROM consum WHERE goods LIKE '%Floppy%'

4.2 Accessing a MySQL server from PHP


Section 2 of this document discussed PHP, a server-side scripting
language that can enable us to produce WWW pages whose content is
dynamically generated. Section 4.1 discussed SQL, a language for
manipulating databases. So we can now move on to produce WWW pages

16 Guide 106: Accessing databases from the World Wide Web


that can manipulate databases. To do this, all we have to do is call the
appropriate functions of PHP that enable us to pass SQL statements to a
MySQL database.
The PHP scripts that follow use these functions:
mysql_connect which connects to a MySQL server running on some
computer supplying a username and a password. For example:
$connect_result = mysql_connect("myeusql.dur.ac.uk", "dxy3fab", "ind1g0");

Typically, the server will be configured so that these are required


when a user wants to change a database but an anonymous name
can be used when the user only wishes to inspect the database:
$connect_result = mysql_connect("myeusql.dur.ac.uk", "nobody", "");

mysql_db_query which executes a given SQL query on a given


database. For example:
$query_result = mysql_db_query("Pdcl0bjc_prices",
"select * from consum where price<1.0");

mysql_num_rows which finds out how many rows there are in the result
of a query:
$numrows = mysql_num_rows($query_result);

mysql_result which returns the value of a given column of a given row


of the result of a query:
print mysql_result($query_result, $rownum, "price");

4.3 Providing a WWW page to query a table


Suppose we have created a database called Pdcl0bjc_prices; that a table
of this database is called consum; and that this table has columns called ID,
goods and price. The idea is that each row of this table contains the details
about an item of consumables that is for sale; the columns headed goods
and price contain the description and the price of the item and the column
headed ID contains a unique number for this item.
If we want to supply a WWW page that can be used to query this table, we
need first to obtain from the person visiting the page the name of the item
of consumables in which he/she is interested. We can do this by providing
a WWW page that contains:
147: <html><body>
148: <form method="post" action="pricesquery.php">
149: To search for an item of consumables:
150: <br />type in part of the name of the item (e.g., Series IV):
151: <input type="text" name="goods" />
152: <br /><input type="submit" value="run query" />
153: </form>
154: </body></html>

A page with this form is at


http://www.dur.ac.uk/resources/its/info/guides/106/pricesquery.htm
When the visitor to the page clicks on the run query button, the
pricesquery.php script will be executed. The code of this script appears
below.

Guide 106: Accessing databases from the World Wide Webb 17


This script first uses mysql_connect to attempt to connect to the MySQL
server. If that succeeds, it assigns to the query variable a string containing
the characters:
SELECT * FROM consum WHERE goods like '%$goods%'

i.e., a string containing the query in which the visitor is interested. It then
calls the function mysql_db_query to send this SELECT statement to the
database Pdcl0bjc_prices. If this is successful, the variable query_result
now contains a pointer to a temporary table that has just been created;
it contains only those rows satisfying the query.
The call of mysql_num_rows finds out how many rows are in this table. And if
this is not zero, the script generates an HTML table containing the rows of
data that are in this table. It does this by using a for command to wander
through each row of the table. For each row, it generates HTML containing
the contents of the ID, goods and price columns.

18 Guide 106: Accessing databases from the World Wide Web


155: <?php
156: print "<html><body>\n";
157: $goods = $_POST['goods'];
158: $connect_result = mysql_connect("myeusql.dur.ac.uk", "nobody", "");
159: if (! $connect_result)
160: {
161: print "<p>There is a problem in connecting to the server</p>\n";
162: print "</body></html>\n";
163: return;
164: }
165: $query = "SELECT * FROM consum WHERE goods like '%$goods%'";
166: $query_result = mysql_db_query("Pdcl0bjc_prices", $query);
167: if (! $query_result)
168: {
169: print "<p>There is a problem with querying the table.</p>\n";
170: print "</body></html>\n";
171: return;
172: }
173: $numrows = mysql_num_rows($query_result);
174: if ($numrows==0)
175: {
176: print "<p>There are no consumables with a name of $goods</p>\n";
177: print "</body></html>\n";
178: return;
179: }
180: print "<table border=\"1\">\n";
181: for ($rownum = 0; $rownum<$numrows; $rownum++)
182: {
183: print "<tr>\n";
184: print "<td align=\"right\">\n";
185: print mysql_result($query_result, $rownum, "ID");
186: print "</td>\n";
187: print "<td>\n";
188: print mysql_result($query_result, $rownum, "goods");
189: print "</td>\n";
190: print "<td bgcolor=\"yellow\" align=\"right\">\n";
191: printf("&pound;%01.2f", mysql_result($query_result, $rownum, "price"));
192: print "</td>\n";
193: print "</tr>\n";
194: }
195: print "</table>\n";
196: print "</body></html>\n";
197: ?>

Guide 106: Accessing databases from the World Wide Webb 19


4.4 Providing a WWW page to insert a new row
We can proceed in a similar way if we want to insert a new row in this table.
Besides a box asking for the name of the item, the HTML form also has a
box asking for details of its price. And, as we wish to change the database,
we will need to supply the MySQL password that is appropriate for this
database. So the form also has a box asking for the password:
198: <html><body>
199: <form method="post" action="pricesinsert.php">
200: To insert a new item of consumables:
201: <br />Enter your password:<input type="password" name="password" />
202: <br />Enter the name of the item:<input type="text" name="goods" />
203: <br />Enter the price of the item in pounds, e.g., <code>18.45</code>
204: <input type="text" name="price" />
205: <br /><input type="submit" value="update consumables" />
206: </form>
207: </body></html>

A page with this form is at


http://www.dur.ac.uk/resources/its/info/guides/106/pricesinsert.htm
When the person using this form clicks on the update consumables
button, the script in the file pricesinsert.php gets executed. This time,
because it wants to update the database, the script’s call of mysql_connect
needs to provide a username and a password: for the password, the script
uses whatever was typed into the password box. And, this time, because the
query is actually an INSERT, the call of mysql_db_query returns either true
or false depending on whether the INSERT was successful or not. The
script outputs an appropriate message:
208: <?php
209: print "<html><body>\n";
210: $password = $_POST['password'];
211: $password = $_POST['goods'];
212: $password = $_POST['price'];
213: $connect_result = mysql_connect("myeusql.dur.ac.uk", "dcl0bjc", "$password");
214: if (! $connect_result)
215: {
216: print "<p>There is a problem in connecting to the server</p>\n";
217: print "</body></html>\n";
218: return;
219: }
220: $query = "INSERT INTO consum SET goods='$goods', price=$price";
221: $query_result = mysql_db_query("Pdcl0bjc_prices", $query);
222: if (! $query_result)
223: {
224: print "<p>There is a problem with updating the table.</p>\n";
225: print "</body></html>\n";
226: return;
227: }
228: print "<p>The table has been updated.</p>\n";
229: print "</body></html>\n";
230: ?>

20 Guide 106: Accessing databases from the World Wide Web


4.5 Providing a WWW page to delete a row
Finally, we look at how we can provide an HTML form and associated PHP
scripts to delete an item from the database. To make sure that we do not
delete items we wish to retain, the first step is to query the database
looking for items that match a name that we supply. So the HTML form for
this can be very similar to the one we used for querying the database:
231: <html><body>
232: <form method="post" action="pricesdelete.php">
233: To search for an item of consumables
234: that you would like to delete:
235: <br />type in part of the name of the item (e.g., Series IV):
236: <input type="text" name="goods" />
237: <br /><input type="submit" value="run query" />
238: </form>
239: </body></html>

A page with this form is at


http://www.dur.ac.uk/resources/its/info/guides/106/pricesdelete.htm
The pricesdelete.php script (shown below) uses code like that in
pricesquery.php to produce an HTML table of those items which have
names that match. It follows this by an HTML form asking the visitor to the
WWW page to type in the ID of an item that he/she wants to delete from the
table. As we are about to make a change to the database, this form also
asks the visitor for the password needed to access this database. This form
has two buttons: one is labelled cancel deletion, the other is labelled
delete item. By this means, the visitor is able to change their mind about
deleting an item.
240: <?php
241: print "<html><body>\n";
242: $goods = $_POST['goods'];
243: $connect_result = mysql_connect("myeusql.dur.ac.uk", "nobody", "");
244: if (! $connect_result)
245: {
246: print "<p>There is a problem in connecting to the server</p>\n";
247: print "</body></html>\n";
248: return;
249: }
250: $query = "SELECT * FROM consum WHERE goods like '%$goods%'";
251: $query_result = mysql_db_query("Pdcl0bjc_prices", $query);
252: if (! $query_result)
253: {
254: print "<p>There is a problem with querying the table.</p>\n";
255: print "</body></html>\n";
256: return;
257: }

Guide 106: Accessing databases from the World Wide Webb 21


258: $numrows = mysql_num_rows($query_result);
259: if ($numrows==0)
260: {
261: print "<p>There are no consumables with a name of $goods</p>\n";
262: print "</body></html>\n";
263: return;
264: }
265: print "<table border=\"1\">\n";
266: for ($rownum = 0; $rownum<$numrows; $rownum++)
267: {
268: print "<tr>\n";
269: print "<td align=\"right\">\n";
270: print mysql_result($query_result, $rownum, "ID");
271: print "</td>\n";
272: print "<td>\n";
273: print mysql_result($query_result, $rownum, "goods");
274: print "</td>\n";
275: print "<td bgcolor=\"yellow\" align=\"right\">\n";
276: printf("&pound;%01.2f", mysql_result($query_result, $rownum, "price"));
277: print "</td>\n";
278: print "</tr>\n";
279: }
280: print "</table>\n";
281: print "<form method=\"post\" action=\"pricesreallydelete.php\">\n";
282: print "<input type=\"submit\" name=\"submit\" value=\"cancel deletion\" />\n";
283: print "<br />\n";
284: if ($numrows==1)
285: {
286: $ID = mysql_result($query_result, 0, "ID");
287: print "<input type=\"hidden\" name=\"ID\" value=\"$ID\" />\n";
288: print "To delete this item:\n";
289: }
290: else
291: {
292: print "To delete an item of consumables\n";
293: $EG = mysql_result($query_result, 0, "ID");
294: print "type in the ID of the item, e.g., <code>$EG</code>\n";
295: print "<input type=\"text\" name=\"ID\" />\n";
296: }
297: print "<br />type in your password\n";
298: print "<input type=\"password\" name=\"password\" />\n";
299: print "<br /><input type=\"submit\" name=\"submit\" value=\"delete item\" />\n";
300: print "</form>\n";
301: print "</body></html>\n";
302: ?>

The above script generates an HTML form, and if a visitor presses either of
its two buttons, the following script (pricesreallydelete.php) is executed. It
detects which of the two buttons was pressed, and performs an appropriate
DELETE SQL statement if and only if the visitor pressed the delete item
button.

22 Guide 106: Accessing databases from the World Wide Web


303: <?php
304: print "<html><body>\n";
305: $submit = $_POST['submit'];
306: $password = $_POST['password'];
307: $ID = $_POST['ID'];
308: if ($submit=="cancel deletion")
309: {
310: print "<p>Item $ID has not been deleted</p>\n";
311: print "</body></html>\n";
312: return;
313: }
314: $connect_result = mysql_connect("mysql.dur.ac.uk", "dcl0bjc", "$password");
315: if (! $connect_result)
316: {
317: print "<p>There is a problem in connecting to the server</p>\n";
318: print "</body></html>\n";
319: return;
320: }
321: $query = "DELETE FROM consum WHERE ID='$ID'";
322: $query_result = mysql_db_query("Pdcl0bjc_prices", $query);
323: if (! $query_result)
324: {
325: print "<p>There is a problem with deleting item $ID.</p>\n";
326: print "</body></html>\n";
327: return;
328: }
329: print "<p>Item $ID has been deleted from the table.</p>\n";
330: print "</body></html>\n";
331: ?>

5 Using Microsoft Access with MySQL databases

5.1 Introducing the two ways in which Access can be used


Although it is reasonably easy to provide HTML forms and PHP scripts that
query a table that is stored in a MySQL database, providing HTML forms
and PHP scripts to update the database is not so easy. So the question
arises as to whether we can continue to use the WWW pages to query the
database but to update it in some other way. In this section of the
document, we look at two ways in which Microsoft Access can be used to
maintain the data.
Either you maintain the data in Access on your PC and transfer the tables
to the MySQL database whenever you update them on the PC, or you can
arrange for the tables in Access to be linked to those in the MySQL
database so that whenever you make a change in Access you are actually
updating the live data, i.e., the data that is accessible from the WWW. We
look at these two methods in Sections 5.3 and 5.4 of this document.
However, whichever method you choose, you will need some way of
communicating between Microsoft Access and the MySQL server. It is
done using something called ODBC. In practice, what you need to do is to
install a MySQL ODBC driver, i.e., an ODBC driver that can communicate
with the MySQL server. Section 5.2 describes how to do this. However,

Guide 106: Accessing databases from the World Wide Webb 23


there is no need to do this if you are using the NPCS or MDS services as
these already have the MyODBC driver installed.

5.2 Installing a MySQL ODBC driver on a Windows PC


In order to use Microsoft Access with MySQL, it is necessary to install a
MySQL ODBC driver on your Windows XP/Vista computer.
The following link provides instructions on how to download and install the
driver:
http://www.dur.ac.uk/its/services/web/publishing/database/odbc/

5.3 Transferring a table to a MySQL database from Access

5.3.1 Creating a database in Microsoft Access 2007


In this section, it is assumed that you have a database in Microsoft Access
whose tables you wish to transfer to a MySQL database. However, it may
be best to try this out first with some other database. So we first create a
simple database with Microsoft Access. This section gives the steps
needed to create a database using Access 2007. Instructions for Access
2003 and earlier are given in section 5.3.2.
1 Get into Microsoft Access. Choose New Blank Database from the
Getting Started with Microsoft Office Access page, and enter a
filename in the box on the right of the screen.
2 A Table box appears. An ID fields is automatically created with an
AutoNumber data type
3 Double-click on the Add New Field column, type name and press
Enter. Ignore the error about reserved words – this doesn’t matter for
this example.
4 Click on the field under the name column; the Data Type box on the
Ribbon should read Text
5 Double-click on the third column of the table, which should now be
Add New Field, type number and press Enter.
6 Once again, if you click on the field under the number column, the
Data Type box should read Text
7 Click on the disk icon to save the table; overtype the suggested
name with phones and click on OK
8 Select the first field underneath Name
9 Type Harold, press the Enter key, and type 1066, then press Enter
again.
10 Press the Tab key, type maggie, press Enter; type 1979, then press
Enter again.
11 Press the Tab key, type peter, press Enter; type 1812, then press
Enter again.
12 Press the Tab key, type julius, press Enter; type 44, then press
Enter again.

24 Guide 106: Accessing databases from the World Wide Web


13 Click on the Office icon, followed by Exit Access
That has created an Access database in the file directory.mdb. The
database has one table called phones and this table has four
records.

5.3.2 Creating a database in Microsoft Access 2003


This section gives the steps needed to create the above database using
Access 2003. Although the following instructions are appropriate for Access
2003, a similar procedure can be adopted with Access 2000 or 97.
1 Get into Microsoft Access; click on File followed by New; then click
on Blank Database radio button; and then click on OK.
2 A File New Database box appears. In the File name box, type
directory.mdb and then click on Create.
3 A Database box appears open for Tables objects. Double-click on
Create Table in Design View.
4 A Table box appears. In the Field Name column, type id and then
press the Tab key.
5 In the Data Type column, use the pull-down menu to select
AutoNumber.
6 Click on the second row of the table, and in the Field Name column,
type name and then press the Tab key.
7 In the Data Type column, Text should appear.
8 Click on the third row of the table, and in the Field Name column,
type number and then press the Tab key.
Once again, Text should appear in the Data Type column.
9 Click on File, followed by Save As.
10 A Save As box appears. Overtype the suggested name with phones
and click on OK.
11 Click on No when asked if you want to create a primary key.
12 Select View | Datasheet View from the Menu bar.
13 Press the Tab key; type harold; press the Tab key; and type 1066.
14 Press the Tab key; press the Tab key again; type maggie; press the
Tab key; and type 1979.
15 Press the Tab key; press the Tab key again; type peter; press the
Tab key; and type 1812.
16 Press the Tab key; press the Tab key again; type julius; press the
Tab key; and type 44.
17 Click on File followed by Exit.
That has created an Access database in the file directory.mdb. The
database has one table called phones and this table has four records.

Guide 106: Accessing databases from the World Wide Webb 25


5.3.3 Creating a MySQL database
Now, you need to create a MySQL database. This was covered in sections
3.3 and 3.4. Create a database called Pdxy3fab_directory, where
dxy3fab is replaced by your username.

5.3.4 Transferring a table from Access to a MySQL database


Here are the steps that are necessary to transfer a table from Microsoft
Access to a MySQL database:
1 Get into Microsoft Access, and open the Access database. In this
example, it is the file directory.mdb.
2 When you open a database in Access 2003, you have a window for
the database. This window has an Objects section on the left hand
side, listing seven Objects, Tables, Queries, Forms, Reports,
Pages Macros and Modules. Ensure that the Tables Object is
selected. In Access 2007, the tables are listed on the left hand side
of the window.
3 In Access 2003, click once on a table of your database. In this
example, click on the table phones. Click on File, then Export. An
Export Table box appears. In the Save as type pull down menu,
choose ODBC Databases(). (It is probably the last entry of the
menu.)
4 In Access 2007, right-click on a table of your database (in this
example, phones), choose Export, and ODBC database
5 An Export box appears. Click on OK.
6 A Select Data Source box appears. It has two tabs. Ensure that the
Machine Data Source tab is selected.
The first time you do this the data source name that you want
(e.g., Pdxy3fab_directory) will not be listed. However, it will be on
subsequent occasions. If it is listed move to step 16; otherwise, do the
following steps:
7 Click on New.
8 A Create New Data Source box appears. Select System Data
Source if you want the database to be accessible by other users on
your computer, otherwise select User Data Source. Click on Next.
9 A list should appear and it should include MySQL. If it is not there,
you need to look at Section 5.2. Click on MySQL ODBC 3.51
Driver.
10 Click on Next.
11 Click on Finish.
12 A Connector/ODBC – Add Data Source Name box should appear.
If instead a MySQL ODBC Driver – DSN Configuration box
appears, you have an out of date MySQL ODBC driver: follow the

26 Guide 106: Accessing databases from the World Wide Web


instructions in Section 5.2 to update your driver, and then start this
section again.
13 In the various fields in the Connector/ODBC box put the following
information:
Data Source Name: Pdxy3fab_directory
Description: Pdxy3fab_directory
Server: myeusql.dur.ac.uk
User: dxy3fab
Password:
Database: Pdxy3fab_directory
where dxy3fab is replaced by your username and
Pdxy3fab_directory is replaced by the name of your database.
Note that you must type the database name – the pull-down list for
this field will not work.
14 If you are happy for a password to be stored on your PC, then fill in
the Password box with your MySQL password. Otherwise, leave this
box empty. It is probably best to leave the box empty.
15 Click on OK.
A Select Data Source box reappears. It now has a new entry (e.g.,
Pdxy3fab_directory) which is selected.
16 Ensure that the required entry (e.g., Pdxy3fab_directory) is
selected. Click on OK. If an Access Denied error box is displayed,
click on OK.
17 A Connector/ODBC – Driver Connect box appears. If the
Password box is not already completed, fill it in now with your
MySQL password.
18 Click on OK.
As long as you do not get an ODBC Call Failed error box, then the table
should have been satisfactorily transferred to the MySQL server. Access
2007 will then ask if you wish to save the export steps. There isn’t a need to
save the steps at this time.
19 Do the same for any other tables of your database.

5.3.5 Updating a table that already exists


The details given above for transferring a table from Access to a MySQL
database assume that the table does not exist in the MySQL database.
Here are some steps that can be used to explore what happens if you
attempt to update a table that already exists:
1 Use Microsoft Access in the usual way to update your table. For
example, you might be updating the phones table (that is in the
directory.mdb file) in some way, e.g., by removing a record from the
table.

Guide 106: Accessing databases from the World Wide Webb 27


2 Attempt to transfer the table to the MySQL server using the
instructions given in Section 5.3.3.
3 You should get an ODBC Call Failed error box. Click on OK.
The problem is that you cannot transfer a table from Access if the table
already exists in the database. So, before transferring the table, you first
need to drop the table. The instructions for dropping a table were covered
in section 3.10. If you attempt to transfer the table again after dropping it in
MySQL, then the transfer should work. You can check that the MySQL
server now has its own copy of the latest version of the data that is in the
Microsoft Access database by displaying the data in the MySQL database
(this was covered in section 3.9).
So remember: if you want to transfer a table from Access to a MySQL
database, any existing table of the same name must be dropped before you
attempt the transfer.

5.4 Using a MySQL table from Access


Instead of transferring a table from Access to a MySQL database every
time that it is altered, you may prefer instead to use Access to alter the
table of the MySQL database.
In the following steps, it is assumed that you have already transferred the
data from a table in an Access database to a table in a MySQL database.
You may have used the instructions of the previous section in order to do
this.
1 First, ensure that you have not got an Access window open.
2 Then, use My Computer or Windows Explorer or a command
window to rename the file directory.mdb as directory.old.
On the Networked PC service, you can do this by:
Click on Start; click on Programs and click on Windows
Explorer.
Ensure that J: is selected in the left-hand pane, and then use the
right-hand mouse button to click on the entry for directory.mdb
in the right-hand pane. A menu should appear. Click on
Rename; type directory.old and then press the Enter key. A
Rename box should appear, asking if you are sure you want to
do this. Click on Yes.
3 Get into Microsoft Access; click on Blank Access database; and, if
you are using Access 2003, click on OK.
4 A File New Database box appears. In the File name box, type
directory.mdb and then click on Create. In Access 2007, the File
name box is on the right of the screen.
A Database box appears.
5 In Access 2003, click on the File button on the menu, then click on
Get External Data and click on Link Tables. A Link box appears. In
the Files of type pull down menu, choose ODBC Databases(). (It is
probably the last entry of the menu.)

28 Guide 106: Accessing databases from the World Wide Web


6 In Access 2007, click on External Data on the toolbar. In the Import
section, click More and choose ODBC Database. Select Link to the
data source by creating a linked table and click OK.
7 A Select Data Source box appears. It has two tabs. Ensure that the
Machine Data Source tab is selected.
The first time you do this the data source name that you want
(e.g., Pdxy3fab_directory) may not be listed. If it is not listed, follow steps
7-15 in section 5.3.4. Ensure that the required entry (e.g.,
Pdxy3fab_directory) is selected. Click on OK. If an Access Denied error
box is displayed, click on OK.
8 A Connector/ODBC – Driver Connect box appears. If the
Password box is not already completed, fill it in now with your
MySQL password.
9 Click on OK.
If you do not get an ODBC Call Failed error box, then a link to the table in
the MySQL database should have satisfactorily been set up. A Link Tables
box appears. This should contain links to the tables (e.g., to phones).
10 Select one of the tables, and click on OK.
11 A Select Unique Record Identifier box may appear. If it does,
select an appropriate field (e.g., id), and click on OK.
12 To open the table, click on the name of the table (e.g., phones), and
then click on Open. In Access 2007, you can double-click the name
of the table to open it.
Any changes you now make are affecting the table in the MySQL database.
To demonstrate this:
1 First, change the table, e.g., by adding a new row to the table.
2 Then, go to the URL
http://www.dur.ac.uk/its/services/web/publishing/database/main
tenance/listtable/ in order to see the table that is visible from the
WWW.

6 Resources

6.1 PHP
The manual for PHP is enormous, but it is very useful. Although the WWW
site for PHP is http://www.php.net/, you should get faster response from
the UK mirror site at http://uk.php.net/. The page about the documentation
that is available for PHP is at http://uk.php.net/docs.php. From this page,
you can see that you can get the documentation in many different ways.
For example, the manual mentioned above is presented using more
sophisticated HTML at http://uk.php.net/manual/.

6.2 SQL
The University Library has a number of books about SQL. Probably the
best is Introduction to SQL: Mastering the Relational Database Language

Guide 106: Accessing databases from the World Wide Webb 29


(fourth edition) by Rick F. van der Lans. It was published by Addison-
Wesley in 2006.
There are a number of SQL tutorials on the WWW.

6.3 MySQL
Although the WWW site for MySQL is http://www.mysql.com/, you should
get faster response from one of the UK mirror sites at
http://www.mirrorservice.org/sites/ftp.mysql.com/.

6.4 Using PHP and MySQL


Some articles about using PHP and MySQL are at:
http://www.webmonkey.com/programming/php/

30 Guide 106: Accessing databases from the World Wide Web

Potrebbero piacerti anche