define("userName","root"); define("password","root"); define("dbName","ahcdb"); define("hostName","localhost");
class BaseDao {
function getConnection() { $link = MysqL_connect(hostName,userName,password); if (!$link) die("Could not connect: " . MysqL_error()); if (!MysqL_select_db(dbName)) die("Could not select database: " . MysqL_error()); return $link; }
function setParams(& $sql,$params) {
if($params != null)
$sql = vsprintf($sql,array_map(function($n) {
if(is_int($n))
return (int)$n;
if(is_float($n))
return (float)$n;
if(is_string($n))
return "'".MysqL_real_escape_string($n)."'";
return MysqL_real_escape_string($n);
},$params));
}
function executeQuery($sql,$params,$callback = null) { $link = $this->getConnection(); $this->setParams($sql,$params); $return = null; if(($result = MysqL_query($sql,$link)) != null) if($callback != null) $return = $callback($result,$link); if($link != null) MysqL_close($link); if(!$result) die("Fatal Error: Invalid query '$sql' : " . MysqL_error()); return $return; }
function getList($sql,$callback) {
return $this->executeQuery($sql,function($result,$link) use ($callback) {
$idx = 0;
$list = array();
while ($row = MysqL_fetch_assoc($result))
if($callback != null)
$list[$idx] = $callback($idx++,$row);
return $list;
});
}
function getSingle($sql,$link) use ($callback) {
if ($row = MysqL_fetch_assoc($result))
$obj = $callback($row);
return $obj;
});
}
}
class Example { var $id; var $name;
function Example($id,$name){
$this->id = $id;
$this->name = $name;
}
function setId($id){
$this->id = $id;
}
}
class ExampleDao extends BaseDao {
function getAll(){
return parent::getList("select * from nodes",null,function($idx,$row) {
return new Example($row["id"],$row["name"]);
});
}
function load($id){
return parent::getSingle("select * from nodes where id = %1\$s",array($id),function($row) {
return new Example($row["id"],$row["name"]);
});
}
function update($example){
return parent::executeQuery("update nodes set name = '' where id = -1",$link){
return $result;
});
}
function insert(& $example){
return parent::executeQuery("insert into nodes",$link) use ($example){
$id = MysqL_insert_id($link);
$example->setId($id);
return $result;
});
}
}
$exampleDao = new ExampleDao();
$list = $exampleDao->getAll());
$exampleObject = $exampleDao->load(1));
$exampleDao->update($exampleObject);
?>