Accessing Databases From the World Wide Web WWW

Embed Size (px)

Citation preview

  • 8/13/2019 Accessing Databases From the World Wide Web WWW

    1/35

    Guide 106Version 1

    Accessing databases fromthe World Wide Web

    The ITS provides a computer on which databases can be stored. If youprovide a WWW page that displays a form, then, when the user clicks on theforms submit button, a request can be sent to the database computer thatqueries a table of the database. The results that are returned can be displayedon a WWW page. Such WWW pages need to be written in a mix of thelanguages HTML, PHP and SQL.

    This document introduces the HTML that is necessary to produce a form; thePHP that is necessary to submit a request to a database and interpret theresults that the request generates; and the SQL that is necessary to specify aquery to a database.

    Although it is necessary to use HTML, PHP and SQL to allow a personanywhere in the world to use a browser to query a database, the documentindicates 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

    http://www.what-is-net.info/http://www.what-is-net.info/http://www.what-is-net.info/http://www.what-is-net.info/http://www.what-is-net.info/
  • 8/13/2019 Accessing Databases From the World Wide Web WWW

    2/35

    Document code: Guide 106

    Title: Accessing databases from the World Wide Web

    Version: 1

    Date: 28/04/2008

    Produced by: 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 fontis used to represent the actual characters you type atthe keyboard.

    A slanted typewri ter fontis used for items such as filenames which you shouldreplace with particular instances.

    A bold fontis used to indicate named keys on the keyboard, for example,Esc and Enter, represent the keys marked Esc and Enter, respectively.

    A bold fontis also used where a technical term or command name is used inthe 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 releasethe first key.

  • 8/13/2019 Accessing Databases From the World Wide Web WWW

    3/35

    Guide 106: Accessing databases from the World Wide Web i

    Contents

    1 Introduction ....................................................................................................................1

    1.1 Accessing large amounts of data from the WWW...............................................11.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? ............................................................................................................22.2 A simple example of a PHP script.........................................................................32.3 Using variables in PHP ............................................................................................32.4 Using a for command to create loops...................................................................42.5 Using an HTML form to supply data......................................................................52.6 Using an if command to make decisions..............................................................62.7 Calling pre-defined functions..................................................................................72.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 ..............................................................................................................113.2 Choosing to use MySQL for storing databases.................................................113.3 Creating a database ...............................................................................................113.4 Creating a table within a database......................................................................133.5 Displaying the headings of the columns of a table............................................143.6 Displaying the data of a table...............................................................................143.7 Inserting a new row into a table...........................................................................143.8 Adding a new column............................................................................................14

    3.8.1 Supplying the type for a new column..........................................................153.8.2 Supplying other attributes for a new column..............................................15

    4 Using SQL in PHP scripts to manipulate MySQL databases..........................16

    4.1 The basics of SQL ..................................................................................................164.1.1 What is SQL?..................................................................................................164.1.2 Creating, dropping and using databases....................................................164.1.3 Creating, altering and dropping tables........................................................164.1.4 Inserting a new row of data into a table ......................................................174.1.5 Querying a database ......................................................................................174.1.6 Removing rows from a database.................................................................17

    4.2 Accessing a MySQL server from PHP................................................................184.3 Providing a WWW page to query a table ............................................................184.4 Providing a WWW page to insert a new row......................................................214.5 Providing a WWW page to delete a row.............................................................22

    5 Using Microsoft Access with MySQL databases................................................24

    5.1 Introducing the two ways in which Access can be used..................................245.2 Installing a MyODBC driver on a Windows PC..................................................255.3 Transferring a table to a MySQL database from Access.................................25

    5.3.1 Creating a database in Microsoft Access...................................................255.3.2 Creating a MySQL database........................................................................265.3.3 Transferring a table from Access to a MySQL database.........................27

    5.3.4 Checking whether the transfer has worked................................................28

  • 8/13/2019 Accessing Databases From the World Wide Web WWW

    4/35

    Guide 106:ii

    5.3.5 Updating a table that already exists............................................................ 285.4 Using a MySQL table from Access..................................................................... 29

    6 Resources.................................................................................................................... 31

    6.1 PHP.......................................................................................................................... 316.2 SQL.......................................................................................................................... 316.3 MySQL..................................................................................................................... 316.4 Using PHP and MySQL........................................................................................ 31

  • 8/13/2019 Accessing Databases From the World Wide Web WWW

    5/35

    Guide 106: Accessing databases from the World Wide Web 1

    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, andso the question arises as to whether it is possible to put the database onthe 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 putthe .mdbfile alongside the HTML files that are in your public_htmldirectory. When the user of a WWW browser clicks on a link to this .mdbfile, 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 hasbeen configured. With Internet Explorer on the Networked PC service, theuser 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 URLhttp://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 theyinadvertently make to it will not affect the actual .mdbfile that is in yourpublic_htmldirectory. And, whenever you use Access to update yourdatabase, you will need to re-transfer the .mdbfile to your public_htmldirectory in order to make the new version available on the WWW.

    By this means, you can easily make a database available to anyonebrowsing the WWW (provided you are familiar with Microsoft Access).

    1.3 The drawbacks of providing a .mdb fileAlthough this looks like an attractive solution, there are three drawbacks.Firstly, it assumes that the person accessing the .mdbfile has MicrosoftAccess on their computer. This will not be the case if they have a Mac or acomputer running Linux or Unix. And even if they have an appropriatecomputer they may not have a copy of Microsoft Access. The seconddrawback concerns different versions of Access: if a database is producedusing the latest version of Access, it is likely to be inaccessible to a personwho has an earlier version. The third drawback concerns the size of thedatabase: as the .mdbfile has to be downloaded to the visitors PC, thiswill be an issue if it is a large database.

    Of course, the first two drawbacks are unimportant in situations where youknow that the people accessing the .mdbfile have the appropriate versionof Access. For example, if you are a lecturer at the University of Durhamwanting a database to be accessible by your students, you can provide anAccess 2003 database in your public_htmldirectory because Access 2003is 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 anappropriate version of Access, you need to move away from providing thedata of the database in a .mdbfile. The ITS has a computer that acts as adatabase server (using some software called MySQL), and it is possible for

    you to store databases on this database server.

    http://www.dur.ac.uk/resources/its/info/guides/106/stucol.mdbhttp://www.dur.ac.uk/resources/its/info/guides/106/stucol.mdbhttp://www.dur.ac.uk/resources/its/info/guides/106/stucol.mdb
  • 8/13/2019 Accessing Databases From the World Wide Web WWW

    6/35

    Guide 106:2

    So, an alternative approach is to provide an HTML form on the WWW forthe 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 thisdatabase server. One way in which you can get this to work is to write yourWWW pages in a mixture of HTML and a server-side scripting languagecalled PHP that generates a query in SQL (a database query language).Section 2 of this document looks at PHP and how to include PHPinstructions in a WWW page. And the first part of Section 4 of thisdocument looks at how to write SQL.

    If you go to the URLhttp://www.dur.ac.uk/its/services/web/publishing/database/examples/quizquery.php,you can see an example of what can be done. This WWWpage provides a quiz where the actual questions are stored in a table onthe database server.

    If you adopt this alternative approach, there are three methods by whichyou can update the database on the database server. First, you can

    produce an appropriate HTML form on the WWW and then, when you clickon the forms Submit button, an update request is sent to the databaseserver. The HTML, PHP and SQL needed to accomplish this is looked at inthe second part of Section 4 of this document.

    Both of the other two methods involve the use of Microsoft Access. Eitheryou maintain the data in Access on your PC and transfer the tables to thedatabase server whenever you update them on the PC, or you can arrangefor the tables in Access to be linked to those on the database server so thatwhenever 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 twomethods in Section 5 of this document.

    So you have a choice of these three methods for updating the data thatpeople see from the WWW.

    However, you will need to become familiar with HTML and PHP and SQL inorder to provide the means by which people can query your databases fromthe WWW. Any forms you have for an Microsoft Access database will be ofno use to you.

    2 Using PHP to generate WWW pages dynamically

    2.1 What is PHP?

    PHP is what is known as aserver-side scripting language

    . When a visitor toa WWW page visits a page that is a PHP page, the WWW server gets aPHP interpreter to examine the page. The PHP interpreter will producesome HTML which is then shipped by the WWW server to the visitor'scomputer and is interpreted by his/her WWW browser.

    PHPs manual says that PHPs syntax is borrowed primarily from C. Javaand 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;

    http://www.dur.ac.uk/its/services/web/publishing/database/examples/quizquery.phphttp://www.dur.ac.uk/its/services/web/publishing/database/examples/quizquery.phphttp://www.dur.ac.uk/its/services/web/publishing/database/examples/quizquery.phphttp://www.dur.ac.uk/its/services/web/publishing/database/examples/quizquery.phphttp://www.dur.ac.uk/its/services/web/publishing/database/examples/quizquery.php
  • 8/13/2019 Accessing Databases From the World Wide Web WWW

    7/35

    Guide 106: Accessing databases from the World Wide Web 3

    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 includingOracle, Generic ODBC, Microsoft SQL Server and MySQL.

    2.2 A simple example of a PHP scriptHere is a simple example of a script written in the PHP language:

    1:

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

    Suppose that the file hello1.phpcontains the above script. It can beexecuted by passing it to a WWW server that understands PHP. This can

    be done by using a WWW browser with the URLhttp://www.dur.ac.uk/resources/its/info/guides/106/hello1.php

    Because the filename ends in .php, the WWW server will pass this to aPHP interpreter which understands the bits inside the brackets. The print commandof PHP just outputs the string that followsprint. The string ends with \nwhich means move to a new line(in the HTMLoutput). So the PHP interpreter will output the following HTML and this iswhat the users browser sees:

    4:

    Hello Fred. I hope you are OK.

    2.3 Using variables in PHP

    There are many facilities in PHP besides the print command. We first lookat how you can use variablesin a PHP script.

    In many ways, a variable is like the memory location of a phone, an entry inan address book of a mailer, or a bookmark used with a WWW browser: itis a place where a value can be stored. So we could set up a variablecontaining a persons name as shown inthis PHP script (which you will findin the file hello2.php):

    5: When the PHP interpreter sees this, it will execute the assignmentcommandthat stores the string "Fred"in the variable firstnameand then itwill obey the print command. In the print command, it will replace the$firstnameby the value of the variable. So the result is the same piece ofHTML that was produced by the hello1.phpscript, i.e.:

    9:

    Hello Fred. I hope you are OK.

    You can execute the above script usinghttp://www.dur.ac.uk/resources/its/info/guides/106/hello2.php

    http://www.dur.ac.uk/resources/its/info/guides/106/hello1.phphttp://www.dur.ac.uk/resources/its/info/guides/106/hello1.phphttp://www.dur.ac.uk/resources/its/info/guides/106/hello2.phphttp://www.dur.ac.uk/resources/its/info/guides/106/hello2.phphttp://www.dur.ac.uk/resources/its/info/guides/106/hello2.phphttp://www.dur.ac.uk/resources/its/info/guides/106/hello1.php
  • 8/13/2019 Accessing Databases From the World Wide Web WWW

    8/35

    Guide 106:4

    2.4 Using afor command to create loops

    Scripts are very boring if they just consist of a sequence of commandswhere each command is always executed and is always executed once.PHP has two kinds of commands that make scripts more exciting! Later, wewill look at if commands, used to make decisions in a script. However, we

    first consider for commands, which are used to execute a group ofcommands a number of times.

    For example, suppose we want to output four paragraphs of HTML each ofwhich contains the hello paragraph that was given above. One way of doingthis is shown by the following PHP script (which is in the file hello3.php):

    10:

    You can execute the above script usinghttp://www.dur.ac.uk/resources/its/info/guides/106/hello3.php

    In the middle of this script, there is a forcommand. It consists of a line thatstarts with forfollowed by some lines that are surrounded by a pair of curlybrackets:

    14: {

    15: print "

    Hello $firstname. I hope you are OK.

    \n";

    16: }

    The lines that are surrounded by a pair of curly brackets form the bodyofthe for command. It is these lines that are repeatedly executed. The otherpart of a for command contains something like:

    13: for ($paranum = 0; $paranum

  • 8/13/2019 Accessing Databases From the World Wide Web WWW

    9/35

    Guide 106: Accessing databases from the World Wide Web 5

    19:

    Here is an introductory paragraph.

    20:

    Hello Fred. I hope you are OK.

    21:

    Hello Fred. I hope you are OK.

    22:

    Hello Fred. I hope you are OK.

    23:

    Hello Fred. I hope you are OK.

    24:

    Here is a final paragraph.

    Because the string of each print command includes a \n, this HTMLappears on 6 lines. If the occurrences of \nwere 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 usea variable that has the value 4. This is shown in the hello4.phpscript thatis given here:

    25:

    You can execute the above script usinghttp://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 usingan HTML form (e.g., hello5.htm):

    35:

    36: Type in a person's name:

    37:

    38:

    39: Type in the number of paragraphs to be generated:

    40:

    41:

    42:

    43:

    When a WWW page containing these HTML instructions is accessed, thebrowser will display a page containing a form. This form includes two boxesand asks the person visiting the page to fill these boxes with a personsname and the number of paragraphs to be generated.

    A page with this form is athttp://www.dur.ac.uk/resources/its/info/guides/106/hello5.htm

    When the user clicks on the submit formbutton, the program mentioned inthe forms actionattribute will get executed. With this example, this meansthat the PHP script hello5.phpgets 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

    http://www.dur.ac.uk/resources/its/info/guides/106/hello4.phphttp://www.dur.ac.uk/resources/its/info/guides/106/hello4.phphttp://www.dur.ac.uk/resources/its/info/guides/106/hello5.htmhttp://www.dur.ac.uk/resources/its/info/guides/106/hello5.htmhttp://www.dur.ac.uk/resources/its/info/guides/106/hello5.htmhttp://www.dur.ac.uk/resources/its/info/guides/106/hello4.php
  • 8/13/2019 Accessing Databases From the World Wide Web WWW

    10/35

    Guide 106:6

    been given in the form. So, because the form has used the names firstnameand numparasfor these boxes, a PHP script can access these as$_POST['firstname']and $_POST['numparas'].

    A script that does this is the hello5.phpscript shown here:

    44:

    2.6 Using an if command to make decisions

    What happens if the person visiting the page types the value 0in thenumparasbox? When the for command of the PHP script gets executed,paranumwill be given the value 0 and then the condition$paranum

    This script assumes that it is triggered into action by an HTML form similarto the hello5.htmgiven above. A page with this form is athttp://www.dur.ac.uk/resources/its/info/guides/106/hello6.htm

    Here is how this if command works. First, the condition $numparas

  • 8/13/2019 Accessing Databases From the World Wide Web WWW

    11/35

    Guide 106: Accessing databases from the World Wide Web 7

    59: {

    60: print "

    That is a silly value for the number of paragraphs!

    \n";

    61: }

    get executed; otherwise those of:

    63: {

    64: for ($paranum = 0; $paranum

  • 8/13/2019 Accessing Databases From the World Wide Web WWW

    12/35

    Guide 106:8

    which describes one of the people. Before moving on to how we can querydatabases, we first look at the HTML instructions that are needed to outputinformation in the form of tables.

    The HTML instructions used to indicate that you want to display informationin the form of a table are the and tags. At the start and end

    of each row of the table, you need and tags. And you need tosurround each cell of the table with and tags.

    So, if you wanted to output a three line table, you could use HTMLinstructions like:

    75:

    76: degrees fahrenheit degrees centigrade

    77: 175 80

    78: 200 100

    79:

    Here is one other useful bit of HTML which we will use when displaying

    tables: if instead of you use you can arrange forthat cell to be output with a yellow background.

    So, suppose we want to calculate and output a table giving the Centigradeequivalent of the Fahrenheit temperatures in the range 175 to 525 at stepsof 25 degrees Fahrenheit, with the Centigrade values rounded to thenearest 10 degrees. Such tables used to appear in cookery books.

    As we need to calculate a Centigrade figure for each of the Fahrenheitfigures, 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/13/2019 Accessing Databases From the World Wide Web WWW

    13/35

    Guide 106: Accessing databases from the World Wide Web 9

    80:

    You can execute the above script usinghttp://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 theother rows. Because we want the background of these headings to be inyellow, we need to use . However, because we areusing PHPs print command to output these characters, and because wehave to put these characters in a string, each occurrence of "in the stringhas to be replaced by \". So the script uses:

    90: print "";

    rather than:

    115: print "";

    The script uses a function called round. This function returns a value whichis the nearest integer to the value of its argument.

    Besides generating the HTML instructions for the table, the script also

    generates the instructions:

    http://www.dur.ac.uk/resources/its/info/guides/106/cookery1.phphttp://www.dur.ac.uk/resources/its/info/guides/106/cookery1.phphttp://www.dur.ac.uk/resources/its/info/guides/106/cookery1.php
  • 8/13/2019 Accessing Databases From the World Wide Web WWW

    14/35

    Guide 106:10

    116:

    117:

    118: A conversion table for cooking

    119:

    120:

    at the start, and:121:

    122:

    at the end. To save space, in the previous examples given in these notes,we have failed to provide these instructions. Although most WWWbrowsers will accept the minimal set of HTML instructions shown in earlierexamples, 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 uselarge numbers of print commands. An alternative is to place literal HTMLoutside of sections. The script cookery2.phpachieves thesame effect as the previous script, but using literal HTML, and combiningtogether some of the remaining print commands, making it shorter andeasier to read.

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

    123:

    124:

    125: A conversion table for cooking

    126:

    127:

    128: 129:

    130: degrees fahrenheit

    131: degrees centigrade

    132:

    133:

    144:

    145:

    146:

    You can execute the above script usinghttp://www.dur.ac.uk/resources/its/info/guides/106/cookery2.php

    http://www.dur.ac.uk/resources/its/info/guides/106/cookery2.phphttp://www.dur.ac.uk/resources/its/info/guides/106/cookery2.phphttp://www.dur.ac.uk/resources/its/info/guides/106/cookery2.php
  • 8/13/2019 Accessing Databases From the World Wide Web WWW

    15/35

    Guide 106: Accessing databases from the World Wide Web 11

    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 manipulatedatabases from a PHP script triggered from an HTML form on a WWW

    page. We will produce the files containing the HTML forms and PHP scriptsourselves.

    However, to give you some idea about what can be done, in this section ofthe notes, we will create a database, add a table to the database, insertsome values into this table, remove a row of the table, and so on. We willdo 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 inappropriateproduct for making databases accessible from the WWW. Anyway, you

    probably would not want anyone anywhere in the world to be accessingyour PC. For more robust and intense use, there are other databaseproducts such as Oracle, Microsoft SQL Server, and so on. Some (such asMicrosofts SQL Server) that run on Windows only, others run oncomputers that use Unix or Linux.

    Besides the products listed above which cost money, there are a number ofdatabase products which are free. One of these is called MySQL (not to beconfused with a rival product called MSQL). MySQL is a robust up to dateimplementation which can handle large databases.

    So in this course we will be storing our data in MySQL databases. Thesedatabases 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 asmysql.dur.ac.uk.

    Having said all that, do not worry if your data is already in a MicrosoftAccess database: in Section 5 of this document, we will see how we caninteroperate 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 whatdatabases 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.

    2 We are interested in the one that is labelled Perform administrative

    functions on a database. Click on this link.

    3 Page Oneof the Administratorwill 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.

    http://www.dur.ac.uk/its/services/web/publishing/database/http://www.dur.ac.uk/its/services/web/publishing/database/http://www.dur.ac.uk/its/services/web/publishing/database/
  • 8/13/2019 Accessing Databases From the World Wide Web WWW

    16/35

    Guide 106:12

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

    5 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 tobe the same as the username that is used to access most of the other ITsystems at the University. However, for security reasons, the passwordshould be kept different from the password you use to access other ITsystems at the University (such as the one you use to access NPCS orUnix.

    By default, the MySQL server has been configured so that you can createany databases you want provided that the name of the database beginswith Pdxy3fab_where dxy3fabis replaced by your username. Each ofthese databases can be updated by you from anywhere in the worldprovided you give your MySQL password. Also, each of these databases

    can be queried by anyone anywhere in the world (without the need tosupply a password).

    So, assuming you know your MySQL username and password, you can fillin the three boxes:

    1 In the first box, type in your username (e.g., dxy3fab).

    2 In the second box, you need to type in the password for the MySQL

    server that is associated with this username.

    3 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 Pfollowed by your username(in lower-case), followed by an underscore character (i.e.,_), the remainingcharacters may be chosen by you. This name can only contain letters,digits, underscores and dollars, and it must not be more than 64 characterslong. The name is case sensitive: this means that for any letters of thename you must be consistent on whether you use a capital letter or a smallletter for every use of that name.

    4 Having filled in the three boxes, click on the Create this database

    button.

    5 The WWW page should be replaced by one saying that the

    database has been created. Return to Page One again.6 Click on the List the databasesbutton. 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. Italso contains a button to destroy a database. The technical word fordestroying a database is drop, and so the button is labelled Drop thisdatabase.

    If you wish, fill in the three boxes again putting the name of the databasethat you recently created in the third box; click on the Drop this databasebutton; click on the List the databasesbutton to check that it no longerexists; fill in the three boxes again; click on the Create this database

  • 8/13/2019 Accessing Databases From the World Wide Web WWW

    17/35

    Guide 106: Accessing databases from the World Wide Web 13

    button; click on the List the databasesbutton to check that it hasreappeared.

    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.

    2 Then click on the Query/update this databasebutton.

    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 databasewhich enables youto find out at any time what tables the database has;

    a button labelled Create this tablewhich enables you to create anew table in this database;

    a button labelled Drop this tablewhich enables you to drop a tablefrom the database;

    a button labelled Query/update this tablewhich enables you toperform more complicated transactions on the table.

    For each of the last three activities, you have to supply the name of thetable.

    So here are some steps for creating a table within a database:

    1 On Page Two, click the button labelled List the tables of thisdatabaseto find out what tables your database has.

    You should find it has none. Then use Page Two to create a table in yourdatabase. You will need to give the table a name. The names of tableshave the same restrictions as those for databases. However, unlikedatabase names, table names do not have to begin with something likePdxy3fab_.

    2 On Page Two, fill in the box with the name you have chosen.

    3 Then click on the Create this tablebutton.

    4 Return to Page Two.

    5 Click the button labelled List the tables of this databaseagain to

    check that you now have a table.

    If you wish, you may want to prove that you can drop a table. If so, ensurethat the box on Page Two is filled in with the name of the table you havejust created; then click on the Drop this tablebutton; click on the List thetables of this databasebutton to check that it no longer exists; fill in thebox containing the name of the table again; click on the Create this tablebutton; click on the List the tables of this databasebutton to check that ithas reappeared.

  • 8/13/2019 Accessing Databases From the World Wide Web WWW

    18/35

    Guide 106:14

    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 youhave just created:

    1 First, ensure that the box on Page Two contains the name of the

    table that you recently created.2 Then click on the Query/update this tablebutton.

    Page Three of the Administrator should now be displayed. Once again, thispage has a number of possibilities. For example, there are buttons todisplay the headings of the columns (or fields) that a table has, to displaythe data of a table, to add a new row to a table, and so on.

    3 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 createdwith 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 calledname, first note that you cannot remove it straightaway as it is not possibleto have a table with no columns. Instead, we will see later how you can useone of the buttons on Page Three to add a column you want to this tableand then you will be in a position to remove the column called name.

    3.6 Displaying the data of a table

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

    1 First, move to Page Three of the Administrator.

    2 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. Youcan do this in the following way:

    1 First, move to Page Three of the Administrator.

    2 Click on the button Insert a new row in the table.

    3 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.4 Click on Add this row.

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

    3.8 Adding a new column

    When you want to add a column, you not only have to supply the name ofthe column, but you also have to indicate the typeof the values you want tostore in the column.

  • 8/13/2019 Accessing Databases From the World Wide Web WWW

    19/35

    Guide 106: Accessing databases from the World Wide Web 15

    3.8.1 Supplying the type for a new column

    The types that are supported can be grouped into three categories: numerictypes, date and time types, and string (or character) types. For the time-being, all you really need to know is:

    The type VARCHAR(20)can be used to represent a variable-lengthstring of up to 20 characters. The value 20 can instead be any valuein the range 1 to 255. You should note that values stored in suchcolumns have any trailing spaces removed, and that (unless youspecify otherwise) they are sorted and compared in case-insensitivefashion.

    The type INTcan be used for whole number values.

    The type DOUBLEcan be used for floating point values,i.e., numerical values that have a decimal point.

    As values of type DOUBLEare only stored approximately, use a typelike DECIMAL(10,2)for monetary values. The values 10and 2meanthat 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: theyinclude DATE, DATETIME, TIMESTAMP, TIMEand YEAR.

    3.8.2 Supplying other attributes for a new column

    Besides giving the name and the type of a column, you may give someother attributes:

    A column is called a NOT NULLcolumn if it has the attribute NOTNULL. If there is no NOT NULLattribute, the column is said to be aNULLcolumn.

    A DEFAULTattribute such as DEFAULT ' 'or DEFAULT 0or DEFAULT0.0specifies the default value the column should have it is not given avalue. If no DEFAULTvalue is given for a column and the column is aNULLcolumn, the default value is the value NULL. If no DEFAULTvalue is given for a column and the column is declared as a NOTNULLcolumn, the default value for the column is: the empty string forstring types; the nextvalue forAUTO_INCREMENTcolumns; the value0 for numeric types; and an appropriate zerofor date and time types.

    An integer column may have the additional attributeAUTO_INCREMENT. When you insert a value of NULLinto anAUTO_INCREMENTcolumn, the column is set to one more than the

    largest value that is currently used for this column. Note that a tablecan have only oneAUTO_INCREMENTcolumn, and that the columnmust be indexed.

    A column can have the PRIMARY KEYattribute. A table can have onlyone column with this attribute. An error occurs if you try to add a newrow to a table with a key that matches an existing row.

  • 8/13/2019 Accessing Databases From the World Wide Web WWW

    20/35

    Guide 106:16

    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 withrelational databases. It has been evolving since the early 1980s. There is astandard version of SQL known as SQL:2003. Although SQLs nameimplies that it is just used for querying databases, it actually also hasfacilities for creating new databases and modifying the data of existingdatabases.

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

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

    DROP DATABASE IF EXISTS Pdxy3fab_prices

    where the IF EXISTSpart is optional.

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

    USE Pdxy3fab_prices

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

    4.1.3 Creating, altering and dropping tables

    The SQL statement to create a new table in a database is the CREATETABLEstatement. Besides giving the name of the table, you also have todescribe the columns of the table. For each column, you need to give aname and a type, and you can also give some attributes. Some brief detailsabout types and attributes were given in Sections 3.9.1 and 3.9.2. Here isan example of a CREATE TABLEstatement:

    CREATE TABLE consum (ID INT NOT NULL PRIMARY KEY,

    goods VARCHAR(40) DEFAULT ' ',

    price DECIMAL(8,2) DEFAULT 0.0)

    Here a table called consumis created: it has three columns, called ID, goodsand price. The first column can contain an integer value, the second cancontain strings up to 40 characters long, whereas the third can contain anumerical 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:

  • 8/13/2019 Accessing Databases From the World Wide Web WWW

    21/35

    Guide 106: Accessing databases from the World Wide Web 17

    DROP TABLE IF EXISTS consum

    where, once again, the IF EXISTSpart 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 rowscontaining data to the table. This is done using the INSERTstatement:

    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_stockcolumn, thisrow will have a number_in_stockvalue of 0, because an attribute for thiscolumn (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 SELECTstatement: it is usedto inspect a table of information. The statement:

    SELECT goods, price FROM consumwould look at the table consumand produce (a new table containing) thegoods and prices from all the rows of the table consum. If you want thevalues of all of the columns, use:

    SELECT * FROM consum

    A where definitioncan be added to a SELECTstatement to constrain whatrows get returned. For example:

    SELECT goods FROM consum WHERE price

  • 8/13/2019 Accessing Databases From the World Wide Web WWW

    22/35

    Guide 106:18

    4.2 Accessing a MySQL server from PHP

    Section 2 of this document discussed PHP, a server-side scriptinglanguage that can enable us to produce WWW pages whose content isdynamically generated. Section 4.1 discussed SQL, a language formanipulating 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 theappropriate functions of PHP that enable us to pass SQL statements to aMySQL database.

    The PHP scripts that follow use these functions:

    mysql_connectwhich connects to a MySQL server running on somecomputer 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 requiredwhen a user wants to change a database but an anonymous namecan be used when the user only wishes to inspect the database:

    $connect_result = mysql_connect("mysql.dur.ac.uk", "nobody", "");

    mysql_db_querywhich executes a given SQL query on a givendatabase. For example:

    $query_result = mysql_db_query("Pdcl0bjc_prices",

    "select * from consum where price

  • 8/13/2019 Accessing Databases From the World Wide Web WWW

    23/35

    Guide 106: Accessing databases from the World Wide Web 19

    A page with this form is athttp://www.dur.ac.uk/resources/its/info/guides/106/pricesquery.htm

    When the visitor to the page clicks on the run querybutton, thepricesquery.phpscript will be executed. The code of this script appearsbelow.

    This script first uses mysql_connectto attempt to connect to the MySQLserver. If that succeeds, it assigns to the queryvariable a string containingthe characters:

    SELECT * FROM consum WHERE goods like '%$goods%'

    i.e., a string containing the query in which the visitor is interested. It thencalls the function mysql_db_queryto send this SELECTstatement to thedatabase Pdcl0bjc_prices. If this is successful, the variable query_resultnow 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_rowsfinds out how many rows are in this table. And if

    this is not zero, the script generates an HTML table containing the rows ofdata that are in this table. It does this by using a for command to wanderthrough each row of the table. For each row, it generates HTML containingthe contents of the ID, goodsand pricecolumns.

    http://www.dur.ac.uk/resources/its/info/guides/106/pricesquery.htmhttp://www.dur.ac.uk/resources/its/info/guides/106/pricesquery.htmhttp://www.dur.ac.uk/resources/its/info/guides/106/pricesquery.htm
  • 8/13/2019 Accessing Databases From the World Wide Web WWW

    24/35

    Guide 106:20

    155:

  • 8/13/2019 Accessing Databases From the World Wide Web WWW

    25/35

    Guide 106: Accessing databases from the World Wide Web 21

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

    199:

    200: To insert a new item of consumables:

    201:
    Enter your password:

    202:
    Enter the name of the item:

    203:
    Enter the price of the item in pounds, e.g., 18.45

    204:

    205:

    206:

    207:

    A page with this form is athttp://www.dur.ac.uk/resources/its/info/guides/106/pricesinsert.htm

    When the person using this form clicks on the update consumablesbutton, the script in the file pricesinsert.phpgets executed. This time,because it wants to update the database, the scripts call of mysql_connectneeds to provide a username and a password: for the password, the scriptuses whatever was typed into the passwordbox. And, this time, because thequeryis actually an INSERT, the call of mysql_db_queryreturns either trueor false depending on whether the INSERTwas successful or not. Thescript outputs an appropriate message:

    208:

  • 8/13/2019 Accessing Databases From the World Wide Web WWW

    26/35

    Guide 106:22

    4.5 Providing a WWW page to delete a row

    Finally, we look at how we can provide an HTML form and associated PHPscripts to delete an item from the database. To make sure that we do notdelete items we wish to retain, the first step is to query the databaselooking 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:

    232:

    233: To search for an item of consumables

    234: that you would like to delete:

    235:
    type in part of the name of the item (e.g., Series IV):

    236:

    237:

    238:

    239:

    A page with this form is at

    http://www.dur.ac.uk/resources/its/info/guides/106/pricesdelete.htmThe pricesdelete.phpscript (shown below) uses code like that inpricesquery.phpto produce an HTML table of those items which havenames that match. It follows this by an HTML form asking the visitor to theWWW page to type in the IDof an item that he/she wants to delete from thetable. As we are about to make a change to the database, this form alsoasks the visitor for the password needed to access this database. This formhas two buttons: one is labelled cancel deletion, the other is labelleddelete item. By this means, the visitor is able to change their mind aboutdeleting an item.

    240:

  • 8/13/2019 Accessing Databases From the World Wide Web WWW

    27/35

    Guide 106: Accessing databases from the World Wide Web 23

    258: $numrows = mysql_num_rows($query_result);

    259: if ($numrows==0)

    260: {

    261: print "

    There are no consumables with a name of $goods

    \n";

    262: print "\n";

    263: return;

    264: }

    265: print "\n";

    266: for ($rownum = 0; $rownum

    The above script generates an HTML form, and if a visitor presses either ofits two buttons, the following script (pricesreallydelete.php) is executed. Itdetects which of the two buttons was pressed, and performs an appropriateDELETESQL statement if and only if the visitor pressed the delete itembutton.

  • 8/13/2019 Accessing Databases From the World Wide Web WWW

    28/35

    Guide 106:24

    303:

  • 8/13/2019 Accessing Databases From the World Wide Web WWW

    29/35

    Guide 106: Accessing databases from the World Wide Web 25

    no need to do this if you are using the NPCS or MDS services as thesealready 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/

    2 Ensure that Save it to diskis selected and click on OK.

    3 A Save Asbox appears. Choose some appropriate directory into

    which to save the file. You might want to choose C:\TEMP(or

    C:\WINDOWS\TEMP).

    4 You will need an unzip program (such as WinZip or Info-ZIP or

    PKUNZIP). Info-ZIP is free and is available athttp://www.info-zip.org

    5 Run your unzip program:

    open the .zipfile 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.

    6 Erase the .zipfile from C:\TEMP.

    7 Run the program C:\TODAY\SETUP.EXE.

    8 Click on Continue.

    9 An Install Driversbox appears. Select MySQLand then click on

    OK.

    10 A Data Sourcebox appears. The entry sample-MySQL (MySQL)

    should be appear in the middle of the list. Click on Close.

    11 A Microsoft ODBC Setupbox re-appears. Click on OK.

    12 Remove the files and the directory C:\TODAY.

    5.3 Transferring a table to a MySQL database from Access

    5.3.1 Creating a database in Microsoft Access

    In this section, it is assumed that you have a database in Microsoft Accesswhose tables you wish to transfer to a MySQL database. However, it maybe best to try this out first with some other database. So we first create asimple database with Microsoft Access. Although the following instructionsare appropriate for Access 2003, a similar procedure can be adopted withAccess 2000 or 97.

    1 Get into Microsoft Access; click on Filefollowed by New; then click

    on Blank Database radio button; and then click on OK.

    http://www.dur.ac.uk/its/services/web/publishing/database/odbc/http://www.dur.ac.uk/its/services/web/publishing/database/odbc/http://www.info-zip.org/http://www.info-zip.org/http://www.info-zip.org/http://www.info-zip.org/http://www.info-zip.org/http://www.info-zip.org/http://www.dur.ac.uk/its/services/web/publishing/database/odbc/
  • 8/13/2019 Accessing Databases From the World Wide Web WWW

    30/35

    Guide 106:26

    2 A File New Databasebox appears. In the File namebox, type

    directory.mdband then click on Create.

    3 A Databasebox appears open for Tablesobjects. Double-click on

    Create Table in Design View.

    4 A Tablebox appears. In the Field Namecolumn, type idand thenpress the Tabkey.

    5 In the Data Typecolumn, use the pull-down menu to select

    AutoNumber.

    6 Click on the second row of the table, and in the Field Namecolumn,

    type nameand then press the Tabkey.

    7 In the Data Typecolumn, Textshould appear.

    8 Click on the third row of the table, and in the Field Namecolumn,

    type numberand then press the Tabkey.

    Once again, Textshould appear in the Data Typecolumn.9 Click on File, followed by Save As.

    10 A Save Asbox appears. Overtype the suggested name with phones

    and click on OK.

    11 Click on Nowhen asked if you want to create a primary key.

    12 Select View |Datasheet Viewfrom the Menu bar.

    13 Press the Tabkey; type harold; press the Tabkey; and type 1066.

    14 Press the Tabkey; press the Tabkey again; type maggie; press the

    Tabkey; and type 1979.

    15 Press the Tabkey; press the Tabkey again; type peter; press the

    Tabkey; and type 1812.

    16 Press the Tabkey; press the Tabkey again; typejulius; press the

    Tabkey; and type 44.

    17 Click on Filefollowed by Exit.

    That has created an Access database in the file directory.mdb. Thedatabase has one table called phonesand this table has four records.

    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/

    2 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 dxy3fabis

    replaced by your username.

    3 Click on Create this database.

    http://www.dur.ac.uk/its/services/web/publishing/database/maintenance/admin1/http://www.dur.ac.uk/its/services/web/publishing/database/maintenance/admin1/http://www.dur.ac.uk/its/services/web/publishing/database/maintenance/admin1/http://www.dur.ac.uk/its/services/web/publishing/database/maintenance/admin1/http://www.dur.ac.uk/its/services/web/publishing/database/maintenance/admin1/
  • 8/13/2019 Accessing Databases From the World Wide Web WWW

    31/35

    Guide 106: Accessing databases from the World Wide Web 27

    5.3.3 Transferring a table from Access to a MySQL database

    Here are the steps that are necessary to transfer a table from MicrosoftAccess 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, 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

    Macrosand Modules. Ensure that the TablesObject is selected.

    3 Click once on a table of your Access database. In this example, click

    on the table phones.

    4 Click on File.

    5 Click onExport.

    6 An Export Table box appears.7 In the Save as typepull down menu, choose ODBC Databases().

    (It is probably the last entry of the menu.)

    8 An Exportbox appears. Click on OK.

    9 A Select Data Sourcebox appears. It has two tabs. Ensure that the

    Machine Data Sourcetab 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 onsubsequent occasions. If it is listed move to step 18; otherwise, do thefollowing steps:

    10 Click on New.

    11 A Create New Data Sourcebox appears. Ensure that System Data

    Sourceis checked. Click on Next.

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

    13 Click on Next.

    14 Click on Finish.

    15 A MySQL ODBC DriverDSN Configurationbox appears. In the

    various boxes put the following information:Data Source Name: Pdxy3fab_directory

    Host/Server Name: mysql.dur.ac.uk

    Database Name: Pdxy3fab_directory

    User: dxy3fab

    where dxy3fabis replaced by your username and

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

  • 8/13/2019 Accessing Databases From the World Wide Web WWW

    32/35

    Guide 106:28

    17 Leave the other boxes empty. Click on OK.

    A Select Data Sourcebox reappears. It now has a new entry (e.g.,Pdxy3fab_directory) which is selected.

    18 Ensure that the required entry (e.g., Pdxy3fab_directory) is

    selected. Click on OK. If an Access Deniederror box is displayed,click on OK.

    19 A MyODBC Connectionbox appears. If the Password box is not

    already completed, fill it in now with your MySQL password.

    20 Click on OK.

    If you fail to get an ODBC Call Failederror box, then the table should havebeen satisfactorily transferred to the MySQL server.

    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/

    2 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 MySQLdatabase assume that the table does not exist in the MySQL database.

    Here are some steps that can be used to explore what happens if youattempt 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 phonestable (that is in the

    directory.mdbfile) in some way, e.g., by removing a record from

    the table.

    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 Failederror box. Click on OK.

    The problem is that you cannot transfer a table from Access if the tablealready exists in the database. So, before transferring the table, you firstneed to dropthe table:

    1 Go to the URL

    http://www.dur.ac.uk/its/services/web/publishing/database/main

    tenance/admin1/

    2 In the boxes, type your username, your MySQL password and the

    name of the database (e.g., Pdxy3fab_directory).

    3 Click on Query/update this database.

    4 On the Page Two screen, in the box type in the name of the table

    (e.g., phones).

    http://www.dur.ac.uk/its/services/web/publishing/database/maintenance/listtable/http://www.dur.ac.uk/its/services/web/publishing/database/maintenance/listtable/http://www.dur.ac.uk/its/services/web/publishing/database/maintenance/listtable/http://www.dur.ac.uk/its/services/web/publishing/database/maintenance/admin1/http://www.dur.ac.uk/its/services/web/publishing/database/maintenance/admin1/http://www.dur.ac.uk/its/services/web/publishing/database/maintenance/admin1/http://www.dur.ac.uk/its/services/web/publishing/database/maintenance/admin1/http://www.dur.ac.uk/its/services/web/publishing/database/maintenance/admin1/http://www.dur.ac.uk/its/services/web/publishing/database/maintenance/listtable/http://www.dur.ac.uk/its/services/web/publishing/database/maintenance/listtable/
  • 8/13/2019 Accessing Databases From the World Wide Web WWW

    33/35

    Guide 106: Accessing databases from the World Wide Web 29

    5 Click on Drop this table.

    6 Then attempt to transfer the table again. It should work this time.

    7 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 hasits 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 MySQLdatabase, any existing table of the same name must be dropped before youattempt the transfer.

    5.4 Using a MySQL table from Access

    Instead of transferring a table from Access to a MySQL database everytime that it is altered, you may prefer instead to use Access to alter thetable of the MySQL database.

    In the following steps, it is assumed that you have already transferred thedata 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 dothis.

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

    2 Then, use My Computeror Windows Exploreror a command

    window to rename the file directory.mdbas directory.old.

    On the Networked PC service, you can do this by:

    Click on Start; click on Programsand 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.oldand then press the Enterkey. A

    Renamebox should appear, asking if you are sure you want to

    do this. Click onYes.

    3 Get into Microsoft Access; click on Blank Access database; and

    then click on OK.

    4 A File New Databasebox appears. In the File namebox, typedirectory.mdband then click on Create.

    A Databasebox appears.

    5 Click on the Filebutton on the menu.

    6 Click on Get External Data.

    7 Click onLink Tables.

    8 A Linkbox appears. In the Files of typepull down menu, choose

    ODBC Databases(). (It is probably the last entry of the menu.)

    9 A Select Data Sourcebox appears. It has two tabs. Ensure that the

    Machine Data Sourcetab is selected.

    http://www.dur.ac.uk/its/services/web/publishing/database/maintenance/listtable/http://www.dur.ac.uk/its/services/web/publishing/database/maintenance/listtable/http://www.dur.ac.uk/its/services/web/publishing/database/maintenance/listtable/http://www.dur.ac.uk/its/services/web/publishing/database/maintenance/listtable/http://www.dur.ac.uk/its/services/web/publishing/database/maintenance/listtable/
  • 8/13/2019 Accessing Databases From the World Wide Web WWW

    34/35

    Guide 106:30

    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 onsubsequent occasions. If it is listed move to step 18; otherwise, do thefollowing steps:

    10 Click on New.

    11 A Create New Data Sourcebox appears. Ensure that System Data

    Sourceis checked. Click on Next.

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

    13 Click on Next.

    14 Click on Finish.

    15 A MySQL ODBC DriverDSN Configurationbox appears. In the

    various boxes put the following information:

    Data Source Name: Pdxy3fab_directory

    Host/Server name: mysql.dur.ac.uk

    Database Name: Pdxy3fab_directory

    User: dxy3fab

    where dxy3fabis replaced by your username and

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

    17 Leave the other boxes empty. Click on OK.

    A Select Data Sourcebox reappears. It now has a new entry (e.g.,Pdxy3fab_directory) which is selected.

    18 Ensure that the required entry (e.g., Pdxy3fab_directory) is

    selected. Click on OK. If an Access Deniederror box is displayed,

    click onOK.

    19 A MyODBC Connectionbox appears. If the Password box is not

    already completed, fill it in now with your MySQL password.

    20 Click on OK.

    If you fail to get an ODBC Call Failederror box, then a link to the table in

    the MySQL database should have satisfactorily been set up. A Link Tablesbox appears. This should contain links to the tables (e.g., to phones).

    21 Select one of the tables, and click on OK.

    22 A Select Unique Record Identifierbox may appear. If it does,

    select an appropriate field (e.g., id), and click on OK.

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

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

  • 8/13/2019 Accessing Databases From the World Wide Web WWW

    35/35

    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 WWWsite for PHP ishttp://www.php.net/,you should get faster response fromthe UK mirror site athttp://uk.php.net/.The page about the documentationthat is available for PHP is athttp://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 moresophisticated HTML athttp://uk.php.net/manual/.

    6.2 SQL

    The University Library has a number of books about SQL. Probably thebest is Introduction to SQL: Mastering the Relational Database Language(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 ishttp://www.mysql.com/,you shouldget 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/

    http://www.dur.ac.uk/its/services/web/publishing/database/maintenance/listtable/http://www.dur.ac.uk/its/services/web/publishing/database/maintenance/listtable/http://www.dur.ac.uk/its/services/web/publishing/database/maintenance/listtable/http://www.php.net/http://www.php.net/http://www.php.net/http://uk.php.net/http://uk.php.net/http://uk.php.net/http://uk.php.net/docs.phphttp://uk.php.net/docs.phphttp://uk.php.net/docs.phphttp://uk.php.net/manual/http://uk.php.net/manual/http://uk.php.net/manual/http://www.mysql.com/http://www.mysql.com/http://www.mysql.com/http://www.mirrorservice.org/sites/ftp.mysql.com/http://www.mirrorservice.org/sites/ftp.mysql.com/http://www.webmonkey.com/programming/php/http://www.webmonkey.com/programming/php/http://www.webmonkey.com/programming/php/http://www.mirrorservice.org/sites/ftp.mysql.com/http://www.mysql.com/http://uk.php.net/manual/http://uk.php.net/docs.phphttp://uk.php.net/http://www.php.net/http://www.dur.ac.uk/its/services/web/publishing/database/maintenance/listtable/http://www.dur.ac.uk/its/services/web/publishing/database/maintenance/listtable/