PHP CRUD || Create, Read, Update, Delete.
Table of Contents
Introduction
This tutorial will guide you through the fundamental operations of PHP CRUD (Create, Read, Update, Delete). These operations are essential for managing data in web applications, allowing you to interact with databases effectively. By the end of this guide, you'll understand how to perform these operations using PHP and MySQL.
Step 1: Set Up Your Environment
Before you begin coding, ensure you have the necessary tools installed.
- Install XAMPP or MAMP to set up a local server environment.
- Download and install PHP and MySQL if they are not included in your package.
- Create a new folder in the
htdocs
(XAMPP) orwww
(MAMP) directory for your project.
Step 2: Create the Database
You need a database to perform CRUD operations.
- Open phpMyAdmin via your local server (usually at
http://localhost/phpmyadmin
). - Create a new database, e.g.,
crud_example
. - Create a table within this database. Here’s a sample SQL command to create a
users
table:
CREATE TABLE users (
id INT(11) AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100) NOT NULL,
email VARCHAR(100) NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
Step 3: Connect to the Database
Create a new PHP file named db.php
to handle your database connection.
<?php
$host = 'localhost';
$user = 'root'; // default user for XAMPP
$password = ''; // leave empty for XAMPP
$dbname = 'crud_example';
$conn = new mysqli($host, $user, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
?>
Step 4: Create Functionality for Create Operation
To add new users, you will create a form and handle form submission.
- Create a file called
create.php
:
<?php
include 'db.php';
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$name = $_POST['name'];
$email = $_POST['email'];
$sql = "INSERT INTO users (name, email) VALUES ('$name', '$email')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
}
?>
<form method="post" action="">
<input type="text" name="name" placeholder="Enter Name" required>
<input type="email" name="email" placeholder="Enter Email" required>
<button type="submit">Submit</button>
</form>
Step 5: Create Functionality for Read Operation
To display users from the database, create another file called read.php
.
<?php
include 'db.php';
$sql = "SELECT * FROM users";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "id: " . $row["id"] . " - Name: " . $row["name"] . " - Email: " . $row["email"] . "<br>";
}
} else {
echo "0 results";
}
?>
Step 6: Create Functionality for Update Operation
Create a file called update.php
to allow users to edit their information.
- First, fetch the user record you want to update. Use a GET request to capture the ID:
<?php
include 'db.php';
$id = $_GET['id'];
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$name = $_POST['name'];
$email = $_POST['email'];
$sql = "UPDATE users SET name='$name', email='$email' WHERE id=$id";
if ($conn->query($sql) === TRUE) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . $conn->error;
}
}
$sql = "SELECT * FROM users WHERE id=$id";
$result = $conn->query($sql);
$user = $result->fetch_assoc();
?>
<form method="post" action="">
<input type="text" name="name" value="<?php echo $user['name']; ?>" required>
<input type="email" name="email" value="<?php echo $user['email']; ?>" required>
<button type="submit">Update</button>
</form>
Step 7: Create Functionality for Delete Operation
To delete a user, create a file named delete.php
.
<?php
include 'db.php';
$id = $_GET['id'];
$sql = "DELETE FROM users WHERE id=$id";
if ($conn->query($sql) === TRUE) {
echo "Record deleted successfully";
} else {
echo "Error deleting record: " . $conn->error;
}
?>
Conclusion
You have now created a basic PHP CRUD application that allows you to create, read, update, and delete users in a database. This foundational knowledge of PHP and MySQL can be built upon to create more complex web applications. Consider exploring further topics such as form validation, user authentication, and AJAX for dynamic updates. Happy coding!