php.Db.class.写法

如题所述

<?php
class Db{
public $host;
public $username;
public $password;
public $database;
public $conn;
public $table;
public $sql;
public $field = '*';

function __construct($host,$username,$password,$database){
$this->host = $host;
$this->username = $username;
$this->password = $password;
$this->database = $database;
$this->connect();
}

function connect(){

$this->conn = new mysqli($this->host, $this->username, $this->password,$this->database);

if ($this->conn->connect_error) {
die("连接失败: " . $this->conn->connect_error);
}
}

function M($table){
$this->table = $table;
return $this;
}

function where($array){
$this->sql = '';
$sql = 'where ';
$one = '';
if($array){
if(is_array($array)){
foreach($array as $key=>$vo){
$one .= '`'.$key.'` = "'.$vo.'" and';
}
$one = trim($one,'and');
$sql .= $one;
$this->sql = $sql;
}else{
$sql .= $array;
$this->sql = $sql;

}
}
return $this;
}

function add($array){
$sql = 'insert into `'.$this->table.'` (';
$one = '';
$two = '';
if($array){
if(is_array($array)){
foreach($array as $key=>$vo){
$one .= '`'.$key.'` ,';
$two .= '"'.$vo.'",';
}
$one = trim($one,',');
$two = trim($two,',');
if($one && $two){
$sql .= $one.') values ('.$two.')';
$this->sql = $sql;

$r = $this->conn->query($this->sql);
if($r){
return mysqli_insert_id($this->conn);
}else{
return false;
}
}
}else{
exit('非数组');
}
}else{
exit('数组为空');
}
}

function select(){
$array = '';
$sql = 'select '.$this->field.' from `'.$this->table.'`'.$this->sql;
$result = $this->conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$array[] = $row;
}
}
return $array;
}
function find(){
$row = '';
$sql = 'select '.$this->field.' from `'.$this->table.'`'.$this->sql.'limit 1';
$result = $this->conn->query($sql);
$row = $result->fetch_assoc();
return $row;
}

function edit($array){
$sql = 'update `'.$this->table.'` set ';
$one = '';
if($array){
if(is_array($array)){
foreach($array as $key=>$vo){
$one .= '`'.$key.'` = "'.$vo.'",';
}
$one = trim($one,',');
$sql .= $one.' '.$this->sql;
}else{
$sql .= $array.' '.$this->sql;
}
$r = $this->conn->query($sql);
if($r){
return true;
}else{
return false;
}
}else{
exit('未接收到参数');
}
}

function delete(){
$sql = 'delete from `'.$this->table.'` ';
$sql .= $this->sql;
$r = $this->conn->query($sql);
if($r){
return true;
}else{
return false;
}
}
function order($data){
$this->sql = $this->sql.' order by '.$data;
return $this;
}

function limit($data){
$this->sql = $this->sql.' limit '.$data;
return $this;
}
function field($data){
$this->field = $data;
return $this;
}

}
$db = new Db('localhost','root','root','database');

?>
温馨提示:答案为网友推荐,仅供参考
相似回答