SqliteDatabase.class.php 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. <?php
  2. class SqliteDatabase {
  3. private static $instance;
  4. public static function getSingleton() {
  5. if(SqliteDatabase::$instance == null) {
  6. SqliteDatabase::$instance = new SqliteDatabase();
  7. }
  8. return SqliteDatabase::$instance;
  9. }
  10. private $sqlite;
  11. public function __construct() {
  12. $this->sqlite = new sqlite3(DATA_PATH . DBNAME);
  13. $this->sqlite->enableExceptions(true);
  14. $this->sqlite->busyTimeout(30000);
  15. $this->sqlite->exec('PRAGMA journal_mode = wal;');
  16. }
  17. public function __destruct() {
  18. $this->sqlite->close();
  19. }
  20. public function exec($sql) {
  21. $return = $this->sqlite->exec($sql);
  22. if(!$return) {
  23. throw new Exception($this->lastErrorMsg());
  24. }
  25. return $return;
  26. }
  27. public function query($sql) {
  28. return $this->sqlite->query($sql);
  29. }
  30. public function queryArray($sql) {
  31. $data = array();
  32. $return = $this->sqlite->query($sql);
  33. while($row = $return->fetchArray(SQLITE3_ASSOC)) {
  34. $data[] = $row;
  35. }
  36. return $data;
  37. }
  38. public function prepare($sql) {
  39. return $this->sqlite->prepare($sql);
  40. }
  41. public function preparedQueryArray($sql, array $keyValue) {
  42. $preparedQuery = $this->prepare($sql);
  43. foreach($keyValue as $key => $value) {
  44. $preparedQuery->bindValue(':' . $key, $value);
  45. }
  46. $result = $preparedQuery->execute();
  47. $resultData = array();
  48. while($row = $result->fetchArray(SQLITE3_ASSOC)) {
  49. $resultData[] = $row;
  50. }
  51. return $resultData;
  52. }
  53. public function lastErrorMsg() {
  54. return $this->sqlite->lastErrorMsg();
  55. }
  56. }