CRUD Application in PHP and MySQL

Building a Simple CRUD Application in PHP and MySQL

CRUD stands for Create, Read, Update, and Delete – four basic operations that are essential for any application dealing with data management. In this guide, we’ll show you how to build a simple CRUD application using PHP and MySQL. Whether you are a beginner or experienced developer, this tutorial will walk you through the process step-by-step.

A CRUD Application in PHP and MySQL is essential for managing data in web development. CRUD stands for Create, Read, Update, and Delete, which are the core operations needed in any database-driven application. In this guide, we’ll walk you through building a fully functional CRUD application in PHP and MySQL, from setting up the database to writing PHP scripts for each operation.

Before diving into CRUD operations, if you’re new to PHP, check out our PHP Guide for Beginners: Learn, Code, and Build Your First Web Project Like a Pro to get a solid foundation in PHP programming.


Why Build a CRUD Application?

Building a CRUD application in PHP and MySQL is an essential skill for any web developer. It helps you understand how to work with databases, interact with forms, and manage data effectively. Whether you’re developing small applications or complex systems, mastering CRUD operations is crucial.


Why Use PHP and MySQL for CRUD Applications?

A CRUD Application in PHP and MySQL is widely used because:
✅ PHP is a server-side scripting language that works seamlessly with MySQL.
✅ MySQL is a reliable database management system for handling structured data.
✅ It allows for dynamic data manipulation with simple queries.
✅ Most web applications, including CMS and e-commerce platforms, use PHP and MySQL CRUD operations.


Prerequisites:

Before diving into the code, here’s what you’ll need:

  1. PHP and MySQL Setup – Ensure that PHP and MySQL are installed on your local server (e.g., XAMPP, WAMP, or MAMP).
  2. Code Editor – Use any text editor or IDE such as Visual Studio Code, Sublime Text, or PHPStorm to write your PHP code.

Step 1: Setting Up the Database

First, create a database and a table to store the data.

SQL Query:

CREATE DATABASE crud_app;
USE crud_app;

CREATE TABLE users (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100) NOT NULL,
email VARCHAR(100) NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

This query will create a database called crud_app and a table named users. The users table will have four columns: an auto-incrementing id, name, email, and created_at.

Step 2: Connecting to the Database in PHP

Next, let’s set up the connection between PHP and MySQL.

db.php (Database Connection):

<?php
$host = "localhost";
$username = "root";
$password = "";
$database = "crud_app";

// Create connection
$conn = new mysqli($host, $username, $password, $database);

// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
?>

This file establishes a connection to the MySQL database using mysqli.

Step 3: Creating the CRUD Operations

1. Create Operation (Insert Data)

To add data to the users table, we need an HTML form and PHP code to process the form data.

create.php:

<form method="POST" action="create.php">
Name: <input type="text" name="name" required><br>
Email: <input type="email" name="email" required><br>
<button type="submit" name="submit">Create User</button>
</form>

<?php
include('db.php');

if (isset($_POST['submit'])) {
$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;
}
}
?>

This code provides a form to enter user details and a PHP script to insert the data into the database.

2. Read Operation (View Data)

To view the list of users, we will fetch the data from the users table.

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";
}
?>

This will display the list of users stored in the database.

3. Update Operation (Edit Data)

You can edit the existing data using a form that will populate the fields with existing values.

update.php:

<?php
include('db.php');

if (isset($_GET['id'])) {
$id = $_GET['id'];
$sql = "SELECT * FROM users WHERE id=$id";
$result = $conn->query($sql);
$row = $result->fetch_assoc();
}

if (isset($_POST['submit'])) {
$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: " . $sql . "<br>" . $conn->error;
}
}
?>

<form method="POST">
Name: <input type="text" name="name" value="<?php echo $row['name']; ?>"><br>
Email: <input type="email" name="email" value="<?php echo $row['email']; ?>"><br>
<button type="submit" name="submit">Update User</button>
</form>

This code lets you update the name and email of a user.

4. Delete Operation (Remove Data)

To delete a record, you can create a simple delete button.

delete.php:

<?php
include('db.php');

if (isset($_GET['id'])) {
$id = $_GET['id'];
$sql = "DELETE FROM users WHERE id=$id";

if ($conn->query($sql) === TRUE) {
echo "Record deleted successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
}
?>

This script deletes a user record based on the id.

Step 4: Running the Application

Now that you have all the operations (Create, Read, Update, Delete) set up, you can run the application by visiting the respective pages in your browser:

  1. create.php to add new users
  2. read.php to view users
  3. update.php?id={id} to update user details
  4. delete.php?id={id} to delete a user

Best Practices for CRUD Applications in PHP and MySQL

To optimize your CRUD Application in PHP and MySQL, follow these best practices:
✅ Use prepared statements to prevent SQL injection.
Validate user input before inserting data.
✅ Implement error handling to catch database connection issues.
✅ Optimize queries for better performance.

Also, to avoid errors while developing your CRUD Application in PHP and MySQL, read Common PHP Mistakes and How to Avoid Them.


Frequently Asked Questions (FAQs)

1. What is a CRUD application?

A CRUD application allows users to create, read, update, and delete data in a database, which are the basic operations for data management.

2. Can I use this CRUD app in real projects?

Yes! This simple CRUD app is a great starting point for building more complex applications, like content management systems or e-commerce platforms.

3. Do I need a framework to build a CRUD app?

While you can build a CRUD app from scratch, using a framework like Laravel can make it more efficient by providing built-in functions and security features.

4. How can I add more functionality to this CRUD app?

You can enhance the app by adding user authentication, data validation, pagination for large datasets, and even a search functionality.

5. What is a CRUD application in PHP and MySQL?

A CRUD application in PHP and MySQL is a web-based system that allows users to Create, Read, Update, and Delete records in a database.


Conclusion

Building a CRUD application in PHP and MySQL is an essential skill for any web developer. With the steps outlined in this tutorial, you can create a basic CRUD app to manage data. As you progress, you can expand the app by adding more features like validation, authentication, or using frameworks such as Laravel or Symfony for more complex applications.

For more advanced CRUD operations, you can check out the PHP documentation. Happy coding!

Scroll to Top