Til inspiration:
<?php
abstract class DAL {
private $con;
protected function __construct($constr, $un, $pw) {
$this->con = new PDO($constr, $un, $pw);
$this->con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
private function get($sqlstr, $parm) {
$stmt = $this->con->prepare($sqlstr);
foreach($parm as $parmkey => $parmval) {
$stmt->bindValue($parmkey, $parmval, gettype($parmval) == "integer" ? PDO::PARAM_INT : PDO::PARAM_STR);
}
$stmt->execute();
return $stmt->fetchAll();
}
public function get_all() {
return $this->get('SELECT f1,f2 FROM t1', array());
}
public function get_n($n) {
return $this->get($this->get_select_n(), array(':n' => $n));
}
protected abstract function get_select_n();
}
class MySQL_DAL extends DAL {
public function __construct($host, $db, $un, $pw) {
parent::__construct(sprintf('mysql:host=%s;dbname=%s', $host, $db), $un, $pw);
}
protected function get_select_n() {
return 'SELECT f1,f2 FROM t1 ORDER BY f1 LIMIT :n';
}
}
class SQLServer_DAL extends DAL {
public function __construct($host, $db) {
parent::__construct(sprintf('sqlsrv:server=%s;database=%s', $host, $db), '', '');
}
protected function get_select_n() {
return 'SELECT f1,f2 FROM (SELECT f1,f2,ROW_NUMBER() OVER (ORDER BY f1) AS rownum FROM t1) x WHERE rownum <= :n';
}
}
try {
$dal1 = new MySQL_DAL('localhost', 'Test', 'root', '');
$resall1 = $dal1->get_all();
foreach($resall1 as $row) {
echo $row['f1'] . ' ' . $row['f2'] . "\r\n";
}
$ressome1 = $dal1->get_n(2);
foreach($ressome1 as $row) {
echo $row['f1'] . ' ' . $row['f2'] . "\r\n";
}
$dal2 = new SQLServer_DAL('(local)', 'Test');
$resall2 = $dal2->get_all();
foreach($resall2 as $row) {
echo $row['f1'] . ' ' . $row['f2'] . "\r\n";
}
$ressome2 = $dal2->get_n(2);
foreach($ressome2 as $row) {
echo $row['f1'] . ' ' . $row['f2'] . "\r\n";
}
} catch (PDOException $ex) {
die($ex->getMessage());
}
?>