/*
* 名称:数据库操作类
* 作用:提供数据库操作方法
*/
include_once("database.php");
class Model{
public $field; //字段
public $tab; //表名
public $where; //条件
public $order; //排序方式
public $limit; //限制条件
public $group;
public $aaa;
function __construct($tab) {
$this->hostname=HOST;
$this->user=USER;
$this->pass=PASS;
$this->dbname=DBNAME;
$this->charset=CHAREST; //gb2312 GBK utf8
$this->linkflag=mysql_connect($this->hostname,$this->user,$this->pass);
mysql_select_db($this->dbname,$this->linkflag) or die("数据库连接失败!!!");
mysql_query("set names ".$this->charset);
$this -> tab = $tab;
}
function field($field) {
$this -> field = $field;
return $this;
}
function where($where) {
$this -> where = "where ".$where;
return $this;
}
function aaa($aaa)
{
$this -> aaa = $aaa;
return $this;
}
function order($order) {
$this -> order = "order by ".$order;
return $this;
}
function group($group) {
$this -> group = " group by ".$group;
return $this;
}
function limit($limit) {
$this -> limit = "limit ".$limit;
return $this;
}
function select($all="") {
if($all) {
$sql = "select $all from {$this -> tab} order by id";
}else{
$sql = "select {$this -> field} from {$this -> tab} {$this -> where} {$this -> group} {$this -> order} {$this -> limit}";
}
$rst = mysql_query($sql);
/*var_dump($sql);*/
while($row = mysql_fetch_assoc($rst)){
$rows[] = $row;
}
return $rows;
}
//更改数据
function update($post){
foreach ($post as $key=>$val){
$sets[] = "{$key} = '{$val}'";
}
$setstr = "set ".join(",", $sets);
$sql = "update {$this->tab} {$setstr} {$this->where} ";
if(mysql_query($sql)){
return mysql_affected_rows();
}else{
return false;
}
}
//添加插入数据
function insert($post){
foreach($post as $key => $val) {
$keys[] = $key;
$vals[] = "'".$val."'";
}
$keystr = join(",", $keys);
$valstr = join(",", $vals);
$sql = "insert into {$this->tab} ({$keystr}) values ({$valstr})";
if(mysql_query($sql)){
return mysql_insert_id();
}else{
return false;
}
}
//删除数据
function delete(){
$sql = "delete from {$this->tab} {$this->where}";
if(mysql_query($sql)){
return mysql_affected_rows();
}else{
return false;
}
}
//获取表的总行数
function total() {
$sql = "select count(*) from {$this -> tab} {$this->where}";
$rst = mysql_query($sql);
$row = mysql_fetch_row($rst);
return $row[0];
}
}
?>