ms access db odbc and php

9
Microsoft Access Database ODBC and PHP Copyright Notice © 2002 - 2005 - The Web Freaks, INC, PHP Freaks.com All rights reserved. No parts of this work may be reproduced in any form or by any means - graphic, electronic, or mechanical, including photocopying, recording, taping, or information storage and retrieval systems - without the written permission of the publisher. Products that are referred to in this document may be either trademarks and/or registered trademarks of the respective owners. The publisher and the author make no claim to these trademarks. While every precaution has been taken in the preparation of this document, the publisher and the author assume no responsibility for errors or omissions, or for damages resulting from the use of information contained in this document or from the use of programs and source code that may accompany it. In no event shall the publisher and the author be liable for any loss of profit or any other commercial damage caused or alleged to have been caused directly or indirectly by this document. Last Update: Thu, 20 Mar 2003 00:00:00 -0500

Upload: jewelbd

Post on 11-Apr-2015

1.251 views

Category:

Documents


1 download

TRANSCRIPT

Page 1: Ms Access Db Odbc and Php

Microsoft Access Database ODBC and PHP

Copyright Notice

© 2002 − 2005 − The Web Freaks, INC, PHP Freaks.com

All rights reserved. No parts of this work may be reproduced in any form or by any means − graphic,electronic, or mechanical, including photocopying, recording, taping, or information storage and retrievalsystems − without the written permission of the publisher.

Products that are referred to in this document may be either trademarks and/or registered trademarks of therespective owners. The publisher and the author make no claim to these trademarks.

While every precaution has been taken in the preparation of this document, the publisher and the authorassume no responsibility for errors or omissions, or for damages resulting from the use of informationcontained in this document or from the use of programs and source code that may accompany it. In no eventshall the publisher and the author be liable for any loss of profit or any other commercial damage caused oralleged to have been caused directly or indirectly by this document.

Last Update: Thu, 20 Mar 2003 00:00:00 −0500

Page 2: Ms Access Db Odbc and Php
Page 3: Ms Access Db Odbc and Php

Table of ContentsMicrosoft Access Database ODBC and PHP....................................................................................................1

Welcome to ODBC with PHP.................................................................................................................1Our Test System.......................................................................................................................................1Preparing the Database............................................................................................................................1

Setting up an ODBC Source..............................................................................................................2Microsoft Access Database, ODBC and PHP..........................................................................................3

odbc_fetch_array Custom Function..................................................................................................4Summary..................................................................................................................................................5

Tutorial Revision History:.................................................................................................................6

PHP Help: Microsoft Access Database ODBC and PHP

i

Page 4: Ms Access Db Odbc and Php

Microsoft Access Database ODBC and PHPNavigate: PHP Tutorials > PHP > Databases > ODBC / Access

Author: phpfreakDate: 03/20/2003Version 1.1Experience Level: Intermediate

Welcome to ODBC with PHP

Recently I was tasked to port a MySQL database that I had been working on over to an Microsoft Accessdatabase file. Although I was not thrilled about doing this, during my research and implementation, I learned afew new tricks with PHP. During the course of this tutorial I'll share my findings with you.

The main reason I had to switch to a Microsoft Access database on the site I was uing MySQL is because weneeded a method for multiple people to manage the database and we needed a method to make the databaseportable. We wanted to have the ability to pick up the database, put it on a floppy or a CD or even email it to adifferent computer and access the information outside of the intranet. These were our reasons, you may findother reasons to use the methods in this tutorial as well.

You'll be quite suprised that configuring your existing PHP script to use Open Database Connectivity(ODBC) is not too much different than using MySQL. The queries are nearly the same with the exception of afew less MySQL query functions. ODBC is also less forgiving than MySQL so you have to be very careful.

Our Test System

During the setup, we tested these methods on Microsoft Windows 2000 Professional and Microsoft WindowsXP Professional running Apache 1.3.27 and PHP 4.2.3. You'll also need to ensure that you have MicrosoftData Access Components (MDAC) installed. If you are using one of the operating systems that I havementioned, you are more than likely available to access them already. If not, you can grab MDAC here at theMicrosoft Data Access page.

Lets begin preparing our databases and configuring our ODBC sources.

Preparing the Database

First, we'll need to create a database file. I simply opened up Microsoft Access and created a database tablewith a few columns in it.

Note: There are some converters out there that work pretty good at converting an existing MySQL database toAccess. Here's one that I used: Intelligent Converter MySQL to Access Converter It works ok, but I still had

Microsoft Access Database ODBC and PHP 1

Page 5: Ms Access Db Odbc and Php

to tidy up my tables and columns after it was completed. Enum and Date or TIMESTAMP fields do notconvert to well.

Setting up an ODBC Source

Once MDAC is installed, you can go to Start Menu >> Settings >> Control Panel >> Administrative Tools>> Data Sources (ODBC)

Select the System DSN Tab and then click on "Add" and you'll see this window below:

Next, we'll need to add our Microsoft Access Database file. Click on the driver called "Microsoft AccessDriver (*.mdb)" and click Finish. You'll be presented with this window below:

PHP Help: Microsoft Access Database ODBC and PHP

Preparing the Database 2

Page 6: Ms Access Db Odbc and Php

In the Data Source Name field, you should enter something that you'll remember to identify the connectionwith. In my example here, I've used "TestDB" and then entered a small description into the Description field.

Next, you'll have to select the database file. Click on the "Select" button and you'll be presented with a filebrowser window. Select your file and click Ok.

Note: if you wish to add security to your ODBC connection, click on the "Advanced.." tab and enter ausername and password there. In this example, I have entered "root" as the username and left the passwordblank.

Click OK and close the remaining windows and now you have completed the ODBC connection setup.

Let's see how to connect to an ODBC source in PHP on the next page.

Microsoft Access Database, ODBC and PHP

Now that we have our database prepared and our ODBC connection setup, let's create our connection script.

The script will look something like this:

PHP Example:

<?php$odbc = odbc_connect ('TestDB', 'root', '') or die('Could Not Connect to ODBC Database!');?>

Now if everything works fine, we should have a good connection. No need to select a database like MySQLbecause we pretty much did that when we configured our ODBC connection.

Tip: I put this code in it's own file and called it "odbc.php" and I'll include that into every file that I need tomake a connection with.

PHP Help: Microsoft Access Database ODBC and PHP

Setting up an ODBC Source 3

Page 7: Ms Access Db Odbc and Php

odbc_fetch_array Custom Function

Before we move along much further, I need to show you something that I found in the user comments of thePHP Manual. In MySQL you have a function called mysql_fetch_array() which allows you to fetch an arrayof results from the query. In PHP's ODBC functions, that does not exists at the moment. So, in my "odbc.php"file that I include into my other files using this ODBC connection, I put this code to allow usage of the samefunction:

PHP Example:

<?if(!function_exists('odbc_fetch_array')){ function odbc_fetch_array($result, $rownumber=−1) { if (PHP_VERSION > '4.1') { if ($rownumber < 0) {

odbc_fetch_into($result, $rs); } else {

odbc_fetch_into($result, $rs, $rownumber); } } else {

odbc_fetch_into($result, $rownumber, $rs); }

$rs_assoc = Array();

foreach ($rs as $key => $value) {

$rs_assoc[odbc_field_name($result, $key+1)] = $value; } return $rs_assoc; }}?>

This function appears to work very much compared to the mysql_fetch_array() functions.

Let's build a simple query using our PHP Script on the next page.

In our database, we have a table that looks like this:

Table: Customers

customer_id AutoNumber Long Integer

customer_first_name Text 30

customer_last_name Text 30

email_address Text 30

PHP Help: Microsoft Access Database ODBC and PHP

odbc_fetch_array Custom Function 4

Page 8: Ms Access Db Odbc and Php

So, based on that table, we'll pull our query in this PHP script:

PHP Example:

<?phprequire_once('odbc.php');

$query = odbc_exec($odbc, "SELECT * FROM Customers") or die (odbc_errormsg());while($row = odbc_fetch_array($query)){ echo 'Customer First Name: '.$row['customer_first_name'].'<br />'; echo 'Customer Last Name: '.$row['customer_last_name'].'<br />'; echo 'Customer Email: '.$row['email_address'].'<br />'; echo '<hr />';}odbc_close($odbc);?>

Ok, let's discuss the above code. We've started out by including the odbc.php file and that established ourconnection to the database. Next, we used a function called odbc_exec() which performed our query almostexactly like you would in a MySQL query. If we had any problems with the query, the script should have diedand left you with the output from the odbc_errormsg()function for debugging.

The rest of the query is pretty familiar if you use the mysql_fetch_array() function, except, we are using ourcustom odbc_fetch_array() function that we included into our "odbc.php" file.

Finally, after displaying my output, I added an odbc_close()function on the end of my script. This shouldclose the connection to the database and unlock it. I have had different results from using this, but accordingto the manual, it should work properly.

Let's wrap up ODBC on the next page!

Summary

I wanted to take this opportunity to write another tutorial and share my findings with you. In my opinion,ODBC is not ideal for everyone. It's something that you'll have to carefully consider your application of. As Itold you in my initial remarks, I was forced to go this route because we had to change our database type andstill maintain the same front−end that was used during the original design. Obviously, if you are concernedabout speed, I'd definately try to use MySQL if possible.

Even though this tutorial was a short one, don't under estimate ODBC connections. You are only limited tothe database itself. I have found a few things that I do not like about ODBC and Microsoft Access. A few ofthem were primarily the DATE column handling. It's not as flexible as MySQL.

I have read applications of ODBC on Linux, however I have not tried them. If you have been successful onLinux with ODBC, please drop us a message and tell how you did it.

Please click on our banners and help keep this site open!

PHP Help: Microsoft Access Database ODBC and PHP

Summary 5

Page 9: Ms Access Db Odbc and Php

Tutorial Revision History:

Revision: 1.1Date: 04/05/2005User: phpfreakRemarks: Updated for new website, fixed up code.

Revision: 1.0Date: 03/20/2003User: phpfreakRemarks: Initial Submission

© Copyright 2002 − 2005 The Web Freaks, INC.

PHP Help: Microsoft Access Database ODBC and PHP

Tutorial Revision History: 6