Skip to content

Commit 6201cd5

Browse files
committed
PDO Class Updates
execute, fetch and fetchAll can now accept a single string as the second parameter if only one is needed (seems pointless sending an array with one item) Also, the fetchAll function accepts a third parameter to allow you to return an array with a key being a column from the database as opposed to the standard indexed array.
1 parent a554208 commit 6201cd5

File tree

1 file changed

+30
-4
lines changed

1 file changed

+30
-4
lines changed

class.PDO.php

Lines changed: 30 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -49,20 +49,46 @@ function table_exists($table_name){
4949
}
5050

5151

52-
function execute($query, $values = array()){
52+
function execute($query, $values = null){
53+
if($values == null){
54+
$values = array();
55+
}else if(!is_array($values)){
56+
$values = array($values);
57+
}
5358
$stmt = $this->pdo->prepare($query);
5459
$stmt->execute($values);
5560
return $stmt;
5661
}
5762

58-
function fetch($query, $values = array()){
63+
function fetch($query, $values = null){
64+
if($values == null){
65+
$values = array();
66+
}else if(!is_array($values)){
67+
$values = array($values);
68+
}
5969
$stmt = $this->execute($query, $values);
6070
return $stmt->fetch(PDO::FETCH_ASSOC);
6171
}
6272

63-
function fetchAll($query, $values = array()){
73+
function fetchAll($query, $values = null, $key = null){
74+
if($values == null){
75+
$values = array();
76+
}else if(!is_array($values)){
77+
$values = array($values);
78+
}
6479
$stmt = $this->execute($query, $values);
65-
return $stmt->fetchAll(PDO::FETCH_ASSOC);
80+
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
81+
82+
// Allows the user to retrieve results using a
83+
// column from the results as a key for the array
84+
if($key != null && $results[0][$key]){
85+
$keyed_results = array();
86+
foreach($results as $result){
87+
$keyed_results[$result[$key]] = $result;
88+
}
89+
$results = $keyed_results;
90+
}
91+
return $results;
6692
}
6793

6894
function lastInsertId(){

0 commit comments

Comments
 (0)