Skip to content

Instantly share code, notes, and snippets.

@J7mbo
Last active December 17, 2015 01:59
Show Gist options
  • Save J7mbo/5532808 to your computer and use it in GitHub Desktop.
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;`
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