Last active
December 16, 2016 11:03
-
-
Save elmarputz/5c5921ffc57e85d8fffa75c392e9b8ea to your computer and use it in GitHub Desktop.
DataManager_PDO
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
/** | |
* place query | |
* | |
* note: using prepared statements | |
* see the filtering in bindValue() | |
* | |
* @return mixed | |
*/ | |
private static function query($connection, $query, $parameters = array()) { | |
$statement = $connection->prepare($query); | |
$i = 1; | |
foreach ($parameters as $param) { | |
if (is_int($param)) { | |
$statement->bindValue($i, $param, PDO::PARAM_INT); | |
} | |
if (is_string($param)) { | |
$statement->bindValue($i, $param, PDO::PARAM_STR); | |
} | |
$i++; | |
} | |
$statement->execute(); | |
return $statement; | |
} | |
/** | |
* get the key of the last inserted item | |
* | |
* @return integer | |
*/ | |
private static function lastInsertId($connection) { | |
return $connection->lastInsertId(); | |
} | |
/** | |
* retrieve an object from the database result set | |
* | |
* @param object $cursor result set | |
* @return object | |
*/ | |
private static function fetchObject($cursor) { | |
return $cursor->fetchObject(); | |
} | |
/** | |
* remove the result set | |
* | |
* @param object $cursor result set | |
* @return null | |
*/ | |
private static function close($cursor) { | |
$cursor->closeCursor(); | |
} | |
/** | |
* get the User item by id | |
* | |
* @param integer $userId uid of that user | |
* @return User | false | |
*/ | |
public static function getUserForId($userId) { | |
$user = null; | |
$con = self::getConnection(); | |
$res = self::query($con, " | |
SELECT id, userName, passwordHash | |
FROM users | |
WHERE id = ?; | |
", array($userId)); | |
if ($u = self::fetchObject($res)) { | |
$user = new User($u->id, $u->userName, $u->passwordHash); | |
} | |
self::close($res); | |
self::closeConnection($con); | |
return $user; | |
} | |
/** | |
* get the User item by name | |
* | |
* @param string $userName name of that user - must be exact match | |
* @return User | false | |
*/ | |
public static function getUserForUserName($userName) { | |
$user = null; | |
$con = self::getConnection(); | |
$res = self::query($con, " | |
SELECT id, userName, passwordHash | |
FROM users | |
WHERE userName = ?; | |
", array($userName)); | |
if ($u = self::fetchObject($res)) { | |
$user = new User($u->id, $u->userName, $u->passwordHash); | |
} | |
self::close($res); | |
self::closeConnection($con); | |
return $user; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment