<?php
abstract class DataRecord {
private static $db; // MySQL i-Connection, same for all subclasses
private static $table = array(); // Array of tables for subclasses

public static function init($classname, $table, $db = false) {
if (!($db === false)) self::$db = $db;
self::$table[$classname] = $table;
}

public static function getDB() { return self::$db; }
public static function getTable($classname) { return self::$table[$classname]; }
}

class dbMysqli extends DataRecord {
public static function fetchFromDB() {

$temp = parent::getDB()->query('select * from '.parent::getTable('dbMysqli').';');
while ($row = $temp->fetch_object()){
$result[] = $row;
}

return $result; // An array of UserDataRecord objects
}
}

class dbPdo extends DataRecord {
public static function fetchFromDB() {

$temp = parent::getDB()->query('select * from '.parent::getTable('dbPdo').';');
foreach($temp as $value){
$result[]=$value;
}
return $result; // An array of UserDataRecord objects
}
}
/*
$db = new mysqli('localhost', 'root', '', 'mysql');

dbMysqli::init('dbMysqli', 'user', $db);
$users = dbMysqli::fetchFromDB();
*/


$dsn = 'mysql:dbname=mysql;host=127.0.0.1';
$user = 'root';
$password = '';

try {
$db = new PDO($dsn, $user, $password );
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}

dbPdo::init('dbPdo', 'user', $db);
$users = dbPdo::fetchFromDB();

var_dump($users);

?>

創作者介紹
創作者 shadow 的頭像
shadow

資訊園

shadow 發表在 痞客邦 留言(0) 人氣()