How to query an MS Access Database with PHP

Below is a simple PHP script to demonstrate how to connect to an MS Access database using ODBC DSN.  For more information on ODBC with PHP, please review the following:

<html>
<head><title>PHP Access TEST</title></head>
<body>
<h2>Access Database / DSN Test</h2>
<table border="1">

<?php
 $DSN="myODBC_DSN";
 $DSN_User="";
 $DSN_Passwd="";
 $QueryString="SELECT id, FirstName, LastName, Email FROM tblContact";
 
 $Connect = odbc_connect( $DSN, $DSN_User, $DSN_Passwd );
 $Result = odbc_exec( $Connect, $QueryString );
 
 echo "\t" . "<tr>\n";
 echo "\t\t" . "<td>id</td><td>FirstName</td><td>LastName></td><td>Email</td>" . "\n";
 
 while( odbc_fetch_row( $Result ) )
 {
  $id  = odbc_result($Result,"id");
        $FirstName  = odbc_result($Result,"FirstName");
        $LastName  = odbc_result($Result,"LastName");
        $Email  = odbc_result($Result,"Email");

  echo "\t" . "<tr>\n";
  echo "\t\t" . "<td>" . $id . "</td><td>" . $FirstName . "</td><td>" . $LastName . "</td><td>" . $Email . "</td>\n";
  echo "\t" . "</tr>\n";
 }
 
 odbc_free_result( $Result );
 odbc_close( $Connect );
?>
</table>

</body>
</html>


If you run into problems when using this code, please post in our community forum. Technical support is unable to assist with specific coding issues.

Article ID: 374, Created On: 11/24/2008, Modified: 1/6/2011