-
Notifications
You must be signed in to change notification settings - Fork 0
/
db.php
58 lines (52 loc) · 1.2 KB
/
db.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
<?php namespace Blog\DB;
$config = array(
'username' => 'root',
'password' => 'root',
'database' => 'blog'
);
// Connecting to db
function connect($config)
{
try {
$conn = new \PDO('mysql:host=localhost;dbname=' .
$config['database'],
$config['username'],
$config['password']);
$conn->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
return $conn;
} catch(Exception $e) {
return false;
}
}
// Constructing queries
function query($query, $bindings, $conn)
{
$stmt = $conn->prepare($query);
$stmt->execute($bindings);
return ($stmt->rowCount() > 0) ? $stmt : false;
}
// Getting information from db
function get($tableName, $conn, $limit = 10)
{
try {
$result = $conn->query("SELECT * from $tableName ORDER BY id DESC LIMIT $limit");
return ( $result->rowCount() > 0 )
? $result
: false;
} catch(Exception $e) {
return false;
}
}
// Getting a single post
function get_by_id($id, $conn)
{
$query = query(
"SELECT * FROM posts WHERE id = :id LIMIT 1",
array('id' => $id),
$conn
);
// return $query;
if ( $query ) {
return $query->fetchAll();
}
}