I'm trying to create a class for my access database connection and return a recordset, then iterate through the RS with MoveNext().
class AccessDBConnection
{
private $db;
private $sql;
function __construct($db, $sql) {
$conn = new COM('ADODB.Connection') or exit('Cannot start ADO.');
$conn->Open("DRIVER={Microsoft Access Driver (*.mdb)}; DBQ=$db");
$rs = $conn->Execute($sql);
return $rs;
}
USE:
function testclass () {
$rs = new AccessDBConnection("e:\database.mdb", "SELECT StudentID, UserName FROM MyTable WHERE StudentID = 'BJxxxx'");
while (!$rs->EOF) {
$SID = $rs->Fields['StudentID']->Value;
$UN = $rs->Fields['UserName']->Value;
echo $SID . " -- CLASS TEST -- " . $UN . "<br>";
$rs->MoveNext();
}
}
You can't return your resultset from constructor.
Create some separated method like getRS
which will returns it.
class AccessDBConnection
{
private $conn;
public function __construct($db) {
$this->conn = new COM('ADODB.Connection') or exit('Cannot start ADO.');
$this->conn->Open("DRIVER={Microsoft Access Driver (*.mdb)}; DBQ=$db");
}
public function query($sql) {
return $this->conn->Execute($sql);
}
}
Usage:
function testclass () {
$db = new AccessDBConnection("e:\database.mdb");
$rs = $db->query("SELECT StudentID, UserName FROM MyTable WHERE StudentID = 'BJxxxx'");
while (!$rs->EOF) {
$SID = $rs->Fields['StudentID']->Value;
$UN = $rs->Fields['UserName']->Value;
echo $SID . " -- CLASS TEST -- " . $UN . "<br>";
$rs->MoveNext();
}
}
Constructors do not return. So calling:
$rs = new AccessDBConnection($db, $sql);
Will not yield a recordset.
Some general pointers:
__construct
so as to make testing easier should you come to itpublic function connect()
which performs the connectionAlternatively find an wrapper class that has already done the legwork. No sense in rewriting the wheel.