Creating a basic CRUD (Create, Read, Update, Delete) application in PHP involves building a system that allows you to perform these four fundamental operations on a database. Here’s a simple example using MySQL as the database. Make sure you have a web server (like Apache) and PHP installed on your system.
- Create a Database:
CREATE DATABASE IF NOT EXISTS crud_example;
USE crud_example;
CREATE TABLE IF NOT EXISTS users (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(50) NOT NULL,
email VARCHAR(50) NOT NULL
);
- Create Connection:
Create a file nameddb.php
to handle the database connection.
<?php
$host = 'localhost';
$username = 'your_username';
$password = 'your_password';
$database = 'crud_example';
$conn = new mysqli($host, $username, $password, $database);
if ($conn->connect_error) {
die('Connection failed: ' . $conn->connect_error);
}
Replace 'your_username'
and 'your_password'
with your actual MySQL username and password.
- Create Read Operation:
Create a file namedread.php
to display the records.
<?php
include 'db.php';
$result = $conn->query('SELECT * FROM users');
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
echo 'ID: ' . $row['id'] . '<br>';
echo 'Name: ' . $row['name'] . '<br>';
echo 'Email: ' . $row['email'] . '<br><br>';
}
} else {
echo 'No records found';
}
$conn->close();
- Create Create Operation:
Create a file namedcreate.php
to insert new records.
<?php
include 'db.php';
$name = 'John Doe';
$email = 'john@example.com';
$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();
- Create Update Operation:
Create a file namedupdate.php
to modify existing records.
<?php
include 'db.php';
$newEmail = 'john.new@example.com';
$userId = 1;
$sql = "UPDATE users SET email='$newEmail' WHERE id=$userId";
if ($conn->query($sql) === TRUE) {
echo 'Record updated successfully';
} else {
echo 'Error updating record: ' . $conn->error;
}
$conn->close();
- Create Delete Operation:
Create a file nameddelete.php
to remove records.
<?php
include 'db.php';
$userId = 1;
$sql = "DELETE FROM users WHERE id=$userId";
if ($conn->query($sql) === TRUE) {
echo 'Record deleted successfully';
} else {
echo 'Error deleting record: ' . $conn->error;
}
$conn->close();
Remember to replace the dummy data and connection details with your actual data. Also, consider adding proper error handling and validation in a real-world scenario. This example is for educational purposes and may not be suitable for production without additional security measures.
Show Comments