一个简单的dao,实现基本的crud功能,可以继承扩展为实际业务的dao类,当然也可以直接使用
复制代码 代码如下:
_con == null) {
$this->_con = @mysql_connect(localhost, root, 123456);
if ($this->_con == false) {
echo(connect to db server failed.);
$this->_con = null;
return;
}
//$firephp->log(new dao object);
@mysql_select_db(swan, $this->_con);
}
}
public function table($tablename) {
$this->_table = $tablename;
return $this;
}
public function query($sql) {
$result = @mysql_query($sql);
$ret = [];
if ($result) {
while ($row = mysql_fetch_array($result)) {
$ret[] = $row;
}
}
return $ret;
}
public function get($where = null) {
$sql = select * from .$this->_table;
$sql = $sql.$this->_getwherestring($where);
//echo [get].$sql.
;
return $this->query($sql);
}
public function insert($params) {
if ($params == null || !is_array($params)) {
return -1;
}
$keys = $this->_getparamkeystring($params);
$vals = $this->_getparamvalstring($params);
$sql = insert into .$this->_table.(.$keys.) values(.$vals.);
//echo [insert].$sql.
;
$result = @mysql_query($sql);
if (! $result) {
return -1;
}
return @mysql_insert_id();
}
public function update($params, $where = null) {
if ($params == null || !is_array($params)) {
return -1;
}
$upvals = $this->_getupdatestring($params);
$wheres = $this->_getwherestring($where);
$sql = update .$this->_table. set .$upvals. .$wheres;
//echo [update].$sql.
;
$result = @mysql_query($sql);
if (! $result) {
return -1;
}
return @mysql_affected_rows();
}
public function delete($where) {
$wheres = $this->_getwherestring($where);
$sql = delete from .$this->_table.$wheres;
//echo [delete].$sql.
;
$result = @mysql_query($sql);
if (! $result) {
return -1;
}
return @mysql_affected_rows();
}
protected function _getparamkeystring($params) {
$keys = array_keys($params);
return implode(,, $keys);
}
protected function _getparamvalstring($params) {
$vals = array_values($params);
return '.implode(',', $vals).';
}
private function _getupdatestring($params) {
//echo _getupdatestring;
$sql = ;
if (is_array($params)) {
$sql = $this->_getkeyvalstring($params, ,);
}
return $sql;
}
private function _getwherestring($params) {
//echo _getwherestring;
$sql = ;
if (is_array($params)) {
$sql = where ;
$where = $this->_getkeyvalstring($params, and );
$sql = $sql.$where;
}
return $sql;
}
private function _getkeyvalstring($params, $split) {
$str = ;
if (is_array($params)) {
$paramarr = array();
foreach($params as $key=>$val) {
$valstr = $val;
if (is_string($val)) {
$valstr = '.$val.';
}
$paramarr[] = $key.=.$valstr;
}
$str = $str.implode($split, $paramarr);
}
return $str;
}
public function release() {
@mysql_close();
}
}
function t($table) {
return (new simpledao())->table($table);
}
?>
,