3.6. Using SQLite

Beginning with PHP 5.0, PHP includes the SQLite software by default. SQLite is designed to store data in a flat file using SQL queries. (SQL is explained in Book III, Chapter 1.)

SQLite is a quick, easy way to store data in a flat file. However, it's less secure than a database and can't handle data that is very complex. In most cases, you should store your data in MySQL, but you occasionally might want to store your data in a flat file. For example, you might want to write the data in a format that can be read by another program, such as Excel.

Storing and retrieving data with SQLite is very similar to the methods described in Book III for using MySQL with PHP. You use SQL to communication with the data file and use PHP functions to send the SQL and retrieve the data. You interact with the data by using the same steps that you use with a database, as follows:

  1. Connect to the data file.

  2. Send an SQL query.

  3. If you retrieved data from the data file, process the data.

  4. Close the connection to the data file.

To connect to the data file, use the following PHP function:

$db = sqlite_open("testdb");

This statement opens the data file testdb. If the file doesn't exist, it creates it.

To send an SQL query, use the sqlite_query function, as follows:

$sql = "SELECT * FROM Product";
$result = sqlite_query($db,$sql);

The retrieved data is stored in a temporary table in rows and columns. You can use PHP functions to retrieve one row from the temporary data table and store it in ...

Get PHP & MySQL® Web Development All-in-One Desk Reference for Dummies® now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.