nieuws/replies: database class with query method
authorMischa POSLAWSKY <perl@shiar.org>
Thu, 17 Oct 2019 03:52:48 +0000 (05:52 +0200)
committerMischa POSLAWSKY <perl@shiar.org>
Sun, 27 Oct 2019 00:36:38 +0000 (02:36 +0200)
Code cleanup preparing for more extensive database support
(where default php is somewhat lacking).

database.inc.php
widget/nieuws/replies.php

index 6e040d46d8cba08d3a9cef90d9cbba5637f0b2ac..aa864d03df32f5dadedba9441512331f5fe10d5c 100644 (file)
@@ -1,4 +1,21 @@
 <?php
 $dsn = require '.dbconfig.inc.php';
-$options = [ PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION ];
-$Db = new PDO($dsn, NULL, NULL, $options);
+$Db = new DB($dsn);
+
+class DB
+{
+       public $dbh;
+
+       function __construct($config, $options = [])
+       {
+               $options += [ PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION ];
+               $this->dbh = new PDO($config, NULL, NULL, $options);
+       }
+
+       function query($sql, $params = [])
+       {
+               $stmt = $this->dbh->prepare($sql);
+               $stmt->execute($params);
+               return $stmt;
+       }
+}
index 54e552a0ff7cb86f7ade5fee3be6d7fcbd9a8777..13533c99fe09a35049f23d918ced22ecd5e591cb 100644 (file)
@@ -8,8 +8,9 @@ if ($_POST) {
        try {
                $html = nl2br(htmlspecialchars($_POST['reply']));
                $html = "<p>$html</p>";
-               $query = $Db->prepare('INSERT INTO comments (page, message, author) VALUES (?, ?, ?)');
-               $query->execute([ $Page, $html, $User->login ]);
+               $query = $Db->query('INSERT INTO comments (page, message, author) VALUES (?, ?, ?)', [
+                       $Page, $html, $User->login
+               ]);
                if (!$query->rowCount()) {
                        throw new Exception('Fout bij opslaan');
                }
@@ -20,8 +21,7 @@ if ($_POST) {
        }
 }
 
-$query = $Db->prepare('SELECT * FROM comments WHERE page = ? ORDER BY created');
-$query->execute([$Page]);
+$query = $Db->query('SELECT * FROM comments WHERE page = ? ORDER BY created', [$Page]);
 
 print '<ul class="replies">';