Current Location: Home> Latest Articles> PHP and SQLite Data Deletion Guide: A Simple and Efficient Approach

PHP and SQLite Data Deletion Guide: A Simple and Efficient Approach

M66 2025-06-16

How to Perform Data Deletion Operations with PHP and SQLite

In modern PHP development, database operations are an essential part of most applications. SQLite, being a lightweight and efficient database, is widely used in many PHP projects. This article will provide a detailed guide on how to perform data deletion operations with SQLite in PHP, including creating a database, connecting to it, executing a delete operation, and closing the database connection.

Step 1: Create SQLite Database and Table

First, we need to create an SQLite database and define a table within it. Below is the PHP code to create an SQLite database named "test.db" and a table named "users".

<?php
try {
    $db = new PDO("sqlite:test.db");
    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $db->exec("CREATE TABLE IF NOT EXISTS users (
        id INTEGER PRIMARY KEY,
        name TEXT,
        email TEXT
    )");
} catch (PDOException $e) {
    echo "Error: " . $e->getMessage();
}
?>

Step 2: Connect to the SQLite Database

Next, we will connect to the previously created "test.db" SQLite database. Using the PDO class makes it easy to interact with SQLite databases in PHP.

<?php
try {
    $db = new PDO("sqlite:test.db");
    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
    echo "Error: " . $e->getMessage();
}
?>

Step 3: Perform the Deletion Operation

Once connected to the database, we can proceed with the deletion operation. For example, the code below deletes the user record with the name "John".

<?php
try {
    $db = new PDO("sqlite:test.db");
    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    
    $name = "John";
    $stmt = $db->prepare("DELETE FROM users WHERE name = :name");
    $stmt->bindParam(':name', $name);
    $stmt->execute();
    
    echo "Record deleted successfully";
} catch (PDOException $e) {
    echo "Error: " . $e->getMessage();
}
?>

Step 4: Close the Database Connection

After completing the deletion operation, it is good practice to close the database connection. Below is the code to close the SQLite database connection.

<?php
$db = null;
?>

Conclusion

This article introduced how to perform data deletion operations in PHP using SQLite. We covered everything from creating a database and table, connecting to the database, executing the delete operation, to finally closing the database connection. With these techniques, you can efficiently manage data deletion in SQLite databases in your PHP applications.

We hope this article was helpful to you!