SQLite is a portable, self-contained database that is perfect for small projects that don't want or need the overhead of a dedicated database engine. According to their website, it's also the "most widely deployed database engine in the world". In this tutorial, we'll be using PHP to create, open, modify, and read data from a SQLite database. You might be surprised at how easy it is.
The SQLite libraries are built right in to PHP 5, so that's the version I'll be using for this tutorial. You don't have to worry about licensing issues when using SQLite, since it's in the public domain.
Creating or Opening SQLite Database
Before we can start putting anything into a database or reading anything out of it, we first need to create one. The SQLiteDatabase constructor will do this for us:
try
{
//create or open the database
$database = new SQLiteDatabase('myDatabase.sqlite', 0666, $error);
}
catch(Exception $e)
{
die($error);
}
The first parameter of the constructor is the database file you'd like
to create or open. It doesn't need any particular extension, however I
chose .sqlite so I could easily identify SQLite databases using a file
explorer. The second parameter is currently ignored by the library,
however it will eventually control how the database will be opened (e.g.
read-only). The default value is 0666. The last parameter will contain
an error message if the database creation/open fails.
According to the documentation, the constructor will return a database handle on success or a boolean (false) on fail. However, when I tested a failure condition, it threw an exception instead - so I surrounded the creation with a try-catch block. I guess that's good advice for any developer - don't always trust the documentation.
Creating New SQLite Table
All right, now that we've successfully opened a SQLite database, let's start putting some data into it. I'm going to begin by creating a new table to hold some information about movies: Title, Director, and Year.
//add Movie table to database
$query = 'CREATE TABLE Movies ' .
'(Title TEXT, Director TEXT, Year INTEGER)';
if(!$database->queryExec($query, $error))
{
die($error);
}
Adding tables is pretty straight forward. Simply build the SQL query
then execute it using queryExec. SQLite doesn't quite have as many
data types as larger databases (like MySQL), but it has enough to get
the job done. You can see all of the supported data types on SQLite's
website.
If the query fails for any reason, queryExec will return false and
$error will be populated with the error message. A common reason why
the query will fail is that the table already exists.
Inserting Data Into SQLite Database
We've got our database, we've got our table, now it's time to push some rows into our Movies table. Inserting data will be done exactly like creating tables, except we'll use a different query.
//insert data into database
$query =
'INSERT INTO Movies (Title, Director, Year) ' .
'VALUES ("The Dark Knight", "Christopher Nolan", 2008); ' .
'INSERT INTO Movies (Title, Director, Year) ' .
'VALUES ("Cloverfield", "Matt Reeves", 2008); ' .
'INSERT INTO Movies (Title, Director, YEAR) ' .
'VALUES ("Beverly Hills Chihuahua", "Raja Gosnell", 2008)';
if(!$database->queryExec($query, $error))
{
die($error);
}
SQLite is capable of executing multiple queries at once - separated by semi-colons. Here I added three movies to my database using a single query. Just like before, if the query fails, the function will return false and the error message will be populated.
Reading Data From SQLite Database
The last thing we're going to do today is read the data that we just put into the database back out again.
//read data from database
$query = "SELECT * FROM Movies";
if($result = $database->query($query, SQLITE_BOTH, $error))
{
while($row = $result->fetch())
{
print("Title: {$row['Title']} <br />" .
"Director: {$row['Director']} <br />".
"Year: {$row['Year']} <br /><br />");
}
}
else
{
die($error);
}
First off, you'll need to create the SQL SELECT statement. In this case,
I just want everything in the database. Next, we call query. The first
parameter is the query we just created. The second parameter tells the
SQLite library how to form the output data. SQLITE_NUM will return
results as arrays only accessible by index. SQLITE_ASSOC will return
arrays only accessible by column name. The default value, SQLITE_BOTH,
returns arrays accessible by name or index. The last parameter will be
populated with an error message if one occurs.
To get the results, we simply call fetch on the result of the query
call. Fetch will return an array for each record returned or false if
there are no more. Since we chose SQL_BOTH, we can now reference the
arrays by column name to get the values. I simply output some HTML code
with the Title, Director, and Year.
That's it for creating, opening, modifying, and reading SQLite databases using PHP. Below is the entire script we created today.
try
{
//create or open the database
$database = new SQLiteDatabase('myDatabase.sqlite', 0666, $error);
}
catch(Exception $e)
{
die($error);
}
//add Movie table to database
$query = 'CREATE TABLE Movies ' .
'(Title TEXT, Director TEXT, Year INTEGER)';
if(!$database->queryExec($query, $error))
{
die($error);
}
//insert data into database
$query =
'INSERT INTO Movies (Title, Director, Year) ' .
'VALUES ("The Dark Knight", "Christopher Nolan", 2008); ' .
'INSERT INTO Movies (Title, Director, Year) ' .
'VALUES ("Cloverfield", "Matt Reeves", 2008); ' .
'INSERT INTO Movies (Title, Director, YEAR) ' .
'VALUES ("Beverly Hills Chihuahua", "Raja Gosnell", 2008)';
if(!$database->queryExec($query, $error))
{
die($error);
}
//read data from database
$query = "SELECT * FROM Movies";
if($result = $database->query($query, SQLITE_BOTH, $error))
{
while($row = $result->fetch())
{
print("Title: {$row['Title']} <br />" .
"Director: {$row['Director']} <br />".
"Year: {$row['Year']} <br /><br />");
}
}
else
{
die($error);
}
When this script is executed, you should see the following output:
Title: The Dark Night
Director: Christopher Nolan
Year: 2008
Title: Cloverfield
Director: Matt Reeves
Year: 2008
Title: Beverly Hills Chihuahua
Director: Raja Gosnell
Year: 2008
thank for the info. after i downloaded the file sqlite3.exe, which folder should i place it, so that the above step will work?
sqlite3.exe is simply a command line tool to let you access the database. It's not used for development - usually just administration and a quick way to work with the database. You don't have to download and install anything to make PHP 5 work with SQLite.
i have created one table in database using PHP & Mysql. Now i am having problem. i want to insert some of the records from table1 to table 2 so how to retrive from html form & how to insert that records into other table
Excellent Post, thanx for sharing the same.. Will keep on reading the post :D
Stumbled your post .. cheers
As a newbie to php, I find I work best with cheat sheets. Since I always have my iPhone with me, I keep them there. The best one I've found so far is from these guys:
http://itunes.apple.com/WebObjects/MZStore.woa/wa/viewSoftware?id=302760278&mt=8
They also have great cheat sheets for CSS and Javascript.
Speaking of which - Anyone know if you can run PHP on the iPhone?
Well not sure if what you mean but if your iPhone is jail broken you might be able to find an application to run php on it.
You should change the array column name from 'Title' to 'Name' at:
Currently, your code will not print the movie titles in the final stage.
Good catch! It looks like I switched it up half way through. What I really wanted was 'Title', so I changed the previous instances of 'Name' to 'Title'.
Um...Can you elaborate - My output was like yours; Please help me get this issue between Name and Title??? thanks.
I have fixed the post, so if you've used the code recently, you'll receive the correct output.
I'm new to PHP and SQLite. As a test, I copied the script you provided and tried it, both on a localhost (on a Mac) as well as online, after cleaning it up (only changing invisible bullets for spaces).
The localhost returns: "unable to open database [dir/myDatabase.sqlite]". And online, I get a parse error: "syntax error, unexpected '{' in [dir/filename] on line 3".
What's wrong?
Problem solved. It was stupidly only a matter of setting the correct permissions. Thanks anyway.
Hi Frederiek,
Im having exactly the same problem as you. How did you set the correct permissions? Thanks
Use chmod to change permissions on Linux.
This is a clear little tutorial and I learned the basics of SQLite/PHP from this tutorial, and I thank you for the nice work.
Thanks a lot. Well done. Clear and useful.
Awesome. Simple to understand but very effective!
Very nice. It was a good insight to SQLite. Nice work. :)
Very helpful and informative. Thanks.
Well done.
Very useful when evaluating its future use.
Thanks
thanks
very useful
The most useful example on the internet that I found. Thanks.
Thanks for this. Clean code. But where is the SQLite database saved when it is created? I mean, where's the file? How do I backup that file? Will myDatabase.sqlite be created in the same folder as this PHP file? Will I need SQLite to be installed already (I am on regular cpanel setup with CentOS)?
As for opening the file and inserting new records, or querying old records for display, I can use your code.
Pls enable some type of "subscribe to comments" functionality on your site so I can know when someone replies. It's pretty easy to find in Wordpress etc, but I suppose you're using drupal? Thanks anyway.
So far this looks like the best PHP/SQLite primer I've come across in the last 3 days. With PHP I am not a newbie but not an expert. I am new to SQLite. I'm trying to use the sample script here and can't get past the creation/opening of the DB. I am unceremoniously greeted with:
Fatal error: Class 'SQLiteDatabase' not found in [Path/filename.php line ##]
It sounds like this should be easy but thus far has been anything but. I was encouraged when I easily created and queried a DB using the sqlite3.exe cmd line interface but have been stymied trying to do anything from PHP.
Any help greatly appreciated!!
Gman
I should add, I am trying this on Windows 7
Gman
What version of PHP are you using? SQLite support is in PHP 5.
Obviously, this is a very old question, but I thought it would be good to answer for others who run into this. The error is coming from your php.ini file. To correct this error you must edit php.ini and add the line "extension=php_sqlite.dll" in the extensions block. Save the file and try again :)
thanks for the nifty article :)
peace
Thanks for this article, it was a great way for me to transition from mysql to this. Just a random suggestion... maybe you could write a follow-up post introducing prepared statements. Putting a security concept on all this would be extremely helpful :)
oops... was supposed to say "post introducing prepared statements".. sorry about that lol
Thanks for your tutorial I would like to know if this tutorial work with sqlite 2 or Sqlite 3 Thanks again!!
Hey great Tut, find it very useful!! But how to save the file on disk, is this possible?
Now, where is this database created, i am just curious to see how the databse would look like and also cross reference, may change something in the database and just read it from php
Thank you for your PHP with SQLite tutorial. I'm just getting started with it. It's exciting to see that your tutorial is still great after all these years.
Excellent article, but one newbie question: How do I open the existing database to select records from it? This article only shows how to retrieve in the same operation as creating it. I tried leaving out the word "new", but clearly this isn't it...
That call will open an existing database if it exists, or create a new one.
Thanks :)
ok I used the script to create myDatabase.sqlite but I can not open the database. running the script again I get the error message: table Movies already exists
trying to connect from the command line, he will not connect to myDatabase.sqlite and I get the message Error: file is encrypted or not a database.
with sqlite3_open I get the error: Sqlite3_open is not recognized as an internal or external command, prgram or batch file.
taking out the create table statements has the effect that nothing is happening. so what is my db problem? anyone knows?