issue: database insert method to keep array values
authorMischa POSLAWSKY <perl@shiar.org>
Thu, 7 Nov 2019 03:43:53 +0000 (04:43 +0100)
committerMischa POSLAWSKY <perl@shiar.org>
Sat, 9 Nov 2019 06:08:13 +0000 (07:08 +0100)
Feature to apply literal SQL with optional arguments, stolen from other
projects modeled after DBIx::Simple.

database.inc.php

index 218335814bebf8e993aeb034449d7dc17efae940..464126b3fad1370fe17f6e32dd4863a92dd759a5 100644 (file)
@@ -22,13 +22,24 @@ class DB
                return $stmt;
        }
 
+       function _value($val, &$params)
+       {
+               $params[] = $val;
+               return '?';
+       }
+
        function insert($table, $row)
        {
+               $params = [];
+               $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(', ', array_fill(0, count($row), '?'))
+                       implode(', ', $cols)
                );
-               return $this->query($sql, array_values($row));
+               return $this->query($sql, $params);
        }
 }