How to Create a CRUD Application with PHP, PDO, and OOP
What We Will Use To Build This Project ? :
- PHP Programming Language.
- JavaScript Programming Language.
- HTML & CSS.
- VSCode Editor.
- MySQL Database.
- PhpMyAdmin.
Project Source Code:
------------ Create A Class "db_connect" To Connect Our Form With Database
This file establishes a connection to a MySQL database using PDO (PHP Data Objects).
It sets up the connection parameters like the server name, username, password, and database name.
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "products_manager";
try{
$conn = new PDO("mysql: host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $ex){
echo"connection failed: " . $ex->getMessage();
die();
}
?>
------------ On The Index Page ------------
This file starts a PHP session, displays a form for searching, adding, editing, and removing products, and pre-populates form fields with product details if a search result is found in the session.
<?php
session_start();
?>
<!DOCTYPE html>
<html>
<head>
<title>Index</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<h1>CRUD POO</h1>
<div class="form-container">
<?php
$id = "";
$name = "";
$description = "";
$category = "";
$price = "";
if(isset($_SESSION['search-result']))
{
$product = $_SESSION['search-result'];
$id = $product['id'];
$name = $product['name'];
$description = $product['description'];
$category = $product['category'];
$price = $product['price'];
}
?>
<form action="functions.php" method="post">
<div class="search-container">
<input type="number" name="id" id="product-id" value="<?php echo $id ?>"
placeholder="id">
<input type="submit" name="search" value="Search" id="search-button">
</div>
<input type="text" name="name" id="product-name" value="<?php echo $name ?>"
placeholder="name">
<input type="text" name="category" id="product-category" value="<?php echo $category ?>"
placeholder="category">
<input type="text" name="description" id="product-description"
value="<?php echo $description ?>" placeholder="description">
<input type="text" name="price" id="product-price" value="<?php echo $price ?>"
placeholder="price">
<input type="submit" name="add" value="Add Product" id="add-button">
<input type="submit" name="edit" value="Edit Product" id="edit-button">
<input type="submit" name="remove" value="Remove Product" id="remove-button">
</form>
</div>
<?php
unset($_SESSION['search-result'])
?>
</body>
</html>
------------ The Product Class ------------
This file defines a Product class with private properties for product details such as name, description, category, and price.
This class provides methods to save new products to the database, update existing product records, remove products from the database, and search for products by their unique ID.
<?php
// Including the required database connection file
require_once 'db_connect.php';
// Class definition for the Product entity
class Product
{
private $name;
private $description;
private $category;
private $price;
// Constructor to initialize the Product object with provided values
public function __construct($name, $description, $category, $price)
{
$this->name = $name;
$this->description = $description;
$this->category = $category;
$this->price = $price;
}
// Method to save the Product to the database
public function saveToDatabase()
{
global $conn;
$stmt = $conn->prepare("INSERT INTO `products2`(`name`, `category`, `description`, `price`)
VALUES (:name, :category, :description, :price)");
$stmt->bindParam(':name', $this->name);
$stmt->bindParam(':category', $this->category);
$stmt->bindParam(':description', $this->description);
$stmt->bindParam(':price', $this->price);
return $stmt->execute();
}
// Method to update the Product in the database
public function updateInDatabase($productId)
{
global $conn;
$stmt = $conn->prepare("
UPDATE `products2` SET `name`=:name,`category`=:category,
`description`=:description,`price`=:price WHERE `id`=:id");
$stmt->bindParam(':name', $this->name);
$stmt->bindParam(':category', $this->category);
$stmt->bindParam(':description', $this->description);
$stmt->bindParam(':price', $this->price);
$stmt->bindParam(':id', $productId);
return $stmt->execute();
}
// Static method to remove a Product from the database
public static function removeFromDatabase($productId)
{
global $conn;
$stmt = $conn->prepare("DELETE FROM `products2` WHERE `id`=:id");
$stmt->bindParam(':id', $productId);
return $stmt->execute();
}
// Static method to search for a Product by its ID
public static function searchById($productId)
{
global $conn;
$stmt = $conn->prepare("SELECT * FROM `products2` WHERE `id`=:id");
$stmt->bindParam(':id', $productId);
$stmt->execute();
return $stmt->fetch(PDO::FETCH_ASSOC);
}
}
?>
------------ The Functions File ------------
This file includes the Product class definition and the db_connect file and handles form submissions from the index page.
If the "Add Product" button is clicked, it creates a new Product instance and saves it to the database.
If the "Edit Product" button is clicked, it creates a new Product instance and updates the product in the database.
If the "Remove Product" button is clicked, it removes the product from the database.
If the "Search" button is clicked, it searches for a product by ID, stores the result in a session variable, and redirects back to the index page to display the search result.
<?php
require_once 'Product.php';
// Add a new product
if(isset($_POST['add']))
{
// Get product details from the form
$productName = $_POST['name'];
$productCategory = $_POST['category'];
$productDescription = $_POST['description'];
$productPrice = $_POST['price'];
// Create a new Product instance
$product = new Product($productName, $productDescription, $productCategory, $productPrice);
// Save the product to the database
if($product->saveToDatabase())
{
echo'product inserted';
}
else{
echo'product not inserted';
}
}
// Edit an existing product
if(isset($_POST['edit']))
{
// Get product details from the form
$productId = $_POST['id'];
$productName = $_POST['name'];
$productCategory = $_POST['category'];
$productDescription = $_POST['description'];
$productPrice = $_POST['price'];
// Create a new Product instance
$product = new Product($productName, $productDescription, $productCategory, $productPrice);
// Update the product in the database
if($product->updateInDatabase($productId))
{
echo'product updated';
}
else{
echo'product not updated';
}
}
// Remove a product
if(isset($_POST['remove']))
{
// Get the product ID from the form
$productId = $_POST['id'];
// Remove the product from the database
if(Product::removeFromDatabase($productId))
{
echo'product removed';
}
else{
echo'product not removed';
}
}
// Search for a product
if(isset($_POST['search']))
{
// Get the product ID from the form
$productId = $_POST['id'];
// Search for products by ID
$product = Product::searchById($productId);
// Start a session
session_start();
// Store the search result in a session variable
$_SESSION['search-result'] = $product;
/* $test = $_SESSION['search-result'];
echo $test['name'].'<br>';
echo $test['price']; */
// Redirect to the next page to display the search results in a form
header("Location: index.php");
exit();
}
?>
////// OUTPUT :
Need Projects + Source Code?