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.
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(); } ?>
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(); } ?>
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(); } ?>
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; ?>
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!