Friday, 1 November 2013
PHP 101 (PART 9): SQLITE MY FIRE! – PART 2
Not My Type
Whilst on the topic of
back about how SQLite is typeless and so you can insert values of any
type into any field? There is one important exception to this rule: a
field marked as
numeric identifier for each record in the table, and if you insert a
INSERT, remember my statement a couple pagesback about how SQLite is typeless and so you can insert values of any
type into any field? There is one important exception to this rule: a
field marked as
INTEGER PRIMARY KEY. In SQLite, fields marked asINTEGER PRIMARY KEY do two important things: they provide a uniquenumeric identifier for each record in the table, and if you insert a
NULL value into them, SQLite automatically inserts a value that is 1greater than the largest value already present in that field.
INTEGER PRIMARY KEY fields in SQLite thus perform the equivalent ofAUTO_INCREMENT fields in MySQL, and are a convenient way ofautomatically numbering your records. Obviously, you can’t insert
non-numeric values into such a field, which is why I said they were an
exception to the typeless rule. Read more about this at
http://www.sqlite.org/datatypes.html.
Since the
such a field (the id field), it’s clear that every
books table used in the previous example already containssuch a field (the id field), it’s clear that every
INSERT into it with aNULL value for that field generates a new record number. If you’d liketo retrieve this number, PHP has a way to do that too – just use the
sqlite_last_insert_rowid() function, which returns the ID of thelast inserted row (equivalent to the
mysql_insert_id() functionin PHP’s MySQL API).
To see this in action, update the
previous script to include a call to
follows:
if() loop in the middle of theprevious script to include a call to
sqlite_last_insert_rowid(), asfollows:
<?php
// check to see if the form was submitted with a new recordif (isset($_POST['submit'])) {
// make sure both title and author are presentif (!empty($_POST['title']) && !empty($_POST['author'])) {
// make sure both title and author are presentif (!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'])."\")";
$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)));
$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 {
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 />";
}
}
// display error message
echo "<i>Incomplete form input. Record not inserted!</i><p />";
}
}
?>
If you need to, you can also find out how many rows were affected using
the
the
sqlite_changes() function – try it for yourself and see!Starting From Scratch
You’ll remember, from the beginning of this tutorial, that I suggested
you initialize the
commandline program. Well, that isn’t the only way to create a fresh
SQLite database – you can use PHP itself to do this, by issuing the
necessary
through the
you initialize the
library.db database using the SQLitecommandline program. Well, that isn’t the only way to create a fresh
SQLite database – you can use PHP itself to do this, by issuing the
necessary
CREATE TABLE and INSERT commandsthrough the
sqlite_query() function. Here’s how:
<?php
// set path of database file$db = $_SERVER['DOCUMENT_ROOT']."/../library2.db";
// create databasesqlite_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 recordssqlite_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)));
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!";
?>
Or, in PHP 5, you can use the object-oriented approach:
<?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");
$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 messageecho "<i>Database successfully initialized!";
// all done
// destroy database objectunset($db);
// destroy database objectunset($db);
?>A Few Extra Tools
Finally, 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
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() andsqlite_libencoding() functions, which return the version numberand encoding of the linked SQLite library respectively:
<?php?>
When things go wrong, reach for the
function, which returns the last error code returned by SQLite. Of
course, this error code – a numeric value – is not very useful in
itself; to convert it to a human-readable message, couple it with the
example, which illustrates by attempting to run a query with a
deliberate error in it:
sqlite_last_error()function, which returns the last error code returned by SQLite. Of
course, this error code – a numeric value – is not very useful in
itself; to convert it to a human-readable message, couple it with the
sqlite_error_string() function. Consider the followingexample, 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";
// generate query string
// query contains a deliberate error$query = "DELETE books WHERE id = 1";
// 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)));
?>
Here’s what the output looks like:
Note that although they might appear similar, the
and
as the
can be used independently of each other to retrieve the last error code
and message respectively, but the
on the error code returned by
sqlite_last_error()and
sqlite_error_string() functions don’t work in exactly the same wayas the
mysql_errno() and mysql_error() functions. Themysql_errno() and mysql_error() functionscan be used independently of each other to retrieve the last error code
and message respectively, but the
sqlite_error_string() is dependenton the error code returned by
sqlite_last_error().











0 Comments:
Post a Comment