秋凉2018-03-14 21:10:44
class db{
private $dbConfig = [
'db' =>; 'mysql',
'主机' => 'localhost',
'端口' => '3306',
'数据库名称'=> '一个',
'用户' => 'root',
'密码' => '1234',//
'字符集' => 'utf'
];
public $insertId = null;
public $num = 0;
私有静态 $instance = null;
private $conn = null;
私有函数 __construct($params){
$this->dbConfig = array_merge($this->dbConfig,$params);
$this->conncet();
}
私有函数 __clone(){
}
公共函数 getInstance(){
if(!self::$instance instanceof self){
self::$instance = new self();
}
return self::$instance;
}
public function connect(){
try{
$dsn = "{$this->dbConfig['db']}:{$this ->dbConfig['host']};
port = {$this->dbConfig['port']};
字符集 = {$this->dbConfig['charset']}";
$this->conn = new pdo($dsn,$this->dbConfig['user'],$this->dbConfig['password']);
}
catch(PDOExecption $e){
die("数据库连接失败".$e->getMessage());
}
}
//完成数据表的写操作 新增更新
// 返回数据表的记录 如果新增还返回新增主键id
public function exec($sql){
$num = $this->conn->exec($sql);
// 如果有此次的记录
if($num>0){
// 如果是新增操作初始化新增主键ID的属性
if(null !==$this->conn->lastInsertId()){
$this ->insertId = $this->conn->lastInsertId();
}
$this->num = $rum;//返回旅行的记录
}else{
$error = $this->conn->errorInfo(); //获取最后操作的错误信息 【0】错误标识符【1】错误代码【2】错误信息
print '操作失败'.$error[0].':'.$error[1].': '.$error[2];
}
}
//获取单条查询信息
public function fetch ($sql )
{
return $this->conn->query ($sql)->fetch(PDO::FETCH_ASSOC);
}
public function fetchALL($sql){
return $this->conn->query($sql)->fetch( PDO::FETCH_ASSOC);
}
}