Last active
December 17, 2015 01:59
-
-
Save J7mbo/5532808 to your computer and use it in GitHub Desktop.
Abstraction for MySQL PDO SELECT statement.
Running `findByValue(array('id', 'username'), 'users', array('website' => 'j7mbo.co.uk'), true);` is the same as:
`SELECT id, username FROM `users` WHERE website = 'j7mbo.co.uk' LIMIT 1;`
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public function findByValue($values, $location, $requirements, $single = false) | |
{ | |
$return = array(); | |
$conn = $this->conn; | |
$query = 'SELECT ' . implode(", ", $values) . ' FROM ' . $location . ' WHERE'; | |
$i = 0; | |
foreach ($requirements as $key => $value) | |
{ | |
$pre = ($i > 0) ? ' AND ' : ' '; | |
$query .= sprintf($pre . ' `%s` = :%s', $key, $key); | |
$i++; | |
} | |
$stmt = $conn->prepare($query); | |
foreach ($requirements as $key => $value) | |
{ | |
$stmt->bindValue(':' . $key, $value); | |
} | |
$stmt->execute(); | |
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) | |
{ | |
$return[] = $row; | |
} | |
return ($single) ? (isset($return[0]) ? $return[0] : null) : $return; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment