mysqlHelper.php
2.36 KB
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
<?php
/**
* 数据库帮助类
*/
class mysqlHelper
{
protected $config = [];
protected $connection;
public function __construct($config = '')
{
$cfg = include('config.php');
$this->config = empty($config) ? $config = [
'driver' => $cfg['driver'],
'host' => $cfg['host'],
'port' => $cfg['port'],
'dbname' => $cfg['dbname'],
'user' => $cfg['user'],
'pass' => $cfg['pass'],
'options' => [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_CASE => PDO::CASE_NATURAL
]
] : $config;
$this->connection = $this->createConnection();
}
private function createConnection()
{
$config = $this->config;
try {
$dsn = "{$config['driver']}:host={$config['host']};port={$config['port']};dbname={$config['dbname']}";
$connection = new PDO($dsn, $config['user'], $config['pass'], $config['options']);
$connection->exec('set names utf8');
return $connection;
} catch (\Exception $e) {
die($e->getMessage());
}
}
public function insert($table, $data = [])
{
$placeholder = rtrim(implode(", ", array_fill(0, count($data), '?')), ',');
$format = "INSERT INTO `{$table}` (%s) VALUES (%s)";
$query = vsprintf($format, [implode(', ', array_keys($data)), $placeholder]);
$statement = $this->connection->prepare($query);
$statement->execute(array_values($data));
}
public function update($query, $data = [])
{
$statement = $this->connection->prepare($query);
// for ($i = 1; count($params) >= $i; $i++) {
// $statement->bindValue($i, $params[i]);
// }
$statement->execute($data);
return $statement->rowCount();
}
public function fetch($query, $data = [])
{
$statement = $this->connection->prepare($query);
$statement->execute($data);
return $statement->fetch(PDO::FETCH_ASSOC);
}
public function fetchAll($query, $data = [])
{
$statement = $this->connection->prepare($query);
$statement->execute($data);
return $statement->fetchAll(PDO::FETCH_ASSOC);
}
public function getLastInsertId()
{
return $this->connection->lastInsertId();
}
}