/
sql.php
98 lines (86 loc) · 2.58 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
95
96
97
98
<?php
class sql
{
function __construct($driver, $server, $username, $password, $database, $charset)
{
$this->pdo = new PDO("$driver:host=$server;dbname=$database;charset=$charset", $username, $password, array
(
PDO::ATTR_PERSISTENT => false
));
}
function begin()
{
$this->pdo->setAttribute(PDO::ATTR_AUTOCOMMIT, false) or $this->push('SQL autocommit disabling failed: ' . $this->error());
if($this->ready())
{
$this->pdo->beginTransaction() or $this->push('SQL begin transaction failed: ' . $this->error());
if(!$this->ready())
{
$this->pdo->setAttribute(PDO::ATTR_AUTOCOMMIT, true) or $this->push('SQL autocommit enabling failed: ' . $this->error());
}
}
$this->flush();
++$this->depth;
}
function commit()
{
$this->pdo->commit() or $this->push('SQL transaction commit failed: ' . $this->error());
$this->pdo->setAttribute(PDO::ATTR_AUTOCOMMIT, true) or $this->push('SQL autocommit enabling failed: ' . $this->error());
$this->flush();
--$this->depth;
}
function rollback()
{
$this->pdo->rollBack() or $this->push('SQL transaction rollback failed: ' . $this->error());
$this->pdo->setAttribute(PDO::ATTR_AUTOCOMMIT, true) or $this->push('SQL autocommit enabling failed: ' . $this->error());
$this->flush();
--$this->depth;
}
function query($query)
{
if($result = $this->pdo->query($query))
{
return $result->fetchAll(PDO::FETCH_ASSOC);
}
else
{
$error = 'SQL query failed: ' . $this->error();
if($this->depth)
{
$this->rollback();
}
$this->push($error);
$this->flush();
}
}
function quote($value)
{
return $this->pdo->quote($value);
}
private function push($error)
{
$this->stack[] = $error;
}
private function ready()
{
return empty($this->stack);
}
private function flush()
{
if(!$this->ready())
{
$message = implode(', ', $this->stack);
$this->stack = array();
runtime_error($message);
}
}
private function error()
{
$info = $this->pdo->errorInfo();
return $info[2];
}
private $pdo;
private $depth = 0;
private $stack = array();
}
?>