PHP and Microsoft Access database – Connection and CRUD

PDO

If you want to interface with an MS Access database using PHP, PDO is available for you.

<?php
    try {
        $pdo = new PDO("odbc:Driver={Microsoft Access Driver (*.mdb)};Dbq=C:\accounts.mdb;Uid=Admin");
    }
    catch (PDOException $e) {
        echo $e->getMessage();
    } 

When using PDO, due to the unified interface for DB operations, you have the opportunity to make your app more portable across various RDBMs systems. All you have to do is to provide the connection string to the PDO new instance and have the correct PDO driver installed.

As the result of this unified interface, your application can be easily ported from MS Access to MySQL, SQLite, Oracle, Informix, DB2, etc. which most certainly is the case if it ages enough.

Here’s an insertion example:

<?php
try {
   // Connect, 
   // Assuming that the DB file is available in `C:\animals.mdb`
   $pdo = new PDO("odbc:Driver={Microsoft Access Driver (*.mdb)};Dbq=C:\animals.mdb;Uid=Admin");

    // INSERT data
    $count = $pdo->exec("INSERT INTO animals(animal_type, animal_name) VALUES ('kiwi', 'troy')");

    // echo the number of affected rows
    echo $count;

    // close the database connection
    // See: http://php.net/manual/en/pdo.connections.php
    $pdo = null;
}
catch (PDOException $e) {
    echo $e->getMessage();
}

ODBC

In case you don’t want to use PDO for some insane reasons, you can look into ODBC.

Here’s an example:

<?php

if (! $conn = odbc_connect('northwind', '', '')) {
    exit("Connection Failed: $conn");
}

if (! $rs = odbc_exec($conn, 'SELECT * FROM customers')) {
    exit('Error in SQL');
}

while (odbc_fetch_row($rs)) {
  echo 'Company name: ', odbc_result($rs, 'CompanyName'), PHP_EOL;
  echo 'Contact name: ', odbc_result($rs, 'ContactName'), PHP_EOL;
}

odbc_close($conn);

Leave a Comment