-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSql.php
94 lines (83 loc) · 2.55 KB
/
Sql.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
<?php
class Sql
{
private $db_type;
private $db_host;
private $db_name;
private $username;
private $password;
private $hostport;
protected static $pdo;
public static $_config;
//构造方法链接数据库
public function __construct()
{
$this->db_type = self::$_config['db_type'];
$this->db_host = self::$_config['db_host'];
$this->db_name = self::$_config['db_name'];
$this->username = self::$_config['username'];
$this->password = self::$_config['password'];
$this->hostport = self::$_config['hostport'];
self::$pdo = new PDO("$this->db_type:host=$this->db_host;dbname=$this->db_name",$this->username,$this->password);
}
//处理SQL语句
private function handleSql($arr,$type)
{
$sql = "";
foreach ($arr as $key => $val){
if (is_numeric($val)){
$sql .= "$key = $val $type";
}else{
$sql .= "$key = '$val' $type";
}
}
$sql = trim($sql,"''|$type");
return $sql;
}
//添加数据方法
public function insert($arr)
{
$opType = ',';
$handleSql = $this->handleSql($arr,$opType);
$realSql = "insert into {$this->_table} set {$handleSql}";
$res = self::$pdo->exec($realSql);
return $res;
}
//修改数据方法
public function update($arrValue,$arrWhere)
{
$strValue = $this->handleSql($arrValue,',');
$strWhere = $this->handleSql($arrWhere,'and');
$sql = "update {$this->_table} set {$strValue} where {$strWhere}";
return self::$pdo->exec($sql);
}
//删除数据方法
public function delete($arrWhere)
{
$strWhere = $this->handleSql($arrWhere,'AND');
$sql = "delete from {$this->_table} where $strWhere";
return self::$pdo->exec($sql);
}
//查询全部数据 以数组形式返回
public function getAll()
{
$sql = "select * from {$this->_table}";
var_dump($sql);die;
}
//传入条件 查询一条数据 以数组返回
public function getOne($where)
{
$strWhere = $this->handleSql($where,'AND');
$sql = "select * from {$this->_table} where $strWhere";
return self::$pdo->query($sql)->fetch(PDO::FETCH_ASSOC);
}
//执行原生SQL
public function query($sql)
{
if (empty($sql)){
return true;
}else{
return self::$pdo->query($sql);
}
}
}