PHP CRUD Operations
What is CRUD?
| Operation | Description |
|---|---|
| Create | Insert data into the database |
| Read | Retrieve and display data |
| Update | Modify existing data |
| Delete | Remove data from the database |
Setup: Database and Table
SQL (run in phpMyAdmin or MySQL CLI):
CREATE DATABASE testdb;
USE testdb;
CREATE TABLE users (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100),
email VARCHAR(100)
);
1. Create (Insert Data)
<?php
$conn = mysqli_connect("localhost", "root", "", "testdb");
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = $_POST["name"];
$email = $_POST["email"];
$sql = "INSERT INTO users (name, email) VALUES ('$name', '$email')";
mysqli_query($conn, $sql);
echo "Record inserted successfully.";
}
?>
<form method="POST">
Name: <input type="text" name="name"><br><br>
Email: <input type="text" name="email"><br><br>
<input type="submit" value="Add User">
</form>
2. Read (Display Data)
<?php
$conn = mysqli_connect("localhost", "root", "", "testdb");
$result = mysqli_query($conn, "SELECT * FROM users");
echo "<h2>User List</h2><table border='1'><tr><th>ID</th><th>Name</th><th>Email</th><th>Actions</th></tr>";
while ($row = mysqli_fetch_assoc($result)) {
echo "<tr>
<td>{$row['id']}</td>
<td>{$row['name']}</td>
<td>{$row['email']}</td>
<td>
<a href='update.php?id={$row['id']}'>Edit</a> |
<a href='delete.php?id={$row['id']}'>Delete</a>
</td>
</tr>";
}
echo "</table>";
?>
3. Update (Edit Data)
<?php
$conn = mysqli_connect("localhost", "root", "", "testdb");
$id = $_GET["id"];
$result = mysqli_query($conn, "SELECT * FROM users WHERE id=$id");
$row = mysqli_fetch_assoc($result);
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = $_POST["name"];
$email = $_POST["email"];
mysqli_query($conn, "UPDATE users SET name='$name', email='$email' WHERE id=$id");
echo "Record updated.";
header("Location: read.php");
}
?>
<form method="POST">
Name: <input type="text" name="name" value="<?= $row['name'] ?>"><br><br>
Email: <input type="text" name="email" value="<?= $row['email'] ?>"><br><br>
<input type="submit" value="Update">
</form>
4. Delete (Remove Data)
<?php
$conn = mysqli_connect("localhost", "root", "", "testdb");
$id = $_GET["id"];
mysqli_query($conn, "DELETE FROM users WHERE id=$id");
echo "Record deleted.";
header("Location: read.php");
?>
| File | Purpose |
|---|---|
| create.php | Form to add new user |
| read.php | Displays user list |
| update.php | Edits existing user |
| delete.php | Deletes a user |
Quickly Find What You Are Looking For
OnlineTpoint is a website that is meant to offer basic knowledge, practice and learning materials. Though all the examples have been tested and verified, we cannot ensure the correctness or completeness of all the information on our website. All contents published on this website are subject to copyright and are owned by OnlineTpoint. By using this website, you agree that you have read and understood our Terms of Use, Cookie Policy and Privacy Policy.
point.com