Use one 'INSERT OR REPLACE' SQL query.
David Blume

David Blume commited on 2016-09-11 21:27:29
Showing 1 changed files, with 16 additions and 18 deletions.

... ...
@@ -13,8 +13,8 @@ try {
13 13
 if (isset($_GET['k'])) {
14 14
     // This is a request to get one specific value.
15 15
     $keys = array_map(array($db, 'quote'), explode(',', $_GET['k']));
16
-    $result = $db->query('select v from keys where k in ('.implode(',', $keys).') 
17
-                          order by updated desc limit 1;', PDO::FETCH_ASSOC);
16
+    $result = $db->query('SELECT v FROM keys WHERE k IN ('.implode(',', $keys).') 
17
+                          ORDER BY updated DESC LIMIT 1;', PDO::FETCH_ASSOC);
18 18
     foreach($result as $row) {
19 19
         echo $row['v'];
20 20
     }
... ...
@@ -25,37 +25,35 @@ if (isset($_GET['k'])) {
25 25
         exit(0);
26 26
     }
27 27
 
28
-    // We have an authorized request to add or update a key/value pair.
29
-    $stmt = $db->prepare('select k from keys where k=?');
28
+    // We have an authorized request to insert or replace a key/value pair.
29
+    $stmt = $db->prepare(
30
+        'INSERT OR REPLACE INTO keys
31
+         VALUES (:k, :v,
32
+                 COALESCE((SELECT created FROM keys WHERE k = :k), :rtime),
33
+                 :rtime, :raddr);');
34
+    $stmt->bindParam(':rtime', $_SERVER['REQUEST_TIME'], PDO::PARAM_INT);
35
+    $stmt->bindParam(':raddr', $_SERVER['REMOTE_ADDR'], PDO::PARAM_STR);
36
+
30 37
     foreach($_POST as $key => $value) {
31 38
         if ($key == 'auth') {
32 39
             continue;
33 40
         }
34
-        $stmt->bindParam(1, $key, PDO::PARAM_STR);
41
+        $stmt->bindParam(':k', $key, PDO::PARAM_STR);
42
+        $stmt->bindParam(':v', $value, PDO::PARAM_STR);
35 43
         $stmt->execute();
36
-        $row = $stmt->fetch(PDO::FETCH_ASSOC);
37
-        if(!$row) {
38
-            $db->exec('insert into keys (k, v, created, updated, origin) values ('.
39
-                       $db->quote($key).', '.$db->quote($value).', '.
40
-                       $_SERVER['REQUEST_TIME'].', '.$_SERVER['REQUEST_TIME'].', '.
41
-                       $db->quote($_SERVER['REMOTE_ADDR']).');');
42
-        } else {
43
-            $db->exec('update keys set v = '.$db->quote($value).', updated = '.$_SERVER['REQUEST_TIME'].
44
-                      ', origin = '.$db->quote($_SERVER['REMOTE_ADDR']).' where k = '.$db->quote($key).';');
45
-        }
46 44
         if ($db->errorCode() != '00000') {
47 45
             echo "Error:", $db->errorInfo()[2], "\n";
48 46
         } else {
49
-            echo 'OK';
47
+            echo "OK\n";
50 48
         }
51 49
     }
52 50
     exit(0);
53 51
 }
54 52
 $headers = array("key          ","value         ","created     ","updated     ","origin      ");
55 53
 echo implode("\t", $headers)."\n";
56
-$headers = array("-----------","------------","------------","------------","------------");
54
+$headers = array("-------------","--------------","------------","------------","------------");
57 55
 echo implode("\t", $headers)."\n";
58
-$result = $db->query('select * from keys', PDO::FETCH_ASSOC);
56
+$result = $db->query('SELECT * FROM keys', PDO::FETCH_ASSOC);
59 57
 foreach($result as $row) {
60 58
     // print_r( $row );
61 59
     $row['k'] = str_pad($row['k'], 12);
62 60