37
SQLite

Php Sq Lite

Embed Size (px)

Citation preview

Page 1: Php Sq Lite

SQLite

Page 2: Php Sq Lite

What is SQLite?

• SQLite is a file-based database engine and uses file I/O functions to store and read databases from files on disk.

• It is much smaller than MySQL where the command-line version of SQLite weighs in at under 200 KB.

• SQLite supports databases up to 2 terabytes in size and is actually faster than MySQL in certain situations.

Page 3: Php Sq Lite

• SQLite database files are easily portable, and SQLite databases created on Windows work fine on *NIX platforms and vice-versa.

• One of SQLite's more interesting aspects is that it is completely typeless.

• 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.

Page 4: Php Sq Lite

• SQLite source code is completely public-domain.

• In order to use SQLite and PHP together, your PHP build must include SQLite.

• This is enabled by default in both the UNIX and Windows versions of PHP 5.

Page 5: Php Sq Lite

How to Use SQLite?

• As with MySQL, use regular SQL commands to interact with an SQLite database.

• The exact SQL syntax used by SQLite is listed below:– Alter Table – Analyze– Attach Database– Begin Transaction– Comment

– Commit Transaction– Create Index– Create Table– Create Trigger– Create View

Page 6: Php Sq Lite

Cont…

– Drop Tigger– Drop View– End Transaction– Explain– Detach Database– Vacuum– Update– Select– Rollback Transaction– On Conflict clause

– Reindex– Pragma– Expression– Replace– Create Virtual Table– Delete– Drop Index– Drop Table– Insert

Page 7: Php Sq Lite

• Example:

C:\WINDOWS\Desktop\sqlite>sqlite library.db SQLite version 2.8.15 Enter ".help" 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

Page 8: Php Sq Lite

Anatomy Class• Now, use PHP to communicate with SQLite, generate the same

result set and format it as an HTML page. Here's the code:

<html> <head></head> <body> <?php // set path of database file $db = $_SERVER['DOCUMENT_ROOT']."/../library.db";

// open database file $handle = sqlite_open($db) or die("Could not open database");

// generate query string $query = "SELECT * FROM books";

cont…

Page 9: Php Sq Lite

// execute query $result = sqlite_query($handle, $query) or die("Error in query: ".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 "<table cellpadding=10 border=1>";     while($row = sqlite_fetch_array($result)) {         echo "<tr>";         echo "<td>".$row[0]."</td>";         echo "<td>".$row[1]."</td>";         echo "<td>".$row[2]."</td>";         echo "</tr>";     }     echo "</table>"; }

// all done // close database file sqlite_close($handle); ?> </body> </html>

Page 10: Php Sq Lite

• 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.

<html> <head></head> <body> <?php // set path of database file $file = $_SERVER['DOCUMENT_ROOT']."/../library.db";

// create database object $db = new SQLiteDatabase($file) or die("Could not open database");

// generate query string $query = "SELECT *  FROM books";

// execute query // return result object $result = $db->query($query) or die("Error in query");

cont…

Page 11: Php Sq Lite

// if rows exist if ($result->numRows() > 0) {     // get each row as an array     // print values     echo "<table cellpadding=10 border=1>";     while($row = $result->fetch()) {         echo "<tr>";         echo "<td>".$row[0]."</td>";         echo "<td>".$row[1]."</td>";         echo "<td>".$row[2]."</td>";         echo "</tr>";     }     echo "</table>"; }

// all done // destroy database object unset($db); ?> </body> </html>

Page 12: Php Sq Lite

• The new keyword is used to instantiate an object of the class SQLiteDatabase() by passing the object constructor the name of the database file.

• If the database file does not already exist, a new database file is created.

• The resulting object, stored in $db, then exposes methods and properties to perform queries.

• Every query returns an instance of the class SQLiteResult() ,which in turn exposes methods for fetching and processing records.

Page 13: Php Sq Lite

Different Strokes

• As with the MySQL API, PHP's SQLite API offers you more than one way to skin a cat.

• 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:

Page 14: Php Sq Lite

<html> <head></head> <body> <?php // set path of database file $db = $_SERVER['DOCUMENT_ROOT']."/../library.db";

// open database file $handle = sqlite_open($db) or die("Could not open database");

// generate query string $query = "SELECT * FROM books";

// execute query $result = sqlite_query($handle, $query) or die("Error in query: ".sqlite_error_string(sqlite_last_error($handle)));

cont…

Page 15: Php Sq Lite

// if rows exist if (sqlite_num_rows($result) > 0) {     // get each row as an object     // print field values as object properties     echo "<table cellpadding=10 border=1>";     while($obj = sqlite_fetch_object($result)) {         echo "<tr>";         echo "<td>".$obj->id."</td>";         echo "<td>".$obj->title."</td>";         echo "<td>".$obj->author."</td>";         echo "</tr>";     }     echo "</table>"; }

// all done // close database file sqlite_close($handle); ?> </body> </html>

Page 16: Php Sq Lite

• Another option is to retrieve the complete result set in one fell swoop with the sqlite_fetch_all() function.

• 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.

Page 17: Php Sq Lite

• Example:

<html> <head></head> <body> <?php // set path of database file $db = $_SERVER['DOCUMENT_ROOT']."/../library.db";

// open database file $handle = sqlite_open($db) or die("Could not open database");

// generate query string $query = "SELECT * FROM books";

// execute query $result = sqlite_query($handle, $query) or die("Error in query: ".sqlite_error_string(sqlite_last_error($handle)));

cont…

Page 18: Php Sq Lite

// 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 "<table cellpadding=10 border=1>";     // iterate over outer array (rows)     // print values for each element of inner array (columns)     foreach ($data as $row) {         echo "<tr>";         echo "<td>".$row[0]."</td>";         echo "<td>".$row[1]."</td>";         echo "<td>".$row[2]."</td>";         echo "</tr>";     }     echo "</table>"; } ?> </body> </html>

Page 19: Php Sq Lite

• 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.

• The database also can be closed before the result set array is processed.

• It because the entire result is retrieved at once and stored in the $data array.

Page 20: Php Sq Lite

• If your result set contains only a single field, use the sqlite_fetch_single() function.

• It retrieves the value of the first field of a row.

• Example:

html> <head></head> <body> <?php // set path of database file $db = $_SERVER['DOCUMENT_ROOT']."/../library.db";

// open database file $handle = sqlite_open($db) or die("Could not open database");

cont…

Page 21: Php Sq Lite

// generate query string // this query returns only a single record with a single field $query = "SELECT author FROM books WHERE title = 'A Study In Scarlet'";

// execute query $result = sqlite_query($handle, $query) or die("Error in query: ".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>

Page 22: Php Sq Lite

• 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.

• Notice also my usage of the sqlite_has_more() function, to check if the next row exists or not.

Page 23: Php Sq Lite

<html> <head></head> <body> <?php // set path of database file $db = $_SERVER['DOCUMENT_ROOT']."/../library.db";

// open database file $handle = sqlite_open($db) or die("Could not open database");

// generate query string $query = "SELECT DISTINCT author FROM books";

// execute query $result = sqlite_query($handle, $query) or die("Error in query: ".sqlite_error_string(sqlite_last_error($handle)));

// if rows exist if (sqlite_num_rows($result) > 0) {     echo "<table cellpadding=10 border=1>";     // check for more rows     while (sqlite_has_more($result)) {         // get first field from each row         // print values         $row = sqlite_fetch_single($result);         echo "<tr>";         echo "<td>".$row."</td>";         echo "</tr>";     }     echo "</table>"; }

// all done // close database file sqlite_close($handle); ?> </body> </html>

Page 24: Php Sq Lite

• Sqlite_has_more() is one function that really doesn't translate to its object method name; in an OO script.

• Need to call $result->valid();. The next script is the OO equivalent of the one above:

<html> <head></head> <body> <?php // set path of database file $file = $_SERVER['DOCUMENT_ROOT']."/../library.db";

// create database object $db = new SQLiteDatabase($file) or die("Could not open database");

// generate query string $query = "SELECT DISTINCT author FROM books";

cont…

Page 25: Php Sq Lite

// execute query $result = $db->query($query) or die("Error in query");

// if rows exist if ($result->numRows() > 0) {     echo "<table cellpadding=10 border=1>";     // check for more rows     while ($result->valid()) {         // get first field from each row         // print values         $row = $result->fetchSingle();         echo "<tr>";         echo "<td>".$row."</td>";             echo "</tr>";     }     echo "</table>"; }

// all done // destroy database object unset($db); ?> </body> </html>

Page 26: Php Sq Lite

Integer Primary Key

• There is one important exception to the typeless rule where a field is marked as INTEGER PRIMARY KEY.

• In SQLite, fields marked as INTEGER PRIMARY KEY do two important things:– provide a unique numeric identifier for each

record in the table.– if there is NULL value, SQLite automatically

inserts a value that is 1 greater than the largest value already present in that field.

Page 27: Php Sq Lite

Cont…

• It perform the equivalent of AUTO_INCREMENT fields in MySQL.

• 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.

• 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).

Page 28: Php Sq Lite

<?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 = "INSERT INTO books (title, author) VALUES (\"".sqlite_escape_string($_POST['title'])."\", \"".sqlite_escape_string($_POST['author'])."\")";         // execute query         $insResult = sqlite_query($handle, $insQuery) or die("Error in query: ".sqlite_error_string(sqlite_last_error($handle)));         // print success message         echo "<i>Record successfully inserted with ID ".sqlite_last_insert_rowid($handle)."!</i><p />";     }     else {         // missing data         // display error message         echo "<i>Incomplete form input. Record not inserted!</i><p />";     } }

?>

Page 29: Php Sq Lite

Starting From Scratch

• We can use PHP itself to create a fresh SQLite database.

• By issuing the necessary CREATE TABLE and INSERT commands through the sqlite_query() function.

Page 30: Php Sq Lite

<?php

// set path of database file $db = $_SERVER['DOCUMENT_ROOT']."/../library2.db";

// open database file $handle = sqlite_open($db) or die("Could not open database");

// create database sqlite_query($handle, "CREATE TABLE books (id INTEGER PRIMARY KEY, title VARCHAR(255) NOT NULL, author VARCHAR(255) NOT NULL)") or die("Error in query: ".sqlite_error_string(sqlite_last_error($handle)));

// insert records sqlite_query($handle, "INSERT INTO books (title, author) VALUES ('The Lord Of The Rings', 'J.R.R. Tolkien')") or die("Error in query: ".sqlite_error_string(sqlite_last_error($handle)));

sqlite_query($handle, "INSERT INTO books (title, author) VALUES ('The Murders In The Rue Morgue', 'Edgar Allan Poe')") or die("Error in query: ".sqlite_error_string(sqlite_last_error($handle))); cont…

Page 31: Php Sq Lite

sqlite_query($handle, "INSERT INTO books (title, author) VALUES ('Three Men In A Boat', 'Jerome K. Jerome')") or die("Error in query: ".sqlite_error_string(sqlite_last_error($handle)));

sqlite_query($handle, "INSERT INTO books (title, author) VALUES ('A Study In Scarlet', 'Arthur Conan Doyle')") or die("Error in query: ".sqlite_error_string(sqlite_last_error($handle)));

sqlite_query($handle, "INSERT INTO books (title, author) VALUES ('Alice In Wonderland', 'Lewis Carroll')") or die("Error in query: ".sqlite_error_string(sqlite_last_error($handle)));

// print success message echo "<i>Database successfully initialized!";

// all done // close database file sqlite_close($handle);

?>

Page 32: Php Sq Lite

<?php

// set path of database file $file = $_SERVER['DOCUMENT_ROOT']."/../library3.db";

// create database object $db = new SQLiteDatabase($file) or die("Could not open database");

// create database $db->query("CREATE TABLE books (id INTEGER PRIMARY KEY, title VARCHAR(255) NOT NULL, author VARCHAR(255) NOT NULL)") or die("Error in query");

// insert records $db->query("INSERT INTO books (title, author) VALUES ('The Lord Of The Rings', 'J.R.R. Tolkien')") or die("Error in query");

$db->query("INSERT INTO books (title, author) VALUES ('The Murders In The Rue Morgue', 'Edgar Allan Poe')") or die("Error in query");

Or, in PHP 5, you can use the object-oriented approach:

cont…

Page 33: Php Sq Lite

$db->query("INSERT INTO books (title, author) VALUES ('Three Men In A Boat', 'Jerome K. Jerome')") or die("Error in query");

$db->query("INSERT INTO books (title, author) VALUES ('A Study In Scarlet', 'Arthur Conan Doyle')") or die("Error in query");

$db->query("INSERT INTO books (title, author) VALUES ('Alice In Wonderland', 'Lewis Carroll')") or die("Error in query");

// print success message echo "<i>Database successfully initialized!";

// all done // destroy database object unset($db);

?>

Page 34: Php Sq Lite

A Few Extra Tools

• 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.

• The following example demonstrates the sqlite_libversion() and sqlite_libencoding() functions, which return the version number and encoding of the linked SQLite library respectively:

<?php

// version echo "SQLite version: ".sqlite_libversion()."<br />"; // encoding echo "SQLite encoding: ".sqlite_libencoding()."<br />";

?>

Page 35: Php Sq Lite

• When things go wrong, reach for the sqlite_last_error() function, which returns the last error code returned by SQLite.

• A numeric value – (couple it with the sqlite_error_string() function). • Consider the following example, which illustrates by attempting to run a

query with a deliberate error in it:

<?php

// set path of database file $db = $_SERVER['DOCUMENT_ROOT']."/../library.db";

// open database file $handle = sqlite_open($db) or die("Could not open database");

cont…

Page 36: Php Sq Lite

// generate query string // query contains a deliberate error $query = "DELETE books WHERE id = 1";

// execute query $result = sqlite_query($handle, $query) or die("Error in query: ".sqlite_error_string(sqlite_last_error($handle)));

// all done // close database file sqlite_close($handle);

?>

Page 37: Php Sq Lite

• 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.

• 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().