if you ever need to connect to an access database (on the server, using the IIS or APACHE user account), here is code below that can help to ease the process. It is written like this because we have a MySQL as well as an Access database and need to be able to switch back and forth. The runQuery function will return a 2 dimensional array and can use column names or numbers for the index of the internal arrays. External arrays are always integer-indexed. We also have found issues with Access staying open and growing from 7MB to 2.5GB within two hours, so we open and close it each time we run a query. If it is not a select query it will return TRUE. if it fails with errors, it will return false.
There is a showErr flag that we mostly only use for MySQL, since you can output MySQL errors without PHP errors. Access doesn't appear to be that friendly.
<?php
function runQuery(&$conn,
$strSQL,
$associative=true,
$debug=false,
$showSQL=false,
$showErr=false) {
return runMSQuery($conn,$strSQL,$associative,$debug,$showSQL,$showErr);
}
function openMSDB($dbfile="c:/path/and/filename.mdb") {
if (!@$conn = new COM("ADODB.Connection"))
exit("Unable to create an ADODB connection<br>");
$strConn = "DRIVER={Microsoft Access Driver (*.mdb)}; DBQ=".$dbfile;
@$conn->open($strConn);
if($conn->State == 0) return false;
return $conn;
}
function closeMSDB(&$conn) {
@$conn->Close();
$conn = null;
return true;
}
function runMSQuery(&$conn,
$strSQL,
$associative=true,
$debug=false,
$showSQL=false,
$showErr=false) {
if(!is_object($conn)) if(!$conn=openMSDB()) return false;
if( $showSQL || $debug ) echo $strSQL."\n<br>\n";
$rtn = false;
if($debug) $rs = $conn->execute($strSQL);
else $rs = @$conn->execute($strSQL);
if(!$rs) {
if($showErr) echo "Error running SQL.<br>\n";
closeMSDB($conn);
return false;
}
if ($rs->State == 0) {
closeMSDB($conn);
return true;
} else {
$rows=0;
while(!$rs->EOF) {
for($i=0;$i<$rs->Fields->count;$i++) {
$rsf = $rs->Fields($i);
if($associative) $rtn[$rows][$rsf->Name] = $rsf->value;
else $rtn[$rows][$i] = $rsf->value;
}
$rows++;
$rs->MoveNext();
}
if($rs->State != 0) $rs->Close();
$rs = null;
}
if($debug) var_dump($rtn);
closeMSDB($conn);
return $rtn;
}
?>