舉例
$obj = new Obj();
$name = $obj->table('test')->where('id','>','3')->get(['id','time']);
鏈?zhǔn)胶瘮?shù)其實是每次執(zhí)行這個函數(shù)的時候,
1.給這個函數(shù)中的屬性賦值,
2.返回本類return $this
下面的一個類是模仿類似于
laravel DB類的一種寫法
<?php
class Obj
{
private $sql_connect;
private $where = '';
/**
* Obj constructor. 我這里是用了直接連接好的mysql變量
*/
public function __construct()
{
global $sql_connect;
$this->sql_connect = $sql_connect;
}
public function table($table)
{
$this->table = $table;
return $this;
}
public function where($k='',$gt='=',$v='')
{
// 如果有傳遞參數(shù),則給$this->>where 賦值 ,
if ($k){
if (!$v){
$this->where = "where $k = $gt";
}else{
$this->where = "where $k $gt $v";
}
}
// 否則,就不用做處理,因為有 where屬性默認(rèn)值是空 where=''
return $this;
}
public function get($val='*')
{
// 如果是數(shù)組,則拆分,不是數(shù)組則取值全部
if ($val && is_array($val)){
$val = implode(',',$val);
}
$res = $this->le_db1->query("select $val from $this->table $this->where");
// 去掉數(shù)字的鍵
$array = $res->fetchAll();
foreach ($array as $key=>$value){
foreach ($value as $k => $val){
if (is_numeric($k)){
unset($array[$key][$k]);
}
}
}
return $array;
}
public function insert($arr)
{
// 判斷是一維還是二維數(shù)組
if (count($arr) == count($arr,1)){
// 一維數(shù)組
$keys = array_keys($arr);
$from = '('.implode(',',$keys).')';
$to = '(\''.implode('\',\'',$arr).'\')';
}else{
// 二維數(shù)組 取出第一組數(shù)組中的鍵就是要插入數(shù)據(jù)的鍵
$keys = array_keys($arr[0]);
$to = '';
$from = '('.implode(',',$keys).')';
foreach ($arr as $key => $value){
$to = $to.'(\''.implode('\',\'',$value).'\'),';
}
$to = rtrim($to,',');
}
$this->le_db1->query("insert into $this->table $from VALUES $to");
// 返回最后一個id
return $this->le_db1->lastInsertId();
}
public function update($arr)
{
$set = '';
foreach ($arr as $key=>$value){
// 如果是字符串,要添加引號
if (is_string($value)){
$value = "'$value'";
}
$set = $set.$key.'='.$value.',';
}
$set = rtrim($set,',');
$res = $this->le_db1->query("update $this->table set $set $this->where");
return $res->rowCount();
}
public function delete()
{
// 防止刪除全部表,此處可以做where限制
if (!$this->where){
return '請謹(jǐn)慎操作,不要刪除全部表數(shù)據(jù)';
}
$res = $this->le_db1->query("delete from $this->table $this->where");
return $res->rowCount();
}
}
注意事項
方法中的參數(shù)最好要寫默認(rèn)值,否則使用的時候如果沒有傳遞值,是會報錯的,比如
$where = '';使用方式
- 獲取
id>3的'id','time'字段
$obj = new Obj();
$res = $obj->table('test')->where('id','>','3')->get(['id','time']);
echo '<pre>';
print_r($res);
2.獲取全部數(shù)據(jù)
$obj = new Obj();
$res = $obj->table('test')->where()->get();
或者
$res = $obj->table('test')->get();
插入數(shù)據(jù)的使用
$obj = new Obj();
$res = $obj->table('test')->insert([['test'=>'4','time'=>'4'],['test'=>'5','time'=>'5'],['test'=>'6','time'=>'6']]);
$res = $obj->table('test')->insert(['test'=>'4','time'=>'4']);
刪除
$res = $obj->table('test')->where('id',2)->delete();
更新
$res = $obj->table('test')->where('id',3)->update(['test'=>4]);