How to connect PHP with Microsoft Access database

user2503040 picture user2503040 · Nov 6, 2013 · Viewed 100.1k times · Source

I am currently faced with a new challenge to develop a site using Microsoft Access as the primary database instead of mysql. I have not used MS Access before and I would like guidiance on how to go about it, I have looked up the w3c website on W3schools but the code gives error

Warning: odbc_connect() [function.odbc-connect]: SQL error: [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified, SQL state IM002 in SQLConnect in C:\Users\NNALI\Desktop\root\test.php on line 2

and this error

Warning: odbc_exec() expects parameter 1 to be resource, boolean given in C:\Users\NNALI\Desktop\Breweries\root\test.php on line 4

I am stuck and do not know what to do, I would appreciate all help on this.

<?php
    $conc = odbc_connect("northwind", "","");
    $sql  = "Select * From customers";
    $rs   = odbc_exec($conn, $sql);
?>

Above is the code I used

Answer

Gord Thompson picture Gord Thompson · Nov 6, 2013

If you are just getting started with a new project then I would suggest that you use PDO instead of the old odbc_exec() approach. Here is a simple example:

<?php
$bits = 8 * PHP_INT_SIZE;
echo "(Info: This script is running as $bits-bit.)\r\n\r\n";

$connStr = 
        'odbc:Driver={Microsoft Access Driver (*.mdb, *.accdb)};' .
        'Dbq=C:\\Users\\Gord\\Desktop\\foo.accdb;';

$dbh = new PDO($connStr);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

$sql = 
        "SELECT AgentName FROM Agents " .
        "WHERE ID < ? AND AgentName <> ?";
$sth = $dbh->prepare($sql);

// query parameter value(s)
$params = array(
        5,
        'Homer'
        );

$sth->execute($params);

while ($row = $sth->fetch()) {
    echo $row['AgentName'] . "\r\n";
}

NOTE: The above approach is sufficient if you do not need to support Unicode characters above U+00FF. If you do need to support such characters then neither PDO_ODBC nor the old odbc_ functions will work; you'll need to use the solution described in this answer.