//数据库类、单例模式
class db{
public $conn;
private static $sql;
private static $instact = null;
private function __construct(){
require_once('db.config.php');
$this->conn = mysql_connect($db['host'],$db['user'],$db['psd']);
if(!mysql_select_db($db['databases'],$this->conn)){
echo "数据库连接错误";
}
mysql_query('set names utf8',$this->conn);
}
public static function getInstance(){
if(is_null(self::$instact)){
self::$instact = new db;
}
return self::$instact;
}
/**
*数据查询
*/
public function select($table,$condition=array(),$field=array()){
$where ="";
if(!empty($condition)){
foreach($condition as $k=>$v){
$where.= $k."='".$v."' and ";
}
$where = "where ".$where." 1=1";
}
if(!empty($field)){
foreach($field as $k=>$v){
$fieldstr.= $v.",";
}
$fieldstr = rtrim($fieldstr);
}else{
$fieldstr = "*";
}
self::$sql = "select {$fieldstr} from {$table} {$where}";
$result = mysql_query(self::$sql);
$i = 0;
while($row = mysql_fetch_assoc($result)){
foreach($row as $k=>$v){
$resultrow[$i][$k] = $v;
}
$i++;
}
var_dump($resultrow);
}
/**
*数据添加
*/
public function insert($table,$data){
$values = "";
$datas = "";
foreach ($data as $k=>$v){
$values.=$k.",";
$datas.="'$v'".",";
}
$values = rtrim($values,',');
$datas = rtrim($datas,',');
self::$sql = "insert into {$table}({$values}) values ({$datas})";
if(mysql_query(self::$sql)){
return mysql_insert_id();
}else{
return false;
};
}
/**
*数据更新
*/
public function update($table,$data,$condition=array()){
$where = "";
if(!empty($condition)){
foreach ($condition as $k=>$v){
$where.= $k."=".$v." and ";
}
$where="where ".$where."1=1";
}
$updatastr = "";
if(!empty($data)){
foreach($data as $k=>$v){
$updatastr.= $k."='".$v."',";
}
$updatastr= "set ".rtrim($updatastr,",");
}
self::$sql = "update {$table} {$updatastr} {$where}";
return mysql_query(self::$sql);
}
/**
*数据 删除
*/
public function delete($table,$condition){
$where = "";
if(!empty($condition)){
foreach( $condition as $k=>$v){
$where.=$k."='".$v."' and ";
}
$where = "where ".$where.'1=1';
}
self::$sql = "delete from {$table} {$where}";
return mysql_query(self::$sql);
}
//打印sql
public function getlastsql(){
echo self::$sql;
}
}
$ne = db::getInstance();
//$ne->update('message',array('user'=>'wanghao','title'=>'sd'),array('id'=>'5'));
//echo $db->insert('message',array('user'=>'张三','title'=>'demo'));
$ne->select('message',array('user'=>'songlin'));
$ne->getlastsql();
?>
数据库的配置文件
db.config.php
$host = "localhost"; //主机地址
$user = "root"; //用户名
$psd= ""; //密码
$databases = "ceshi";
$db = array( "host" =>$host,
"user" =>$user,
"psd" =>$psd,
"databases"=>$databases
);
?>
|