Php Sq Lite

3,791 views

Published on

Published in: Technology, Education
0 Comments
1 Like
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total views
3,791
On SlideShare
0
From Embeds
0
Number of Embeds
7
Actions
Shares
0
Downloads
45
Comments
0
Likes
1
Embeds 0
No embeds

No notes for slide

Php Sq Lite

  1. 1. SQLite
  2. 2. What is SQLite? <ul><li>SQLite is a file-based database engine and uses file I/O functions to store and read databases from files on disk. </li></ul><ul><li>It is much smaller than MySQL where the command-line version of SQLite weighs in at under 200 KB. </li></ul><ul><li>SQLite supports databases up to 2 terabytes in size and is actually faster than MySQL in certain situations. </li></ul>
  3. 3. <ul><li>SQLite database files are easily portable, and SQLite databases created on Windows work fine on *NIX platforms and vice-versa. </li></ul><ul><li>One of SQLite's more interesting aspects is that it is completely typeless. </li></ul><ul><li>Fields in an SQLite database need not be associated with a specific type, and even if they are, you can still insert values of different types into them. </li></ul>
  4. 4. <ul><li>SQLite source code is completely public-domain. </li></ul><ul><li>In order to use SQLite and PHP together, your PHP build must include SQLite. </li></ul><ul><li>This is enabled by default in both the UNIX and Windows versions of PHP 5. </li></ul>
  5. 5. How to Use SQLite? <ul><li>As with MySQL, use regular SQL commands to interact with an SQLite database. </li></ul><ul><li>The exact SQL syntax used by SQLite is listed below: </li></ul><ul><ul><li>Alter Table </li></ul></ul><ul><ul><li>Analyze </li></ul></ul><ul><ul><li>Attach Database </li></ul></ul><ul><ul><li>Begin Transaction </li></ul></ul><ul><ul><li>Comment </li></ul></ul><ul><li>Commit Transaction </li></ul><ul><li>Create Index </li></ul><ul><li>Create Table </li></ul><ul><li>Create Trigger </li></ul><ul><li>Create View </li></ul>
  6. 6. Cont… <ul><ul><li>Drop Tigger </li></ul></ul><ul><ul><li>Drop View </li></ul></ul><ul><ul><li>End Transaction </li></ul></ul><ul><ul><li>Explain </li></ul></ul><ul><ul><li>Detach Database </li></ul></ul><ul><ul><li>Vacuum </li></ul></ul><ul><ul><li>Update </li></ul></ul><ul><ul><li>Select </li></ul></ul><ul><ul><li>Rollback Transaction </li></ul></ul><ul><ul><li>On Conflict clause </li></ul></ul><ul><li>Reindex </li></ul><ul><li>Pragma </li></ul><ul><li>Expression </li></ul><ul><li>Replace </li></ul><ul><li>Create Virtual Table </li></ul><ul><li>Delete </li></ul><ul><li>Drop Index </li></ul><ul><li>Drop Table </li></ul><ul><li>Insert </li></ul>
  7. 7. <ul><li>Example: </li></ul><ul><li>C:WINDOWSDesktopsqlite>sqlite library.db SQLite version 2.8.15 Enter &quot;.help&quot; for instructions sqlite> create table books (    ...> id integer primary key,    ...> title varchar(255) not null,    ...> author varchar(255) not null    ...>); sqlite> insert into books (title, author) values ('The Lord Of The Rings', 'J.R.R. Tolkien'); sqlite> insert into books (title, author) values ('The Murders In The Rue Morgue', 'Edgar Allen Poe'); sqlite> insert into books (title, author) values ('Three Men In A Boat', 'Jerome K. Jerome'); sqlite> insert into books (title, author) values ('A Study In Scarlet', 'Arthur Conan Doyle'); sqlite> insert into books (title, author) values ('Alice In Wonderland', 'Lewis Carroll'); sqlite> .exit </li></ul>
  8. 8. Anatomy Class <ul><li>Now, use PHP to communicate with SQLite, generate the same result set and format it as an HTML page. Here's the code: </li></ul><ul><li><html> <head></head> <body> <?php // set path of database file $db = $_SERVER [ 'DOCUMENT_ROOT' ]. &quot;/../library.db&quot; ; // open database file $handle = sqlite_open ( $db ) or die( &quot;Could not open database&quot; ); // generate query string $query = &quot;SELECT * FROM books&quot; ; </li></ul>cont…
  9. 9. <ul><li>// execute query $result = sqlite_query ( $handle , $query ) or die( &quot;Error in query: &quot; . sqlite_error_string ( sqlite_last_error ( $handle ))); // if rows exist if ( sqlite_num_rows ( $result ) > 0 ) {      // get each row as an array     // print values      echo &quot;<table cellpadding=10 border=1>&quot; ;     while( $row = sqlite_fetch_array ( $result )) {         echo &quot;<tr>&quot; ;         echo &quot;<td>&quot; . $row [ 0 ]. &quot;</td>&quot; ;         echo &quot;<td>&quot; . $row [ 1 ]. &quot;</td>&quot; ;         echo &quot;<td>&quot; . $row [ 2 ]. &quot;</td>&quot; ;         echo &quot;</tr>&quot; ;     }     echo &quot;</table>&quot; ; } // all done // close database file sqlite_close ( $handle ); ?> </body> </html> </li></ul>
  10. 10. <ul><li>In PHP 5 you can also use the SQLite API in an object-oriented way, wherein each of the functions above becomes a method of the SQLiteDatabase() object. </li></ul><ul><li><html> <head></head> <body> <?php // set path of database file $file = $_SERVER [ 'DOCUMENT_ROOT' ]. &quot;/../library.db&quot; ; // create database object $db = new SQLiteDatabase ( $file ) or die( &quot;Could not open database&quot; ); // generate query string $query = &quot;SELECT *  FROM books&quot; ; // execute query // return result object $result = $db -> query ( $query ) or die( &quot;Error in query&quot; ); </li></ul>cont…
  11. 11. <ul><li>// if rows exist if ( $result -> numRows () > 0 ) {      // get each row as an array     // print values      echo &quot;<table cellpadding=10 border=1>&quot; ;     while( $row = $result -> fetch ()) {         echo &quot;<tr>&quot; ;         echo &quot;<td>&quot; . $row [ 0 ]. &quot;</td>&quot; ;         echo &quot;<td>&quot; . $row [ 1 ]. &quot;</td>&quot; ;         echo &quot;<td>&quot; . $row [ 2 ]. &quot;</td>&quot; ;         echo &quot;</tr>&quot; ;     }     echo &quot;</table>&quot; ; } // all done // destroy database object unset( $db ); ?> </body> </html> </li></ul>
  12. 12. <ul><li>The new keyword is used to instantiate an object of the class SQLiteDatabase() by passing the object constructor the name of the database file. </li></ul><ul><li>If the database file does not already exist, a new database file is created. </li></ul><ul><li>The resulting object, stored in $db, then exposes methods and properties to perform queries. </li></ul><ul><li>Every query returns an instance of the class SQLiteResult() ,which in turn exposes methods for fetching and processing records. </li></ul>
  13. 13. Different Strokes <ul><li>As with the MySQL API, PHP's SQLite API offers you more than one way to skin a cat. </li></ul><ul><li>For example, you can retrieve each row as an object with the sqlite_fetch_object() method, and access field values by using the field names as object properties. Here's an example: </li></ul>
  14. 14. <ul><li><html> <head></head> <body> <?php // set path of database file $db = $_SERVER [ 'DOCUMENT_ROOT' ]. &quot;/../library.db&quot; ; // open database file $handle = sqlite_open ( $db ) or die( &quot;Could not open database&quot; ); // generate query string $query = &quot;SELECT * FROM books&quot; ; // execute query $result = sqlite_query ( $handle , $query ) or die( &quot;Error in query: &quot; . sqlite_error_string ( sqlite_last_error ( $handle ))); </li></ul>cont…
  15. 15. <ul><li>// if rows exist if ( sqlite_num_rows ( $result ) > 0 ) {      // get each row as an object     // print field values as object properties      echo &quot;<table cellpadding=10 border=1>&quot; ;     while( $obj = sqlite_fetch_object ( $result )) {         echo &quot;<tr>&quot; ;         echo &quot;<td>&quot; . $obj -> id . &quot;</td>&quot; ;         echo &quot;<td>&quot; . $obj -> title . &quot;</td>&quot; ;         echo &quot;<td>&quot; . $obj -> author . &quot;</td>&quot; ;         echo &quot;</tr>&quot; ;     }     echo &quot;</table>&quot; ; } // all done // close database file sqlite_close ( $handle ); ?> </body> </html> </li></ul>
  16. 16. <ul><li>Another option is to retrieve the complete result set in one fell swoop with the sqlite_fetch_all() function. </li></ul><ul><li>This function retrieves the complete set of records as an array of arrays; each element of the outer array represents a record, and is itself structured as an array whose elements represent fields in that record. </li></ul>
  17. 17. <ul><li>Example: </li></ul><ul><li><html> <head></head> <body> <?php // set path of database file $db = $_SERVER [ 'DOCUMENT_ROOT' ]. &quot;/../library.db&quot; ; // open database file $handle = sqlite_open ( $db ) or die( &quot;Could not open database&quot; ); // generate query string $query = &quot;SELECT * FROM books&quot; ; // execute query $result = sqlite_query ( $handle , $query ) or die( &quot;Error in query: &quot; . sqlite_error_string ( sqlite_last_error ( $handle ))); </li></ul>cont…
  18. 18. <ul><li>// get the complete result set as a series of nested arrays $data = sqlite_fetch_all ( $result ); // all done // close database file sqlite_close ( $handle ); // check the array to see if it contains at least one record if ( sizeof ( $data ) > 0 ) {     echo &quot;<table cellpadding=10 border=1>&quot; ;      // iterate over outer array (rows)     // print values for each element of inner array (columns)      foreach ( $data as $row ) {         echo &quot;<tr>&quot; ;         echo &quot;<td>&quot; . $row [ 0 ]. &quot;</td>&quot; ;         echo &quot;<td>&quot; . $row [ 1 ]. &quot;</td>&quot; ;         echo &quot;<td>&quot; . $row [ 2 ]. &quot;</td>&quot; ;         echo &quot;</tr>&quot; ;     }     echo &quot;</table>&quot; ; } ?> </body> </html> </li></ul>
  19. 19. <ul><li>In all the previous examples, the database remained open while the result set was processed, because records were retrieved one after another with the sqlite_fetch_array() or sqlite_fetch_object() functions. </li></ul><ul><li>The database also can be closed before the result set array is processed. </li></ul><ul><li>It because the entire result is retrieved at once and stored in the $data array. </li></ul>
  20. 20. <ul><li>If your result set contains only a single field, use the sqlite_fetch_single() function. </li></ul><ul><li>It retrieves the value of the first field of a row. </li></ul><ul><li>Example: </li></ul><ul><li>html> <head></head> <body> <?php // set path of database file $db = $_SERVER [ 'DOCUMENT_ROOT' ]. &quot;/../library.db&quot; ; // open database file $handle = sqlite_open ( $db ) or die( &quot;Could not open database&quot; ); </li></ul>cont…
  21. 21. <ul><li>// generate query string // this query returns only a single record with a single field $query = &quot;SELECT author FROM books WHERE title = 'A Study In Scarlet'&quot; ; // execute query $result = sqlite_query ( $handle , $query ) or die( &quot;Error in query: &quot; . sqlite_error_string ( sqlite_last_error ( $handle ))); // if a row exists if ( sqlite_num_rows ( $result ) > 0 ) {      // get the value of the first field of the first row      echo sqlite_fetch_single ( $result ); } // all done // close database file sqlite_close ( $handle ); ?> </body> </html> </li></ul>
  22. 22. <ul><li>The sqlite_fetch_single() function even can be used in combination with a while() loop to iterate over a result set containing many records but a single field. </li></ul><ul><li>Notice also my usage of the sqlite_has_more() function, to check if the next row exists or not. </li></ul>
  23. 23. <ul><li><html> <head></head> <body> <?php // set path of database file $db = $_SERVER [ 'DOCUMENT_ROOT' ]. &quot;/../library.db&quot; ; // open database file $handle = sqlite_open ( $db ) or die( &quot;Could not open database&quot; ); // generate query string $query = &quot;SELECT DISTINCT author FROM books&quot; ; // execute query $result = sqlite_query ( $handle , $query ) or die( &quot;Error in query: &quot; . sqlite_error_string ( sqlite_last_error ( $handle ))); // if rows exist if ( sqlite_num_rows ( $result ) > 0 ) {     echo &quot;<table cellpadding=10 border=1>&quot; ;      // check for more rows      while ( sqlite_has_more ( $result )) {          // get first field from each row         // print values          $row = sqlite_fetch_single ( $result );         echo &quot;<tr>&quot; ;         echo &quot;<td>&quot; . $row . &quot;</td>&quot; ;         echo &quot;</tr>&quot; ;     }     echo &quot;</table>&quot; ; } // all done // close database file sqlite_close ( $handle ); ?> </body> </html> </li></ul>
  24. 24. <ul><li>Sqlite_has_more() is one function that really doesn't translate to its object method name; in an OO script. </li></ul><ul><li>Need to call $result->valid();. The next script is the OO equivalent of the one above: </li></ul><ul><li><html> <head></head> <body> <?php // set path of database file $file = $_SERVER [ 'DOCUMENT_ROOT' ]. &quot;/../library.db&quot; ; // create database object $db = new SQLiteDatabase ( $file ) or die( &quot;Could not open database&quot; ); </li></ul><ul><li>// generate query string $query = &quot;SELECT DISTINCT author FROM books&quot; ; </li></ul>cont…
  25. 25. <ul><li>// execute query $result = $db -> query ( $query ) or die( &quot;Error in query&quot; ); // if rows exist if ( $result -> numRows () > 0 ) {     echo &quot;<table cellpadding=10 border=1>&quot; ;      // check for more rows      while ( $result -> valid ()) {          // get first field from each row         // print values          $row = $result -> fetchSingle ();         echo &quot;<tr>&quot; ;         echo &quot;<td>&quot; . $row . &quot;</td>&quot; ;             echo &quot;</tr>&quot; ;     }     echo &quot;</table>&quot; ; } // all done // destroy database object unset( $db ); ?> </body> </html> </li></ul>
  26. 26. Integer Primary Key <ul><li>There is one important exception to the typeless rule where a field is marked as INTEGER PRIMARY KEY. </li></ul><ul><li>In SQLite, fields marked as INTEGER PRIMARY KEY do two important things: </li></ul><ul><ul><li>provide a unique numeric identifier for each record in the table. </li></ul></ul><ul><ul><li>if there is NULL value, SQLite automatically inserts a value that is 1 greater than the largest value already present in that field. </li></ul></ul>
  27. 27. Cont… <ul><li>It perform the equivalent of AUTO_INCREMENT fields in MySQL. </li></ul><ul><li>Since the books table used in the previous example already contains such a field (the id field), it's clear that every INSERT into it with a NULL value for that field generates a new record number. </li></ul><ul><li>PHP also has a way to do this - just use the sqlite_last_insert_rowid() function, which returns the ID of the last inserted row (equivalent to the mysql_insert_id() function in PHP's MySQL API). </li></ul>
  28. 28. <ul><li><?php // check to see if the form was submitted with a new record if (isset( $_POST [ 'submit' ])) {      // make sure both title and author are present if (!empty( $_POST [ 'title' ]) && !empty( $_POST [ 'author' ])) {          // generate INSERT query          $insQuery = &quot;INSERT INTO books (title, author) VALUES (&quot;&quot; . sqlite_escape_string ( $_POST [ 'title' ]). &quot;&quot;, &quot;&quot; . sqlite_escape_string ( $_POST [ 'author' ]). &quot;&quot;)&quot; ;          // execute query          $insResult = sqlite_query ( $handle , $insQuery ) or die( &quot;Error in query: &quot; . sqlite_error_string ( sqlite_last_error ( $handle )));          // print success message          echo &quot;<i>Record successfully inserted with ID &quot; . sqlite_last_insert_rowid ( $handle ). &quot;!</i><p />&quot; ;     }     else {          // missing data         // display error message          echo &quot;<i>Incomplete form input. Record not inserted!</i><p />&quot; ;     } } ?> </li></ul>
  29. 29. Starting From Scratch <ul><li>We can use PHP itself to create a fresh SQLite database. </li></ul><ul><li>By issuing the necessary CREATE TABLE and INSERT commands through the sqlite_query() function. </li></ul>
  30. 30. <ul><li><?php // set path of database file $db = $_SERVER [ 'DOCUMENT_ROOT' ]. &quot;/../library2.db&quot; ; // open database file $handle = sqlite_open ( $db ) or die( &quot;Could not open database&quot; ); // create database sqlite_query ( $handle , &quot;CREATE TABLE books (id INTEGER PRIMARY KEY, title VARCHAR(255) NOT NULL, author VARCHAR(255) NOT NULL)&quot; ) or die( &quot;Error in query: &quot; . sqlite_error_string ( sqlite_last_error ( $handle ))); // insert records sqlite_query ( $handle , &quot;INSERT INTO books (title, author) VALUES ('The Lord Of The Rings', 'J.R.R. Tolkien')&quot; ) or die( &quot;Error in query: &quot; . sqlite_error_string ( sqlite_last_error ( $handle ))); sqlite_query ( $handle , &quot;INSERT INTO books (title, author) VALUES ('The Murders In The Rue Morgue', 'Edgar Allan Poe')&quot; ) or die( &quot;Error in query: &quot; . sqlite_error_string ( sqlite_last_error ( $handle ))); </li></ul>cont…
  31. 31. <ul><li>sqlite_query ( $handle , &quot;INSERT INTO books (title, author) VALUES ('Three Men In A Boat', 'Jerome K. Jerome')&quot; ) or die( &quot;Error in query: &quot; . sqlite_error_string ( sqlite_last_error ( $handle ))); sqlite_query ( $handle , &quot;INSERT INTO books (title, author) VALUES ('A Study In Scarlet', 'Arthur Conan Doyle')&quot; ) or die( &quot;Error in query: &quot; . sqlite_error_string ( sqlite_last_error ( $handle ))); sqlite_query ( $handle , &quot;INSERT INTO books (title, author) VALUES ('Alice In Wonderland', 'Lewis Carroll')&quot; ) or die( &quot;Error in query: &quot; . sqlite_error_string ( sqlite_last_error ( $handle ))); // print success message echo &quot;<i>Database successfully initialized!&quot; ; // all done // close database file sqlite_close ( $handle ); ?> </li></ul>
  32. 32. <ul><li><?php // set path of database file $file = $_SERVER [ 'DOCUMENT_ROOT' ]. &quot;/../library3.db&quot; ; // create database object $db = new SQLiteDatabase ( $file ) or die( &quot;Could not open database&quot; ); // create database $db -> query ( &quot;CREATE TABLE books (id INTEGER PRIMARY KEY, title VARCHAR(255) NOT NULL, author VARCHAR(255) NOT NULL)&quot; ) or die( &quot;Error in query&quot; ); // insert records $db -> query ( &quot;INSERT INTO books (title, author) VALUES ('The Lord Of The Rings', 'J.R.R. Tolkien')&quot; ) or die( &quot;Error in query&quot; ); $db -> query ( &quot;INSERT INTO books (title, author) VALUES ('The Murders In The Rue Morgue', 'Edgar Allan Poe')&quot; ) or die( &quot;Error in query&quot; ); </li></ul>Or, in PHP 5, you can use the object-oriented approach: cont…
  33. 33. <ul><li>$db -> query ( &quot;INSERT INTO books (title, author) VALUES ('Three Men In A Boat', 'Jerome K. Jerome')&quot; ) or die( &quot;Error in query&quot; ); $db -> query ( &quot;INSERT INTO books (title, author) VALUES ('A Study In Scarlet', 'Arthur Conan Doyle')&quot; ) or die( &quot;Error in query&quot; ); $db -> query ( &quot;INSERT INTO books (title, author) VALUES ('Alice In Wonderland', 'Lewis Carroll')&quot; ) or die( &quot;Error in query&quot; ); // print success message echo &quot;<i>Database successfully initialized!&quot; ; // all done // destroy database object unset( $db ); ?> </li></ul>
  34. 34. A Few Extra Tools <ul><li>The SQLite API also includes some ancillary functions, to provide you with information on the SQLite version and encoding, and on the error code and message generated by the last failed operation. </li></ul><ul><li>The following example demonstrates the sqlite_libversion() and sqlite_libencoding() functions, which return the version number and encoding of the linked SQLite library respectively: </li></ul><ul><li><?php // version echo &quot;SQLite version: &quot; . sqlite_libversion (). &quot;<br />&quot; ; // encoding echo &quot;SQLite encoding: &quot; . sqlite_libencoding (). &quot;<br />&quot; ; ?> </li></ul>
  35. 35. <ul><li>When things go wrong, reach for the sqlite_last_error() function, which returns the last error code returned by SQLite. </li></ul><ul><li>A numeric value – (couple it with the sqlite_error_string() function). </li></ul><ul><li>Consider the following example, which illustrates by attempting to run a query with a deliberate error in it: </li></ul><ul><li><?php // set path of database file $db = $_SERVER [ 'DOCUMENT_ROOT' ]. &quot;/../library.db&quot; ; // open database file $handle = sqlite_open ( $db ) or die( &quot;Could not open database&quot; ); </li></ul>cont…
  36. 36. <ul><li>// generate query string // query contains a deliberate error $query = &quot;DELETE books WHERE id = 1&quot; ; // execute query $result = sqlite_query ( $handle , $query ) or die( &quot;Error in query: &quot; . sqlite_error_string ( sqlite_last_error ( $handle ))); // all done // close database file sqlite_close ( $handle ); ?> </li></ul>
  37. 37. <ul><li>Note that although they might appear similar, the sqlite_last_error() and sqlite_error_string() functions don't work in exactly the same way as the mysql_errno() and mysql_error() functions. </li></ul><ul><li>The mysql_errno() and mysql_error() functions can be used independently of each other to retrieve the last error code and message respectively, but the sqlite_error_string() is dependent on the error code returned by sqlite_last_error(). </li></ul>

×