X-Git-Url: http://git.shiar.net/minimedit.git/blobdiff_plain/a89937ec79577fd78af6fe40450ca53dd2d3604f..4acdd7f1c3b2b78933d7953e8777df73af3189aa:/database.inc.php diff --git a/database.inc.php b/database.inc.php index 2183358..9b65ce6 100644 --- a/database.inc.php +++ b/database.inc.php @@ -22,13 +22,51 @@ class DB return $stmt; } - function insert($table, $row) + function _value($val, &$params) { - $sql = sprintf('INSERT INTO %s (%s) VALUES (%s)', - '"'.$table.'"', - implode(', ', array_keys($row)), - implode(', ', array_fill(0, count($row), '?')) - ); - return $this->query($sql, array_values($row)); + if (is_array($val)) { + $sql = array_shift($val); + $params = array_merge($params, $val); + return $sql; + } + elseif (is_bool($val)) { + return $val ? 'TRUE' : 'FALSE'; + } + + $params[] = $val; + return '?'; + } + + function set($table, $row, $filter = NULL) + { + $params = []; + if (is_null($filter)) { + $cols = []; + foreach ($row as $col => $val) { + $cols[] = $this->_value($val, $params); + } + $sql = sprintf('INSERT INTO %s (%s) VALUES (%s) RETURNING *', + '"'.$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; + } + } + return $this->query($sql, $params); } }