Sling Academy
Home/PHP/How to use SQLite in PHP

How to use SQLite in PHP

Last updated: January 12, 2024

Introduction

SQLite is a software library that provides a relational database management system. The lite in SQLite means lightweight in terms of setup, database administration, and required resource. PHP has built-in extensions for integrating with SQLite, making it a convenient choice for small to medium-sized projects. In this tutorial, we’re going to learn how to use SQLite in PHP, including basic operations like creating databases, writing queries, and managing data.

Setting up Your Environment

To work with SQLite in PHP, you’ll need PHP 5 or newer, as SQLite is bundled with PHP from version 5 onwards. Most current web hosting providers support PHP and SQLite, so you should be ready to go. If you are working locally, install a server environment like XAMPP or MAMP that supports PHP and comes with SQLite.

Creating a New SQLite Database

<?php
    $db = new SQLite3('my_database.db');
    echo 'Database created successfully';
?>

This snippet creates a new SQLite database file called ‘my_database.db’ or opens it if it already exists.

Creating Tables

<?php
    $db->exec('CREATE TABLE IF NOT EXISTS contacts (
        id INTEGER PRIMARY KEY AUTOINCREMENT, 
        name TEXT NOT NULL, 
        phone TEXT NOT NULL
    );');
    echo 'Table created successfully';
?>

This code will create a new table called ‘contacts’ if it doesn’t already exist in the database.

Inserting Data

<?php
    $statement = $db->prepare('INSERT INTO contacts (name, phone) VALUES (:name, :phone)');
    $statement->bindValue(':name', 'John Doe');
    $statement->bindValue(':phone', '123-456-7890');
    $statement->execute();
    echo 'Record created successfully';
?>

We’re using a prepared statement to insert data into our contacts table safely. It helps prevent SQL injection attacks.

Querying Data

<?php
    $results = $db->query('SELECT * FROM contacts');
    while ($row = $results->fetchArray()) {
        echo 'ID: ' . $row['id'] . ' Name: ' . $row['name'] . ' Phone: ' . $row['phone'];
    }
?>

This snipped fetches everything from the contacts table and prints out the results.

Updating Data

<?php
    $db->exec("UPDATE contacts SET phone = '999-999-9999' WHERE name = 'John Doe'");
    echo 'Record updated successfully';
?>

This code updates the phone number for contacts where the name is ‘John Doe’.

Deleting Data

<?php
    $db->exec("DELETE FROM contacts WHERE name = 'John Doe'");
    echo 'Record deleted successfully';
?>

This snippet will delete records from the contacts table where the name is ‘John Doe’.

Error Handling

<?php
    if (!$db->exec('SOME INVALID SQL')) {
        echo 'SQLite Error: ' . $db->lastErrorMsg();
    }
?>

This code checks if your SQL is executed correctly. If not, it will print out an error message.

Securing Your SQLite Database

# Keeping your .db files safe

You should ensure your .db files are not accessible via the web. Store your database file outside of the public_html directory whenever possible.

# Using encryption

SQLite databases do not come with built-in encryption. For sensitive data, consider using an extension like SQLCipher which extends SQLite with AES encryption.

Conclusion

In this tutorial, we’ve covered the basics of using SQLite in PHP. We’ve created a new SQLite database, defined a table structure, inserted data into that table, performed queries to retrieve and update that data, and cleaned up by deleting unnecessary records. Always remember to follow best practices when handling databases and ensure the security of your data. SQLite is a powerful tool when combined with PHP, providing a simple yet effective way to store data for web applications.

Next Article: How to use MongoDB in PHP

Previous Article: How to implement search by keyword in PHP and MySQL

Series: Building Dynamic Web Pages with PHP

PHP

You May Also Like

  • Pandas DataFrame.value_counts() method: Explained with examples
  • Constructor Property Promotion in PHP: Tutorial & Examples
  • Understanding mixed types in PHP (5 examples)
  • Union Types in PHP: A practical guide (5 examples)
  • PHP: How to implement type checking in a function (PHP 8+)
  • Symfony + Doctrine: Implementing cursor-based pagination
  • Laravel + Eloquent: How to Group Data by Multiple Columns
  • PHP: How to convert CSV data to HTML tables
  • Using ‘never’ return type in PHP (PHP 8.1+)
  • Nullable (Optional) Types in PHP: A practical guide (5 examples)
  • Explore Attributes (Annotations) in Modern PHP (5 examples)
  • An introduction to WeakMap in PHP (6 examples)
  • Type Declarations for Class Properties in PHP (5 examples)
  • Static Return Type in PHP: Explained with examples
  • PHP: Using DocBlock comments to annotate variables
  • PHP: How to ping a server/website and get the response time
  • PHP: 3 Ways to Get City/Country from IP Address
  • PHP: How to find the mode(s) of an array (4 examples)
  • PHP: Calculate standard deviation & variance of an array