Connecting PHP to a Microsoft Access Database

My youngest son is learning how to code.

He is working on a PHP fitness application.

He’s built his demo app using PHP and MySQL and I want to run the code on my PC but I don’t have MySQL and don’t want to install it either.

Instead, I’ll try to do something much harder.

I’ll make his code connect to a Microsoft Access Database instead.

It was harder than I thought it would be initially.
I tried an ODBC connection but had to abandon it after having way too many issues running 32-bit ODBC drivers on 64 bit Windows that is trying to Microsoft Access Database files. 

To get this to work, I had to enable an ODBC dll in the PHP.ini file.  Then trial and error coding until I found some code that works but I ended up having to learn about PHP PDO and use that for connecting to the Access Database instead of a strait OBDC connection.

Configuring PHP to use a Microsoft Access Database

  1. Enable an ODBC.dll in the PHP.ini file
  2. Use code below to connect to the Microsoft Access Database using PHP PDO

PHP code I used to connect a PHP page to a Microsoft Access Database

<?php
try {
    $dbName = $_SERVER["DOCUMENT_ROOT"] . "phpFitness_Trackerlifting_tracker.mdb";
    if (!file_exists($dbName)) {
        die("Could not find database file." . $_SERVER["DOCUMENT_ROOT"] . "phpFitness_Trackerlifting_tracker.mdb" );
    }

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

    /*** The SQL SELECT statement ***/
    $sql = "SELECT * FROM lifting_tracker";
    /*** fetch into an PDOStatement object ***/
    $stmt = $db->query($sql);
    $stmt2 = $db->query($sql);
    /*** echo number of columns ***/
    $result = $stmt->fetch(PDO::FETCH_ASSOC);
    /*** loop over the object directly ***/
    foreach($result as $key=>$val) {
        echo $key.' - '.$val.'<br />';
        echo 'Reps: ' . $result['reps']. '<br />';
    }
    /*** loop over the object directly ***/
    while ($row = $stmt2->fetch(PDO::FETCH_ASSOC))
    {
      echo 'This is from the while loop! ' . $row['reps']. '<br />';
    }
}
catch(PDOException $e) {
    echo $e->getMessage();
}
$db = null;
?>

Author: Rick Cable / AKA Cyber Abyss

A 16 year US Navy Veteran with 25+ years experience in various IT Roles in the US Navy, Startups and Healthcare. Founder of FinditClassifieds.com in 1997 to present and co-founder of Sports Card Collector Software startup, LK2 Software 1999-2002. For last 7 years working as a full-stack developer supporting multiple agile teams and products in a large healthcare organization. Part-time Cyber Researcher, Aspiring Hacker, Lock Picker and OSINT enthusiast.