CRUD Operations in PHP
CRUD stands for Create, Read, Update, and Delete, which are the basic operations for
managing data in a database. Below is a practical implementation of CRUD in PHP.
Step 1: Database Connection
Before performing any operation, connect to the database:
<?php
$conn = new mysqli("localhost", "root", "", "test_db");
if ($conn->connect_error) die("Connection failed: " . $conn->connect_error);
?>
Step 2: Create (Insert Data)
Add new records to the database using an INSERT query:
<?php
$conn->query("INSERT INTO users (name, email) VALUES ('Alice', 'alice@example.com')");
?>
Explanation: The INSERT query adds a new record with the name "Alice" and the email
"alice@example.com" to the users table.
Step 3: Read (Retrieve Data)
Retrieve and display records from the database using a SELECT query:
<?php
$result = $conn->query("SELECT * FROM users");
while ($row = $result->fetch_assoc()) {
echo "{$row['id']} - {$row['name']} - {$row['email']}<br>";
}
?>
Explanation: The SELECT query fetches all data from the users table. The while loop iterates
over the results and prints each row.
Step 4: Update (Modify Data)
Modify existing records in the database using an UPDATE query:
<?php
$conn->query("UPDATE users SET email = 'updated@example.com' WHERE id = 1");
?>
Explanation: The UPDATE query changes the email of the user with ID 1 to
'updated@example.com'.
Step 5: Delete (Remove Data)
Remove records from the database using a DELETE query:
<?php
$conn->query("DELETE FROM users WHERE id = 1");
?>
Explanation: The DELETE query removes the record with ID 1 from the users table.
Step 6: Close the Connection
After performing the CRUD operations, close the database connection:
<?php
$conn->close();
?>