How to Create a Simple CRUD Application in PHP
Creating a CRUD (Create, Read, Update, Delete) application is one of the foundational skills for any aspiring web developer. PHP, a popular server-side scripting language, makes it easy to develop a CRUD application with a straightforward approach. In this article, we’ll guide you through the process of building a simple CRUD application using PHP, MySQL, and HTML.
What is CRUD?
CRUD stands for Create, Read, Update, and Delete. These four operations form the backbone of most database applications, allowing users to manipulate data effectively. Here’s a brief overview of each operation:
- Create: Insert new records into the database.
- Read: Retrieve existing records from the database.
- Update: Modify existing records.
- Delete: Remove records from the database.
Use Cases of CRUD Applications
CRUD applications are everywhere, from simple contact forms to complex data management systems. Here are a few common use cases:
- Content Management Systems (CMS): Manage blog posts, user comments, and media.
- E-commerce Platforms: Handle product listings, inventory, and customer data.
- User Management Systems: Create user profiles, manage permissions, and track activity.
Tools You'll Need
To create a simple CRUD application in PHP, you'll need the following tools:
- PHP: The server-side scripting language.
- MySQL: The database management system.
- XAMPP: A free and open-source cross-platform web server solution stack package.
- Code Editor: Any text editor or integrated development environment (IDE) like Visual Studio Code or PHPStorm.
Step-by-Step Guide to Building a Simple CRUD Application
Step 1: Set Up Your Environment
- Download and Install XAMPP: This will give you a local server environment to run your PHP applications.
- Start Apache and MySQL: Open the XAMPP control panel and start both services.
Step 2: Create a MySQL Database
- Access phpMyAdmin by navigating to
http://localhost/phpmyadmin
in your web browser. - Create a new database named
crud_app
. - Create a table named
users
with the following columns: id
(INT, Primary Key, Auto Increment)name
(VARCHAR)email
(VARCHAR)
Use the following SQL query to create the table:
sql
CREATE TABLE users (
id INT(11) AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100) NOT NULL,
email VARCHAR(100) NOT NULL
);
Step 3: Create the PHP Files
You will need several PHP files to handle the CRUD operations.
1. config.php
This file will handle the database connection.
<?php
$host = "localhost";
$username = "root";
$password = "";
$dbname = "crud_app";
$conn = new mysqli($host, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
?>
2. create.php
This file will handle creating new users.
<?php
include 'config.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;
}
}
$conn->close();
?>
<form method="POST" action="">
Name: <input type="text" name="name" required>
Email: <input type="email" name="email" required>
<input type="submit" value="Create User">
</form>
3. read.php
This file will display the users.
<?php
include 'config.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";
}
$conn->close();
?>
4. update.php
This file will handle updating existing user data.
<?php
include 'config.php';
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$id = $_POST['id'];
$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;
}
}
$conn->close();
?>
<form method="POST" action="">
ID: <input type="text" name="id" required>
Name: <input type="text" name="name" required>
Email: <input type="email" name="email" required>
<input type="submit" value="Update User">
</form>
5. delete.php
This file will handle deleting users.
<?php
include 'config.php';
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$id = $_POST['id'];
$sql = "DELETE FROM users WHERE id=$id";
if ($conn->query($sql) === TRUE) {
echo "Record deleted successfully";
} else {
echo "Error deleting record: " . $conn->error;
}
}
$conn->close();
?>
<form method="POST" action="">
ID: <input type="text" name="id" required>
<input type="submit" value="Delete User">
</form>
Step 4: Testing Your Application
- Open your browser and navigate to
http://localhost/yourproject/create.php
to add a new user. - Go to
http://localhost/yourproject/read.php
to view users. - Use
update.php
anddelete.php
to modify or remove users.
Troubleshooting Common Issues
- Connection Errors: Ensure your database credentials in
config.php
are correct. - SQL Errors: Double-check your SQL syntax and the structure of your database.
- Empty Results: Ensure you have added users before trying to read them.
Conclusion
Creating a simple CRUD application in PHP is a great way to understand the basics of web development and database interaction. With this guide, you’ve learned how to set up a MySQL database, handle user input, and perform essential CRUD operations.
As you grow more comfortable with these concepts, consider exploring more advanced features such as user authentication, validation, and using frameworks like Laravel or CodeIgniter. Happy coding!