From: Mischa POSLAWSKY Date: Thu, 7 Nov 2019 03:59:13 +0000 (+0100) Subject: reply: set method to abstract update queries X-Git-Tag: v4.2~28 X-Git-Url: http://git.shiar.net/minimedit.git/commitdiff_plain/084f4a795fb5874eecd7b17b3999f716432ad41c?hp=f988982ad609256e3bbbb8a41ca7c7b0b3b4fb74 reply: set method to abstract update queries Extend insert, renamed to generic "set", to allow updates using the same syntax with an additional select parameter. --- diff --git a/database.inc.php b/database.inc.php index 464126b..aaf2023 100644 --- a/database.inc.php +++ b/database.inc.php @@ -24,22 +24,46 @@ class DB function _value($val, &$params) { + if (is_array($val)) { + $sql = array_shift($val); + $params = array_merge($params, $val); + return $sql; + } + $params[] = $val; return '?'; } - function insert($table, $row) + function set($table, $row, $filter = NULL) { $params = []; - $cols = []; - foreach ($row as $col => $val) { - $cols[] = $this->_value($val, $params); + if (is_null($filter)) { + $cols = []; + foreach ($row as $col => $val) { + $cols[] = $this->_value($val, $params); + } + $sql = sprintf('INSERT INTO %s (%s) VALUES (%s)', + '"'.$table.'"', + implode(', ', array_keys($row)), + implode(', ', $cols) + ); + } + else { + $sql = 'UPDATE "'.$table.'"'; + $cols = []; + foreach ($row as $col => $val) { + $cols[] = $col . ' = ' . $this->_value($val, $params); + } + + $sql .= ' SET ' . implode(', ', $cols); + if (is_array($filter)) { + $sql .= ' WHERE ' . array_shift($filter); + $params = array_merge($params, $filter); + } + else { + $sql .= ' ' . $filter; + } } - $sql = sprintf('INSERT INTO %s (%s) VALUES (%s)', - '"'.$table.'"', - implode(', ', array_keys($row)), - implode(', ', $cols) - ); return $this->query($sql, $params); } } diff --git a/issue/index.php b/issue/index.php index abd9611..10efc5e 100644 --- a/issue/index.php +++ b/issue/index.php @@ -33,7 +33,7 @@ if ($id) { if ($_POST) { $html = nl2br(htmlspecialchars($_POST['body'])); $html = empty($html) ? NULL : "

$html

"; - $query = $Db->insert('issues', [ + $query = $Db->set('issues', [ 'page' => $Page, 'subject' => $_POST['subject'], 'body' => $html, diff --git a/widget/reply.php b/widget/reply.php index abb364c..4d504bb 100644 --- a/widget/reply.php +++ b/widget/reply.php @@ -8,7 +8,7 @@ if ($_POST) { try { $html = nl2br(htmlspecialchars($_POST['reply'])); $html = "

$html

"; - $query = $Db->insert('comments', [ + $query = $Db->set('comments', [ 'page' => $Page, 'message' => $html, 'author' => $User->login, @@ -17,10 +17,8 @@ if ($_POST) { throw new Exception('Fout bij opslaan'); } if (@list ($cat, $issue) = explode('/', $Page) and ctype_digit($issue)) { - $Db->query( - 'UPDATE issues SET updated = now() WHERE page = ? AND id = ?', - [$cat, $issue] - ); + $row = ['updated' => ['now()']]; + $Db->set('issues', $row, ['page = ? AND id = ?', $cat, $issue]); } $_POST['reply'] = NULL; }