Categories: Development

SQLite3 with PHP; Creating a database and connecting to it.

SQLite is a serverless, self-contained database that in practice works straight out of the box. With no need to install or run to access and use.

The SQLite library is 250KB in size compared to 650MB for the MySQL server package.

SQLite is used in programs and mobile apps/games to store data as it is an embedded database.

Its downside comes with using large databases as SQLite can only have a single write operation going at any one time.

SQLite3 with PHP

Since PHP 5.3.0 SQLite3 comes bundled and enabled with PHP as default.  This means it does not need to be installed or linked to use.

The easiest way to create a new SQLite database is to create a PDO connection to what you want the database called and it will create it if it does not exist.

$db = new PDO('sqlite:test_database.db', '', '', array(
    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
));

This will create test_database.db

If you want your database in a subfolder:

$db = new PDO('sqlite:/db/test_database.db', '', '', array( PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, ));

Once the database has been created/exists the above code is now used as the connection, with this you can create tables:

$db->exec("CREATE TABLE IF NOT EXISTS mytable (
    id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT);");

And insert data:

$db->exec("INSERT INTO mytable (id, name) VALUES (1, 'Mike')");

Or run any PDO SQLite commands.

Share

Recent Posts

Kennington reservoir drained drone images

A drained and empty Kennington reservoir images from a drone in early July 2024. The…

2 years ago

Merrimu Reservoir drone images

Merrimu Reservoir from drone. Click images to view larger.

2 years ago

Early September spring shots

Some early September spring shots from a bushwalk, It is still too early for wildflowers.

3 years ago

Cloning an NVMe to SK Hynix Platinum P41 NVMe

I recently needed to clone over a smaller NVMe to a 2TB SK Hynix Platinum…

3 years ago

Using Laravel’s deleteDirectory to delete folders and their contents

If you ever needed a simple solution in Laravel to delete an entire directory and…

3 years ago

How to allow only 1 user to register in a Laravel application

How to enforce only one user to register or be registered in a Laravel web…

3 years ago