Sie sind auf Seite 1von 10

Using an Access Database with PHP

http://www.sitepoint.com/using-an-access-database-with-php/

(http://www.sitepoint.com)

MENU

PHP (http://www.sitepoint.com/php/)

Using an Access Database with PHP

(http://www.sitepoint.com/author/dfrancis/)
David Francis (http://www.sitepoint.com/author/dfrancis/)

Published May 7, 2012


Tweet (Https://twitter.com/share?text=Using+an+Access+Database+with+PHP&via=sitepointdotcom)

Subscribe (Https://confirmsubscription.com/h/y/1FD5B523FA48AA2B)

A previous client of mine had an Access database of products they sell, which they had been using
offline. But increasingly this working arrangement had proven to be limited. There had been too many
instances when they needed to use the database but werent near the computer where they kept their
database.
Wouldnt it have been better for them to able to maintain their database where ever they were? Of
course, but how? Simple put it online. In addition, having their product database online opens the
door to using it as the basis of a website for their business.
Theres another advantage to having an online database, but which is a significant multi-user
access. That is: storing the database on a server means that any authorized person be able to use the
companys product database using nothing more than a browser. And all as a result of moving an
existing Access database file from an offline to an online location.
To make the transition to online databases easier, the existing Access database can be kept
unchanged and simply uploaded to a suitable Windows host. (Linux hosting is possible too, but thats
slightly more complicated.) The hosting is not enough in itself, though, because you also need to build
an interface allowing them to read and write to the database. Building an interface may sound
daunting, but it neednt be. In effect, what youll be doing is replacing the forms listed under the Forms
tab in Access.

1 of 10

4/10/2015 6:30 AM

Using an Access Database with PHP

http://www.sitepoint.com/using-an-access-database-with-php/

In this article Ill focus on the essential elements of PHP youll need to use an existing Access
database online. One other item thats standard with a Windows installation is the availability of ODBC
drivers. These are essential for the use of Access from PHP.

Front-end and Back-end


First of all, lets clarify how the clients Access database would be opened. Normally theyd use
Microsoft Access on their PC, perhaps by double-clicking the icon for the database file. With the
database online, however, they will be opening the database in a browser.
How can a browser be used to open, view, and edit an Access database? Well, think of the MS Access
application as a user interface. As a UI, it has been designed to be used within Windows to read and
write an Access database file. Remember, an Access database file is completely separate from the MS
Access application software. Thus it is possible to build an alternative UI to read and write to an
Access database file. This one just happens to be run using a web browser.
Before getting into the nuts and bolts of the UI, it is important to keep in mind that the data and the
user interface are distinct aspects of a system. Lets take a moment to reinforce a key aspect of using
a browser to access a database hosted on a server.
When using MS Access on a PC to use an Access database (that is, offline), the application software
is the front-end and the database file ( .mdb ) is the back-end. Similarly, when going online, the
browser is the front-end and the database file is the back-end. In other words, the relationship hasnt
changed: it is still a front-end/back-end relationship. The front-end connects to the back-end, and the
back-end stores the data.

The Database
In the example Ive chosen for this article, well use a very simple database that consists of three
tables: a product table, a category table, and a linking product-category table.
The Microsoft Access database contains all the data and table definitions that are relevant to this
article. As per best practice, the data is separated into distinct tables. For example, the list of products
is stored in the product table, and the list of categories is stored in the category table. The
Access database is self-contained, with no links to external tables.
Many products can be of any given category, and any given product can belong to more than one
category. For example, if the database purpose is to store details of silver antiques, a pair of
19th-Century silver cuff-links can be categorised as both 19th-Century and Gifts for Men.

2 of 10

4/10/2015 6:30 AM

Using an Access Database with PHP

http://www.sitepoint.com/using-an-access-database-with-php/

This relationship between the data is shown diagrammatically using Accesss own Relationships
option.

That is, there is a many-to-many relationship between products and categories. Hence the need for
the link table.

Connection to Database
Before reading or writing a database, a connection must be made to it. Windows hosts have a similar
folder hierarchy to a Windows PC, so the location of the files on a Windows server will likely have a
path of the form C:inetpubvhostsexample.comhttpdocs . You should be able to extract the value
of the path to the root folder of your host using the PHP superglobal $_SERVER["DOCUMENT_ROOT"] .
The code needed to connect to the Access database then would be similar to:

<?php

$dbName = $_SERVER["DOCUMENT_ROOT"] . "products\products.mdb";

if (!file_exists($dbName)) {

die("Could not find database file.");

$db = new PDO("odbc:DRIVER={Microsoft Access Driver (*.mdb)}; DBQ=$dbName; Uid=; Pwd=;");

A successful connection will allow SQL commands to be executed from PHP to read or write the
database. If, however, you get the error message PDOException Could not find driver then its likely
that the PDO ODBC driver is not installed. Use the phpinfo() function to check your installation for
references to PDO.
If an entry for PDO ODBC is not present, you will need to ensure your installation includes the PDO
extension and ODBC drivers. To do so on Windows, uncomment the line
extension=php_pdo_odbc.dll in php.ini , restart Apache, and then try to connect to the

database again.
With the driver installed, the output from phpinfo() should include information like this:

3 of 10

4/10/2015 6:30 AM

Using an Access Database with PHP

http://www.sitepoint.com/using-an-access-database-with-php/

SQL Commands
The four basic commands used from PHP are the same as those used within MS Access, namely
SELECT , UPDATE , INSERT , and DELETE . Thus, the following SQL examples should be easy to

follow. Unless, that is, you normally use Accesss Design View, in which you may need an SQL
refresher course.

SELECT row(s)
Suppose you need to get the price for a specific product. This is readily achieved using the id of the
product to select a single field from the product table.

<?php

$sql

$sql .= " WHERE id = " . $productId;

= "SELECT price FROM product";

4
5

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

$row = $result->fetch();

7
8

$productPrice = $row["price"];

After choosing a category from a pull-down list, you can use the category id to query the link table to
obtain a list of products that have been assigned to that category.

4 of 10

4/10/2015 6:30 AM

Using an Access Database with PHP

http://www.sitepoint.com/using-an-access-database-with-php/

<?php

$sql

$sql .= "

$sql .= " WHERE p.id

$sql .= "

$sql .= " ORDER BY name";

= "SELECT p.name, p.description, p.price";


FROM product p, product_category pc";
= pc.productId";

AND pc.category_id = " . $categoryId;

7
8

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

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

10

$productName

11

$productDescription = $row["description"];

12

$productPrice

13

= $row["name"];

= $row["price"];

UPDATE row
Using details provided by an HTML form, you can update a products details.

<?php

$sql

$sql .= "

$sql .= "

price

$sql .= "

sale_status = " . $db->quote($strDescription);

$sql .= " WHERE id = " . $productId;

= "UPDATE product";
SET description = " . $db->quote($strDescription) . ",";
=

" . $strPrice . ",";

7
8

$db->query($sql);

A troublesome character to be wary of is the apostrophe. The apostrophe cant be stored in an Access
table simply as an apostrophe, rather it has to be escaped by another apostrophe. This ensures that
Access knows it is to be stored as an apostrophe and not as the apostrophe that delimits the string.
Fortunately, PHPs PDO library contains a method that prepares strings for storing in a database,
quote() .

INSERT row
You can add a new product to the product table, using details entered in an HTML form.

5 of 10

4/10/2015 6:30 AM

Using an Access Database with PHP

http://www.sitepoint.com/using-an-access-database-with-php/

<?php

$sql

$sql .= "

$sql .= "VALUES (" . $db->quote($strName) . ", " . $db->quote($strDescription) . ", " . $strPrice . ", "

= "INSERT INTO product";


(name, description, price, sale_status) ";

5
6

$db->query($sql);

DELETE row
If a product has been entered by mistake, or is no longer needed in the database, you can delete it
from the product table.

<?php

$sql

$sql .= "

$sql .= " WHERE id = " . $productId;

= "DELETE";
FROM product";

5
6

$db->query($sql);

It could be argued that deleting a product is unlikely as its better to have a suitable status to indicate a
product has been sold or has been archived, etc. Thus, the details would be retained for future
reference.

Summary
The above is the bare bones of what is needed to use an Access database from PHP. I hope it shows
how little PHP is needed for the essential nitty-gritty of reading and writing an Access database, and
how easy it is to understand these basic elements of database interaction using PHP.
Reviewing the above SQL, its clear there were only three PDO ODBC commands required to allow
PHP to access Access, namely, $db = new PDO() , $db->query() , $db->query() , and
$db->quote() . Of course, this is the bare minimum. More complicated databases, and more

complicated websites, will require more SQL than shown in this article, but you have now the basics to
put your own or your clients Access database online using PHP.
Comments on this article are closed. Have a question about PHP? Why not ask it on our forums
(http://www.sitepoint.com/forums/forumdisplay.php?34-PHP?utm_source=sitepoint&utm_medium=link&
utm_campaign=forumlink)?

6 of 10

4/10/2015 6:30 AM

Using an Access Database with PHP

http://www.sitepoint.com/using-an-access-database-with-php/

(http://www.sitepoint.com/author/dfrancis/)

David Francis (http://www.sitepoint.com/author/dfrancis/)


David is a web developer based in England. He is an experienced programmer having developed
software for various platforms including 8-bit CPUs, corporate mainframes, and most recently the Web.
His preference is for simplicity and efficiency, avoiding where possible software that's complex,
bloated, or closed.

(https://plus.google.com/115465223091007176209)

You might also like:


18 Critical Oversights in Web Development
(http://www.sitepoint.com/18-critical-oversightsweb-development/)

Course: PHP & MySQL Web Development for Beginners


(https://learnable.com/courses/php-mysql-web-developmentfor-beginners-13?utm_source=sitepoint&utm_medium=relateditems&utm_content=phpmysql-beginners)

Database Versioning with DBV (http://www.sitepoint.com/database


versioning-dbv/)

7 of 10

4/10/2015 6:30 AM

Using an Access Database with PHP

8 of 10

http://www.sitepoint.com/using-an-access-database-with-php/

Free JavaScript: Novice to Ninja Sample


Get a free 32-page chapter of JavaScript: Novice to Ninja and receive updates on exclusive offers
from SitePoint.

Claim Now

4/10/2015 6:30 AM

Using an Access Database with PHP

http://www.sitepoint.com/using-an-access-database-with-php/

Comments for this thread are now closed.

29 Comments

9 of 10

Guest

How to add UTF-8 support to pdo (odbc) ?


Access database

Robert

Hi David,
I tried to implement your code with:
I also uncommented the line extension=php_pdo_odbc.dll in php.ini and restart Apache. And I am
doing this on my laptop
The errors I received were:
Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[IM002]
SQLDriverConnect: 0 [Microsoft][ODBC Driver Manager] Data source name not found and no
default driver specified' in C:wampwwwjunkie-test-areamdb-test.php on line 6
and
PDOException: SQLSTATE[IM002] SQLDriverConnect: 0 [Microsoft][ODBC Driver Manager] Data
source name not found and no default driver specified in C:wampwwwjunkie-test-areamdb-test.php
on line 6
What am I doing wrong?
Thanks for your help.
Robert
P.S. I enjoyed your interview on the SitePoint podcast.

David

Robert, have you also checked in the PHP extensions folder on your laptop to ensure the
driver file is present? On my laptop, running PHP 5.3.5, it's in C:Program FilesPHPext

Xander Taylor

Hi David,
Firstly, I want to say thanks for a fantastic article ... I'm still learning a lot everyday! I'm working with a
10 year old application at the moment which still uses MDB, but I'm writing in PHP so this was VERY
handy!
Secondly and extremely important ... I want to say a MASSIVE THANKS and WOW!! I never
thought to write my SQL queries like you do above!
01 $sql = "SELECT p.name, p.description, p.price";
02 $sql .= " FROM product p, product_category pc";

4/10/2015 6:30 AM

Using an Access Database with PHP

http://www.sitepoint.com/using-an-access-database-with-php/

About
About us (/about-us/)
Advertise (/advertising)
Press Room (/press)
Legals (/legals)
Feedback (mailto:feedback@sitepoint.com)
Write for Us (/write-for-us)

Our Sites
Learnable (https://learnable.com)
Reference (http://reference.sitepoint.com)
Web Foundations (/web-foundations/)

Connect

(/feed) (/newsletter) (https://www.facebook.com/sitepoint)

(http://twitter.com/sitepointdotcom) (https://plus.google.com/+sitepoint)
2000 2015 SitePoint Pty. Ltd.

10 of 10

4/10/2015 6:30 AM

Das könnte Ihnen auch gefallen