reply: setup database to fetch objects
[minimedit.git] / database.inc.php
1 <?php
2 $dsn = require '.dbconfig.inc.php';
3 $Db = new DB($dsn);
4
5 class DB
6 {
7         public $dbh;
8
9         function __construct($config, $options = [])
10         {
11                 $options += [
12                         PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
13                         PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_OBJ,
14                 ];
15                 $this->dbh = new PDO($config, NULL, NULL, $options);
16         }
17
18         function query($sql, $params = [])
19         {
20                 $stmt = $this->dbh->prepare($sql);
21                 $stmt->execute($params);
22                 return $stmt;
23         }
24
25         function insert($table, $row)
26         {
27                 $sql = sprintf('INSERT INTO %s (%s) VALUES (%s)',
28                         '"'.$table.'"',
29                         implode(', ', array_keys($row)),
30                         implode(', ', array_fill(0, count($row), '?'))
31                 );
32                 return $this->query($sql, array_values($row));
33         }
34 }