Advertisement
Guest User

SQLite3 Class for PHP

a guest
Jun 2nd, 2011
397
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 2.17 KB | None | 0 0
  1. <?php
  2.  
  3. /*
  4. * SQLite3 Class
  5. * based on the code of miquelcamps
  6. * @see http://7devs.com/code/view.php?id=67
  7. */
  8.  
  9. class DB{
  10.   private $sqlite;
  11.   private $mode;
  12.  
  13.   function __construct( $filename, $mode = SQLITE3_ASSOC ){
  14.     $this->mode = $mode;
  15.     $this->sqlite = new SQLite3($filename);
  16.   }
  17.  
  18.   function __destruct(){
  19.     @$this->sqlite->close();
  20.   }
  21.  
  22.   function clean( $str ){
  23.     return $this->sqlite->escapeString( $str );
  24.   }
  25.  
  26.   function query( $query ){
  27.     $res = $this->sqlite->query( $query );
  28.     if ( !$res ){
  29.       throw new Exception( $this->sqlite->lastErrorMsg() );
  30.     }
  31.  
  32.     return $res;
  33.   }
  34.  
  35.   function queryRow( $query ){
  36.     $res = $this->query( $query );
  37.     $row = $res->fetchArray( $this->mode );
  38.     return $row;
  39.   }
  40.  
  41.   function queryOne( $query ){
  42.     $res = $this->sqlite->querySingle( $query );
  43.     return $res;
  44.   }
  45.  
  46.   function queryAll( $query ){
  47.     $rows = array();
  48.     if( $res = $this->query( $query ) ){
  49.       while($row = $res->fetchArray($this->mode)){
  50.         $rows[] = $row;
  51.       }
  52.     }
  53.     return $rows;
  54.   }
  55.  
  56.   function getLastID(){
  57.     return $this->sqlite->lastInsertRowID();
  58.   }
  59. }
  60.  
  61. // initialize
  62. $db = new DB( 'database.sqlite' );
  63.  
  64. // create the database structure
  65. $query = 'CREATE TABLE IF NOT EXISTS "foobar" (
  66.            "id" INTEGER PRIMARY KEY AUTOINCREMENT,
  67.            "name" TEXT
  68.          );';
  69. $db->query( $query );
  70.  
  71. // insert some data to the database
  72. $query = array(
  73.   "INSERT INTO foobar VALUES(1,'LOLOLOL');",
  74.   "INSERT INTO foobar VALUES(2,'Lorem Ipsum....');"
  75.   );
  76.  
  77. foreach($query as $key):
  78.   $db->query( $key );
  79. endforeach;
  80.  
  81. // query example, multiple rows
  82. $users = $db->queryAll( "SELECT * FROM foobar" );
  83.  
  84. // query example, one row
  85. $search = 'Lorem Ipsum....';
  86. $user_info = $db->queryRow( sprintf( "SELECT * FROM foobar WHERE name = '%s'", $db->clean( $search ) ) );
  87.  
  88. // query example, one result
  89. $total_users = $db->queryOne( "SELECT COUNT(*) FROM foobar" );
  90.  
  91. // insert query
  92. $insert = array(
  93.   'id' => 3,
  94.   'text' => 'Testing'
  95. );
  96. $db->query( sprintf( "INSERT INTO foobar VALUES ( %s, '%s' )", $db->clean ( $insert['id'] ), $db->clean( $insert['text'] ) ) );
  97.  
  98. ?>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement