Skip to content

Instantly share code, notes, and snippets.

@lnaia
Last active August 29, 2015 14:00
Show Gist options
  • Save lnaia/11257808 to your computer and use it in GitHub Desktop.
Save lnaia/11257808 to your computer and use it in GitHub Desktop.
Articles model using a pdo wrapper
<?php
namespace Model;
class Articles
{
const DB_DSN = "mysql:host=localhost;dbname=DN_NAME_GOES_HERE";
const DB_USERNAME = 'DB_USER_GOES_HERE';
const DB_PASSWORD = 'DB_PASSWORD_GOES_HERE';
public static function find()
{
$query = "SELECT * FROM Articles";
$query_results = self::queryDB($query);
$query_results = $query_results['results'];
$articles = [];
foreach ($query_results as $article) {
$article['tags'] = self::getTags($article['id']);
$articles[] = $article;
}
return $articles;
}
public static function findbyId($id)
{
$query = "SELECT * FROM Articles WHERE id = :XXX_ARTICLE_ID";
$parameters = [
[
'key' => "XXX_ARTICLE_ID",
'value' => $id,
'kind' => \PDO::PARAM_INT
]
];
$article = self::queryDB($query, $parameters);
if (empty($article['status'])) {
return $article;
}
$article = $article['results'][0];
$article['tags'] = self::getTags($id);
return $article;
}
private static function queryDB($query, $parameters = array())
{
try {
$pdo = new \PDO(
self::DB_DSN,
self::DB_USERNAME,
self::DB_PASSWORD
);
$preparedStatement = $pdo->prepare($query);
foreach ($parameters as $item) {
$preparedStatement->bindParam(
$item['key'],
$item['value'],
$item['kind']
);
}
return [
'status' => $preparedStatement->execute(),
'results' => $preparedStatement->fetchAll(\PDO::FETCH_ASSOC),
];
} catch (\Exception $e) {
error_log($e->getMessage());
exit(1);
}
}
/**
* @param $id
* @return array
*/
public static function getTags($id)
{
$query = "SELECT title FROM articles_tags, Tags
WHERE articles_id = :XXX_ARTICLE_ID AND Tags.id = articles_tags.tags_id";
$parameters = [
[
'key' => "XXX_ARTICLE_ID",
'value' => $id,
'kind' => \PDO::PARAM_INT
]
];
$query_result = self::queryDB($query, $parameters);
$tags = [];
foreach ($query_result['results'] as $tag) {
$tags[] = $tag['title'];
}
return $tags;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment