Vous êtes sur la page 1sur 35

Guide 106

Version 1

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 forms 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. 2. 3. 4. 5. 6. Introduction Using PHP to generate WWW pages dynamically Using WWW pages that create and manipulate databases Using SQL in PHP scripts to manipulate MySQL databases Using Microsoft Access with MySQL databases Resources

Document code: Title: Version: Date: Produced by:

Guide 106 Accessing databases from the World Wide Web 1 28/04/2008 University of Durham Information Technology Service

Copyright 2008 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 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 ...................................................................4 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 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 Creating a database...............................................................................................11 3.4 Creating a table within a database ......................................................................13 3.5 Displaying the headings of the columns of a table ............................................14 3.6 Displaying the data of a table ...............................................................................14 3.7 Inserting a new row into a table ...........................................................................14 3.8 Adding a new column ............................................................................................14 3.8.1 Supplying the type for a new column ..........................................................15 3.8.2 Supplying other attributes for a new column ..............................................15 Using SQL in PHP scripts to manipulate MySQL databases ..........................16 4.1 The basics of SQL ..................................................................................................16 4.1.1 What is SQL? ..................................................................................................16 4.1.2 Creating, dropping and using databases ....................................................16 4.1.3 Creating, altering and dropping tables ........................................................16 4.1.4 Inserting a new row of data into a table ......................................................17 4.1.5 Querying a database......................................................................................17 4.1.6 Removing rows from a database .................................................................17 4.2 Accessing a MySQL server from PHP ................................................................18 4.3 Providing a WWW page to query a table ............................................................18 4.4 Providing a WWW page to insert a new row ......................................................21 4.5 Providing a WWW page to delete a row .............................................................22 Using Microsoft Access with MySQL databases................................................24 5.1 Introducing the two ways in which Access can be used ..................................24 5.2 Installing a MyODBC driver on a Windows PC ..................................................25 5.3 Transferring a table to a MySQL database from Access .................................25 5.3.1 Creating a database in Microsoft Access ...................................................25 5.3.2 Creating a MySQL database ........................................................................26 5.3.3 Transferring a table from Access to a MySQL database .........................27 5.3.4 Checking whether the transfer has worked ................................................28

Guide 106: Accessing databases from the World Wide Web

5.3.5 Updating a table that already exists ............................................................ 28 5.4 Using a MySQL table from Access ..................................................................... 29 6 Resources .................................................................................................................... 31 6.1 PHP .......................................................................................................................... 31 6.2 SQL .......................................................................................................................... 31 6.3 MySQL ..................................................................................................................... 31 6.4 Using PHP and MySQL ........................................................................................ 31

ii

Guide 106:

1
1.1

Introduction
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. 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 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.2

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 visitors 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 2003 database in your public_html directory because Access 2003 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 database server (using some software called MySQL), and it is possible for you to store databases on this database server.

Guide 106: Accessing databases from the World Wide Web

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 forms 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 go to the URL http://www.dur.ac.uk/its/services/web/publishing/database/examples/q uizquery.php, you can see an example of what can be done. This WWW page provides a quiz where the actual questions are stored in a table on the database server. 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 forms 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 an Microsoft Access database will be of no use to you.

2
2.1

Using PHP to generate WWW pages dynamically


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. PHPs manual says that PHPs 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 GIF output; you can do sophisticated mathematical calculations;

Guide 106:

you can send mail; you can interrogate an IMAP server; you can access LDAP servers; you can access XML documents; 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 users 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 persons 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

Guide 106: Accessing databases from the World Wide Web

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 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: 12: 13: 14: print "<p>Here is an introductory paragraph.</p>\n"; $firstname = "Fred"; for ($paranum = 0; $paranum<4; $paranum++) {

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: 16: { print "<p>Hello $firstname. I hope you are OK.</p>\n"; }

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:

Guide 106:

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>

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: 29: 30: 31: $numparas = 4; for ($paranum = 0; $paranum<$numparas; $paranum++) { 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: 38: 39: 40: <input type="text" name="firstname" /> <br /> Type in the number of paragraphs to be generated: <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 persons 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 forms 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

Guide 106: Accessing databases from the World Wide Web

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:
44: <?php 45: 46: 47: 48: 49: 50: 51: 52: $firstname = $_POST['firstname']; $numparas = $_POST['numparas']; print "<p>Here is an introductory paragraph.</p>\n"; for ($paranum = 0; $paranum<$numparas; $paranum++) { print "<p>Hello $firstname. I hope you are OK.</p>\n"; } 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: 56: 57: 58: 59: 60: 61: 62: 63: 64: 65: 66: $firstname = $_POST['firstname']; $numparas = $_POST['numparas']; print "<p>Here is an introductory paragraph.</p>\n"; if ($numparas<=0) { print "<p>That is a silly value for the number of paragraphs!</p>\n"; } else { for ($paranum = 0; $paranum<$numparas; $paranum++) { 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:

Guide 106:

59: 60: 61:

{ print "<p>That is a silly value for the number of paragraphs!</p>\n"; }

get executed; otherwise those of:


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

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

Guide 106: Accessing databases from the World Wide Web

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

Guide 106:

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

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 PHPs 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 Web

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: 137: 138: 139: for ($rownum = 0; $rownum<$numrows; $rownum++) { $centigrade = ($fahrenheit - 32.0)*5.0/9.0; $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:

3
3.1

Using WWW pages that create and manipulate databases


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 Microsofts 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 Microsofts 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 mysql.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

Creating a database Before creating a database, we will first look to see how to find out what databases already exist:
1

Go to the WWW page http://www.dur.ac.uk/its/services/web/publishing/database/. Here you will find a list of links. Most of these involve the execution of a PHP script. We are interested in the one that is labelled Perform administrative functions on a database. Click on this link. Page One of the Administrator will be displayed. This WWW page is in two parts. In the first part, you will find a button labelled List the databases. Click on it.

Guide 106: Accessing databases from the World Wide Web

11

The WWW page should be replaced with one listing the databases that are known to the MySQL server. Now return to Page One by clicking on your browsers Back button.

Now look at the second part of this page. 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.
5

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). So, assuming you know your MySQL username and password, you can fill in the three boxes:
1 2

In the first box, type in your username (e.g., dxy3fab). In the second box, you need to type in the password for the MySQL server that is associated with this username.

In the third box, you should type in the name of the database that you wish to create. 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.
3 4

Having filled in the three boxes, click on the Create this database button. The WWW page should be replaced by one saying that the database has been created. Return to Page One again.

Click on the List the databases button. You should now see the name of your database in the list. Page One contains buttons to list the databases and to create a new one. It also contains a button to destroy a database. The technical word for destroying a database is drop, and so the button is labelled Drop this database.
6

If you wish, fill in the three boxes again putting the name of the database that you recently created in the third box; click on the Drop this database button; click on the List the databases button to check that it no longer exists; fill in the three boxes again; click on the Create this database

12

Guide 106:

button; click on the List the databases button to check that it has reappeared. 3.4 Creating a table within a database We now move on to create a table in the database that has just been created:
1

First, ensure that the three boxes on Page One are filled with values that are appropriate for the name of the database that you recently created. Then click on the Query/update this database button.

2 3

Page Two of the Administrator should now be displayed. In the same way that Page One had four buttons to allow you to list, create, drop or query-and-update databases, this page has: a button labelled List the tables of this database which enables you to find out at any time what tables the database has; a button labelled Create this table which enables you to create a new table in this database; a button labelled Drop this table which enables you to drop a table from the database; a button labelled Query/update this table which enables you to perform more complicated transactions on the table. For each of the last three activities, you have to supply the name of the table. So here are some steps for creating a table within a database: On Page Two, click the button labelled List the tables of this database to find out what tables your database has. You should find it has none. Then use Page Two to create a table in your database. 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 2 3 4 5

On Page Two, fill in the box with the name you have chosen. Then click on the Create this table button. Return to Page Two.

Click the button labelled List the tables of this database again to check that you now have a table. If you wish, you may want to prove that you can drop a table. If so, ensure that the box on Page Two is filled in with the name of the table you have just created; then click on the Drop this table button; click on the List the tables of this database button to check that it no longer exists; fill in the box containing the name of the table again; click on the Create this table button; click on the List the tables of this database button to check that it has reappeared.

Guide 106: Accessing databases from the World Wide Web

13

3.5

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:
1

First, ensure that the box on Page Two contains the name of the table that you recently created.

Then click on the Query/update this table button. Page Three of the Administrator should now be displayed. Once again, this page has a number of possibilities. For example, there are buttons to display the headings of the columns (or fields) that a table has, to display the data of a table, to add a new row to a table, and so on.
2

The first button is labelled Display the column headings of this table. Click on this button. You should find that the table that you have just created has been created with a column labelled name. This was done because it is not possible to create a table without any columns. If you do not want a column called name, first note that you cannot remove it straightaway as it is not possible to have a table with no columns. Instead, we will see later how you can use one of the buttons on Page Three to add a column you want to this table and then you will be in a position to remove the column called name.
3

3.6

Displaying the data of a table Another button on Page Three of the Administrator, enables you to display the data of the table, i.e., to display the contents of each row of the table:
1 2

First, move to Page Three of the Administrator. Click on the button Display the data of this table.

3.7

Inserting a new row into a table Page Three also enables you to add a new row to an existing table. You can do this in the following way:
1 2 3

First, move to Page Three of the Administrator. Click on the button Insert a new row in the table. Page Four of the Administrator will be displayed. This page asks you type in a value for each of the columns of the table. If a value is a string, you will need to include a character at the start and end of the string, e.g., banana. Click on Add this row. If you return to Page Three and click on the button labelled Display the data of this table, you should now see the new row in the table.

4 5

3.8

Adding a new column When you want to add a column, you not only have to supply the name of the column, but you also have to indicate the type of the values you want to store in the column.

14

Guide 106:

3.8.1

Supplying the type for a new 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 timebeing, all you really need to know is:

The type VARCHAR(20) can be used to represent a variable-length string of up to 20 characters. The value 20 can instead be any value 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(10,2) for monetary values. 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.8.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 DEFAULT ' ' or DEFAULT 0 or DEFAULT 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. 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. 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 Web

15

4
4.1

Using SQL in PHP scripts to manipulate MySQL databases


The basics of SQL What is SQL? The Structured Query Language (or SQL) is a language for use with relational databases. It has been evolving since the early 1980s. There is a standard version of SQL known as SQL:2003. Although SQLs 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. SQL is a very comprehensive language and this document will only have room to describe a small part of it.

4.1.1

4.1.2

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.3 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.9.1 and 3.9.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:

16

Guide 106:

DROP TABLE IF EXISTS consum

where, once again, the IF EXISTS part is optional. 4.1.4 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.5 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.6

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%'

Guide 106: Accessing databases from the World Wide Web

17

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 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("mysql.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("mysql.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>

18

Guide 106:

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

Guide 106: Accessing databases from the World Wide Web

19

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

194: } 195: print "</table>\n"; 196: print "</body></html>\n"; 197: ?>

20

Guide 106:

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 scripts 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: 210: 211: 212: 213: 214: 215: 216: 217: 218: 219: 220: 221: 222: 223: 224: 225: 226: 227: 228: print "<html><body>\n"; $password = $_POST['password']; $password = $_POST['goods']; $password = $_POST['price']; $connect_result = mysql_connect("mysql.dur.ac.uk", "dcl0bjc", "$password"); if (! $connect_result) { print "<p>There is a problem in connecting to the server</p>\n"; print "</body></html>\n"; return; } $query = "INSERT INTO consum SET goods='$goods', price=$price"; $query_result = mysql_db_query("Pdcl0bjc_prices", $query); if (! $query_result) { print "<p>There is a problem with updating the table.</p>\n"; print "</body></html>\n"; return; } print "<p>The table has been updated.</p>\n";

229: print "</body></html>\n"; 230: ?>

Guide 106: Accessing databases from the World Wide Web

21

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: 242: 243: 244: 245: 246: 247: 248: 249: 250: 251: 252: 253: 254: 255: 256: 257: print "<html><body>\n"; $goods = $_POST['goods']; $connect_result = mysql_connect("mysql.dur.ac.uk", "nobody", ""); if (! $connect_result) { print "<p>There is a problem in connecting to the server</p>\n"; print "</body></html>\n"; return; } $query = "SELECT * FROM consum WHERE goods like '%$goods%'"; $query_result = mysql_db_query("Pdcl0bjc_prices", $query); if (! $query_result) { print "<p>There is a problem with querying the table.</p>\n"; print "</body></html>\n"; return; }

22

Guide 106:

258: 259: 260: 261: 262: 263: 264: 265: 266: 267: 268: 269: 270: 271: 272: 273: 274: 275: 276: 277: 278: 279: 280: 281: 282: 283: 284: 285: 286: 287: 288: 289: 290: 291: 292: 293: 294: 295: 296: 297: 298: 299: 300: 301:

$numrows = mysql_num_rows($query_result); if ($numrows==0) { print "<p>There are no consumables with a name of $goods</p>\n"; print "</body></html>\n"; return; } print "<table border=\"1\">\n"; for ($rownum = 0; $rownum<$numrows; $rownum++) { print "<tr>\n"; print "<td align=\"right\">\n"; print mysql_result($query_result, $rownum, "ID"); print "</td>\n"; print "<td>\n"; print mysql_result($query_result, $rownum, "goods"); print "</td>\n"; print "<td bgcolor=\"yellow\" align=\"right\">\n"; printf("&pound;%01.2f", mysql_result($query_result, $rownum, "price")); print "</td>\n"; print "</tr>\n"; } print "</table>\n"; print "<form method=\"post\" action=\"pricesreallydelete.php\">\n"; print "<input type=\"submit\" name=\"submit\" value=\"cancel deletion\" />\n"; print "<br />\n"; if ($numrows==1) { $ID = mysql_result($query_result, 0, "ID"); print "<input type=\"hidden\" name=\"ID\" value=\"$ID\" />\n"; print "To delete this item:\n"; } else { print "To delete an item of consumables\n"; $EG = mysql_result($query_result, 0, "ID"); print "type in the ID of the item, e.g., <code$EG</code\n"; print "<input type=\"text\" name=\"ID\" />\n"; } print "<br />type in your password\n"; print "<input type=\"password\" name=\"password\" />\n"; print "<br /><input type=\"submit\" name=\"submit\" value=\"delete item\" />\n"; print "</form>\n"; 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.

Guide 106: Accessing databases from the World Wide Web

23

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

330: print "</body></html>\n"; 331: ?>

5
5.1

Using Microsoft Access with MySQL databases


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 MyODBC driver, i.e., an ODBC driver that can communicate with the MySQL server. Section 5.2 describes how to do this. However, there is

24

Guide 106:

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 MyODBC driver on a Windows PC In order to use Microsoft Access with MySQL, it is necessary to install a MyODBC driver on your Windows 95/98/NT/XP computer:
1

Click on the following link in order to access a file containing an ODBC driver: http://www.dur.ac.uk/its/services/web/publishing/database/odbc/ Ensure that Save it to disk is selected and click on OK. A Save As box appears. Choose some appropriate directory into which to save the file. You might want to choose C:\TEMP (or C:\WINDOWS\TEMP). You will need an unzip program (such as WinZip or Info-ZIP or PKUNZIP). Info-ZIP is free and is available at http://www.infozip.org Run your unzip program: open the .zip file that you have just saved select all the files of the archive choose a new directory for unzipping, e.g., C:\TODAY extract the files of the archive into this directory. Erase the .zip file from C:\TEMP. Run the program C:\TODAY\SETUP.EXE. Click on Continue. An Install Drivers box appears. Select MySQL and then click on OK. A Data Source box appears. The entry sample-MySQL (MySQL) should be appear in the middle of the list. Click on Close. A Microsoft ODBC Setup box re-appears. Click on OK. Remove the files and the directory C:\TODAY.

2 3

6 7 8 9

10

11 12

5.3 5.3.1

Transferring a table to a MySQL database from Access Creating a database in Microsoft Access 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. 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.

Guide 106: Accessing databases from the World Wide Web

25

A File New Database box appears. In the File name box, type directory.mdb and then click on Create. A Database box appears open for Tables objects. Double-click on Create Table in Design View. A Table box appears. In the Field Name column, type id and then press the Tab key. In the Data Type column, use the pull-down menu to select AutoNumber. Click on the second row of the table, and in the Field Name column, type name and then press the Tab key. In the Data Type column, Text should appear.

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

Click on File, followed by Save As. A Save As box appears. Overtype the suggested name with phones and click on OK. Click on No when asked if you want to create a primary key. Select View | Datasheet View from the Menu bar. Press the Tab key; type harold; press the Tab key; and type 1066. Press the Tab key; press the Tab key again; type maggie; press the Tab key; and type 1979. Press the Tab key; press the Tab key again; type peter; press the Tab key; and type 1812. Press the Tab key; press the Tab key again; type julius; press the Tab key; and type 44.

11 12 13 14

15

16

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

5.3.2

Creating a MySQL database Now, you need to create a MySQL database. Probably, the easiest way is:
1

Go to the URL http://www.dur.ac.uk/its/services/web/publishing/database/main tenance/admin1/ In the boxes, type your username, your MySQL password and the name of the database. If you have an Access database called directory.mdb, it is recommended that you call the MySQL database by the name Pdxy3fab_directory, where dxy3fab is replaced by your username. Click on Create this database.

26

Guide 106:

5.3.3

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. When you open a database in Access, 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. Click once on a table of your Access database. In this example, click on the table phones. Click on File. Click on 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.) An Export box appears. Click on OK.

4 5 6 7

8 9

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 18; otherwise, do the following steps:
10 11

Click on New. A Create New Data Source box appears. Ensure that System Data Source is checked. Click on Next. 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. Click on Next. Click on Finish. A MySQL ODBC Driver DSN Configuration box appears. In the various boxes put the following information: Data Source Name: Host/Server Name: Database Name: User: Pdxy3fab_directory mysql.dur.ac.uk Pdxy3fab_directory dxy3fab

12

13 14 15

where dxy3fab is replaced by your username and Pdxy3fab_directory is replaced by the name of your database.
16

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.

Guide 106: Accessing databases from the World Wide Web

27

Leave the other boxes empty. Click on OK. A Select Data Source box reappears. It now has a new entry (e.g., Pdxy3fab_directory) which is selected.
17 18

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. A MyODBC Connection box appears. If the Password box is not already completed, fill it in now with your MySQL password.

19

Click on OK. If you fail to get an ODBC Call Failed error box, then the table should have been satisfactorily transferred to the MySQL server.
20 21

Do the same for any other tables of your database.

5.3.4

Checking whether the transfer has worked All you have to do to check whether the transfer has worked is to:
1

Go to the URL http://www.dur.ac.uk/its/services/web/publishing/database/main tenance/listtable/ List the table(s) that you have transferred.

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. Attempt to transfer the table to the MySQL server using the instructions given in Section 5.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:
3 1

Go to the URL http://www.dur.ac.uk/its/services/web/publishing/database/main tenance/admin1/ In the boxes, type your username, your MySQL password and the name of the database (e.g., Pdxy3fab_directory). Click on Query/update this database. On the Page Two screen, in the box type in the name of the table (e.g., phones).

3 4

28

Guide 106:

5 6 7

Click on Drop this table. Then attempt to transfer the table again. It should work this time.

Go to the URL http://www.dur.ac.uk/its/services/web/publishing/database/main tenance/listtable/ in order to show that the MySQL server now has its own copy of the latest version of the data that is in the Microsoft Access database. 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 2

First, ensure that you have not got an Access window open.

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.

Get into Microsoft Access; click on Blank Access database; and then click on OK.

A File New Database box appears. In the File name box, type directory.mdb and then click on Create. A Database box appears.
4 5 6 7 8

Click on the File button on the menu. Click on Get External Data. 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.) A Select Data Source box appears. It has two tabs. Ensure that the Machine Data Source tab is selected.

Guide 106: Accessing databases from the World Wide Web

29

The first time you do this the data source name that you want (e.g., Pdxy3fab_directory) may not be listed. However, it will be on subsequent occasions. If it is listed move to step 18; otherwise, do the following steps:
10 11

Click on New. A Create New Data Source box appears. Ensure that System Data Source is checked. Click on Next. 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. Click on Next. Click on Finish. A MySQL ODBC Driver DSN Configuration box appears. In the various boxes put the following information: Data Source Name: Host/Server name: Database Name: User: Pdxy3fab_directory mysql.dur.ac.uk Pdxy3fab_directory dxy3fab

12

13 14 15

where dxy3fab is replaced by your username and Pdxy3fab_directory is replaced by the name of your database.
16

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.

Leave the other boxes empty. Click on OK. A Select Data Source box reappears. It now has a new entry (e.g., Pdxy3fab_directory) which is selected.
17 18

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. A MyODBC Connection box appears. If the Password box is not already completed, fill it in now with your MySQL password.

19

Click on OK. If you fail to 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).
20 21 22

Select one of the tables, and click on OK. A Select Unique Record Identifier box may appear. If it does, select an appropriate field (e.g., id), and click on OK.

To open the table, click on the name of the table (e.g., phones), and then click on Open. Any changes you now make are affecting the table in the MySQL database. To demonstrate this:
23 1

First, change the table, e.g., by adding a new row to the table.

30

Guide 106:

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
6.1

Resources
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/. SQL The University Library has a number of books about SQL. Probably the best is Introduction to SQL: Mastering the Relational Database Language (fourth edition) by Rick F. van der Lans. It was published by AddisonWesley in 2006. There are a number of SQL tutorials on the WWW.

6.2

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/. Using PHP and MySQL Some articles about using PHP and MySQL are at: http://www.webmonkey.com/programming/php/

6.4

Guide 106: Accessing databases from the World Wide Web

31

Vous aimerez peut-être aussi