This article will guide you through creating a simple CRUD application using MySQLi, a popular PHP extension for interacting with MySQL databases. We will cover each step in detail, along with code examples to help you understand the process better.
Setting Up the Environment
Before starting with the CRUD operations, ensure that you have a working PHP environment and a MySQL database set up. For this tutorial, we will use a database named crud_example and a table named users.
Database and Table Creation
CREATE DATABASE crud_example;
USE crud_example;
CREATE TABLE users (
id INT AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(50) NOT NULL,
email VARCHAR(100) NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
Establishing a Database Connection
To interact with the MySQL database, we need to establish a connection using MySQLi. This connection will be used throughout the CRUD operations.
PHP Code: Database Connection
connect_error) {
die("Connection failed: " . $conn->connect_error);
}
?>
This script will be included in all other files to establish a connection to the database.
Creating Data (Insert Operation)
The first step in our CRUD application is the creation of data. We will create a form to add a new user to the users table.
HTML Form for Creating a User
Create User
Create New User
PHP Code: Handling the Insert Operation
prepare("INSERT INTO users (username, email) VALUES (?, ?)");
$stmt->bind_param("ss", $username, $email);
// Execute the statement
if ($stmt->execute()) {
echo "New user created successfully!";
} else {
echo "Error: " . $stmt->error;
}
// Close the statement and connection
$stmt->close();
$conn->close();
}
?>
This script captures the data from the form and inserts it into the users table using a prepared statement, ensuring security against SQL injection.
Reading Data (Retrieve Operation)
The next step is to read and display the data from the database. We will create a script that fetches all the records from the users table and displays them in an HTML table.
PHP Code: Retrieving Data
query($sql);
?>
View Users
List of Users
ID
Username
Email
Created At
Actions
num_rows > 0) {
// Output data of each row
while($row = $result->fetch_assoc()) {
echo "
{$row['id']}
{$row['username']}
{$row['email']}
{$row['created_at']}
Edit |
Delete
";
}
} else {
echo "No users found ";
}
?>
close();
?>
This script fetches all records from the users table and displays them in a table. Each row includes options to edit or delete the user.
Updating Data (Update Operation)
The update operation allows us to modify existing data in the database. We will create a form to edit a user’s details and a PHP script to handle the update.
HTML Form for Updating a User
prepare($sql);
$stmt->bind_param("i", $id);
$stmt->execute();
$result = $stmt->get_result();
$user = $result->fetch_assoc();
if (!$user) {
echo "User not found!";
exit();
}
}
?>
Edit User
Edit User
prepare("UPDATE users SET username=?, email=? WHERE id=?");
$stmt->bind_param("ssi", $username, $email, $id);
// Execute the statement
if ($stmt->execute()) {
echo "User updated successfully!";
} else {
echo "Error: " . $stmt->error;
}
// Close the statement and connection
$stmt->close();
$conn->close();
}
?>
This script updates the user details in the users table based on the ID passed through the form.
Deleting Data (Delete Operation)
Finally, we need to implement the delete operation to remove users from the database.
PHP Code: Handling the Delete Operation
prepare("DELETE FROM users WHERE id=?");
$stmt->bind_param("i", $id);
// Execute the statement
if ($stmt->execute()) {
echo "User deleted successfully!";
} else {
echo "Error: " . $stmt->error;
}
// Close the statement and connection
$stmt->close();
$conn->close();
}
?>
This script deletes the user from the users table based on the ID passed through the URL.
Conclusion
Creating a simple CRUD application using MySQLi involves establishing a database connection, and implementing the Create, Read, Update, and Delete operations. This guide provided a step-by-step approach with examples to help you build a functional CRUD application.
In summary:
- Create: Insert new data into the database.
- Read: Retrieve and display data from the database.
- Update: Modify existing data in the database.
- Delete: Remove data from the database.
By following these steps, you can create a robust CRUD application that forms the backbone of many web applications. As you gain more experience, you can extend this basic application with features like pagination, search, and user authentication to enhance its functionality.