forked from a1phanumeric/PHP-MySQL-Class
-
Notifications
You must be signed in to change notification settings - Fork 0
/
DBPDO.php
107 lines (86 loc) · 2.22 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
<?php
namespace A1phanumeric;
use \PDO;
use \PDOException;
class DBPDO {
public $pdo;
private $error;
private $dbname;
private $dbhost;
private $dbuser;
private $dbpass;
function __construct($dbhost = '', $dbname = '', $dbuser = '', $dbpass= '') {
$this->dbhost = $dbhost;
$this->dbname = $dbname;
$this->dbuser = $dbuser;
$this->dbpass = $dbpass;
$this->connect();
}
function prep_query($query){
return $this->pdo->prepare($query);
}
function connect(){
if(!$this->pdo){
$dsn = 'mysql:dbname=' . $this->dbname . ';host=' . $this->dbhost . ';charset=utf8';
$user = $this->dbuser;
$password = $this->dbpass;
try {
$this->pdo = new PDO($dsn, $user, $password, array(PDO::ATTR_PERSISTENT => true));
return true;
} catch (PDOException $e) {
$this->error = $e->getMessage();
die($this->error);
return false;
}
}else{
$this->pdo->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING );
return true;
}
}
function table_exists($table_name){
$stmt = $this->prep_query('SHOW TABLES LIKE ?');
$stmt->execute(array($table_name));
return $stmt->rowCount() > 0;
}
function execute($query, $values = null){
if($values == null){
$values = array();
}else if(!is_array($values)){
$values = array($values);
}
$stmt = $this->prep_query($query);
$stmt->execute($values);
return $stmt;
}
function fetch($query, $values = null){
if($values == null){
$values = array();
}else if(!is_array($values)){
$values = array($values);
}
$stmt = $this->execute($query, $values);
return $stmt->fetch(PDO::FETCH_ASSOC);
}
function fetchAll($query, $values = null, $key = null){
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;
}
function lastInsertId(){
return $this->pdo->lastInsertId();
}
}