Guest User

Untitled

a guest
Jan 31st, 2020
16
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. <?php
  2.  
  3. $dbfilename = 'demo.db';
  4.  
  5. if (is_file($dbfilename)) {
  6.     unlink($dbfilename);
  7. }
  8.  
  9. $sql = 'CREATE TABLE demo (id int, name string)';
  10. $result = demoQuery($dbfilename, $sql);
  11. var_dump($result);
  12.  
  13. $sql = 'SELECT * FROM demo WHERE id=0';
  14. $rows = demoQuery($dbfilename, $sql);
  15. var_dump($rows);
  16.  
  17. $sql = 'INSERT INTO demo VALUES (0, "A")';
  18. $result = demoQuery($dbfilename, $sql);
  19. var_dump($result);
  20.  
  21. $sql = 'SELECT * FROM demo WHERE id=0';
  22. $rows = demoQuery($dbfilename, $sql);
  23. var_dump($rows);
  24.  
  25. function demoQuery(string $dbfilename, string $sql) : array {
  26.     $fetchable = (0===stripos(trim($sql), 'select'));
  27.  
  28.     $db = new SQLite3($dbfilename);
  29.     if ($db === false) {
  30.         throw new Exception("demoQuery: open error " . $dbfilename);
  31.     }
  32.  
  33.     //$result = $db->query($sql);
  34.     $stmt = $db->prepare($sql);
  35.     if ($stmt === false) {
  36.         throw new Exception("demoQuery: prepare error " . $sql);
  37.     }
  38.  
  39.     // TODO //$stmt->bindvalue();
  40.     $result = $stmt->execute();
  41.     if ($result === false) {
  42.         throw new Exception("demoQuery: execute query error " . $sql);
  43.     }
  44.  
  45.     $rows = [];
  46.     if (true) { // Expected to work before reading internals of PHP+SQLite3
  47.     //if ($fetchable) { // May work
  48.     //if ($result->columnName(0) !== false) { // Works
  49.     //if ($result->columnType(0)!=SQLITE3_NULL) { // Didnt work
  50.     //if ($result->fetchArray()) { // Dangerous
  51.     //if ($result->finalize()) { // Cant do that
  52.     //if ($result->numColumns()!==0) { // Works
  53.     //if ($result->reset()) { // Didnt work
  54.     //if ($result->columnName(0) !== false || $result->numColumns()!==0) { // My best
  55.         while ($row = $result->fetchArray()) {
  56.             $rows[] = $row;
  57.         }
  58.     }
  59.     $db->close();
  60.     return $rows;
  61. }
RAW Paste Data