-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDBPDO.php
124 lines (116 loc) · 2.65 KB
/
DBPDO.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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
<?php
class DBPDO
{
public $pdo;
private $error;
function __construct()
{
$this->connect();
}
function prep_query($query)
{
return $this->pdo->prepare($query);
}
function connect()
{
if (!$this->pdo) {
$dsn = 'mysql:dbname=' . DATABASE_NAME . ';host=' . DATABASE_HOST . ';charset=utf8';
$user = DATABASE_USER;
$password = DATABASE_PASS;
try {
$this->pdo = new PDO($dsn, $user, $password, array(PDO::ATTR_PERSISTENT => true));
$this->pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
return true;
} catch (PDOException $e) {
$this->error = $e->getMessage();
return $this->error;
}
} else {
$this->pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING);
return true;
}
}
function table_exists($table_name)
{
try {
$stmt = $this->prep_query('SHOW TABLES LIKE ?');
$stmt->execute(array($table_name));
return $stmt->rowCount() > 0;
} catch (PDOException $e) {
return $e->getMessage();
}
}
function execute($query, $values = null)
{
try {
if ($values == null) {
$values = array();
} else if (!is_array($values)) {
$values = array($values);
}
$stmt = $this->prep_query($query);
$stmt->execute($values);
return $stmt;
} catch (PDOException $e) {
return $e->getMessage();
}
}
function count($query, $values = null)
{
try {
if ($values == null) {
$values = array();
} else if (!is_array($values)) {
$values = array($values);
}
$stmt = $this->prep_query($query);
$stmt->execute($values);
$number = $stmt->rowCount();
return $number;
} catch (PDOException $e) {
return $e->getMessage();
}
}
function fetch($query, $values = null)
{
try {
if ($values == null) {
$values = array();
} else if (!is_array($values)) {
$values = array($values);
}
$stmt = $this->execute($query, $values);
return $stmt->fetchObject();
} catch (PDOException $e) {
return $e->getMessage();
}
}
function fetchall($query, $values = null, $key = null)
{
try {
if ($values == null) {
$values = array();
} else if (!is_array($values)) {
$values = array($values);
}
$stmt = $this->execute($query, $values);
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
// Allows the user to retrieve results using a
// column from the results as a key for the array
if ($key != null && $results[0][$key]) {
$keyed_results = array();
foreach ($results as $result) {
$keyed_results[$result[$key]] = $result;
}
$results = $keyed_results;
}
return $results;
} catch (PDOException $e) {
return $e->getMessage();
}
}
function lastInsertId()
{
return $this->pdo->lastInsertId();
}
}