PHP And MySQL - Project Example With Source Code
What We Will Use To Build This Project ? :
- PHP Programming Language.
- JavaScript Programming Language.
- HTML & CSS.
- Font-Awesome.
- VSCode Editor.
- MySQL Database.
- PhpMyAdmin.
Project Source Code:
------------ Create A Class "db_connect" To Connect Our Project With Database
This file establishes a connection to a MySQL database by setting up a PDO (PHP Data Objects) connection, to facilitate interactions with the database while handling exceptions and displaying an error message in the event of a connection failure.
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "products_manager_db";
try
{
$conn = new PDO("mysql: host=$servername; dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e){
echo "connection failed: " . $e->getMessage();
die();
}
?>
------------ On The Manager Page ------------
This page functions as a product management interface, retrieving data from a database and presenting it in an HTML table.
It offers a form enabling users to add new products, specifying details like name, description, price, and image, with the ability to upload images.
The system provides feedback to users through session variables, displaying messages indicating the success or failure of their actions.
JavaScript Section: This script attaches event listeners to the "Remove" buttons associated with each product in the table.
When a "Remove" button is clicked, it triggers a request to a delete-product.php script to initiate the deletion process.
It incorporates a confirmation dialog to ensure user consent before proceeding with the deletion action. Additionally, the script utilizes JavaScript alerts to convey success or error messages to the user.
<?php
require_once 'db_connect.php';
$stmt = $conn->prepare("SELECT * FROM `product`");
$stmt->execute();
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" type="text/css" href="style.css">
<title>Product Manager</title>
</head>
<body>
<div class="header">
<h1>Product Manager</h1>
</div>
<div class="main-container">
<?php
session_start();
if(isset($_SESSION['error']))
{
echo '<div class="alert error">
<p>'.$_SESSION['error'].'</p>
<span class="close">×</span></div>';
}
elseif(isset($_SESSION['success']))
{
echo '<div class="alert success">
<p>'.$_SESSION['success'].'</p>
<span class="close">×</span></div>';
}
unset($_SESSION['success']);
unset($_SESSION['error']);
?>
<div class="form-container">
<h2>Add Product</h2>
<form action="add.php" method="post" enctype="multipart/form-data">
<div class="form-input">
<input type="text" name="name" id="name" placeholder="Name">
</div>
<div class="form-input">
<input type="text" name="description" id="description" placeholder="Description">
</div>
<div class="form-input">
<input type="text" name="price" id="price" placeholder="Price">
</div>
<div class="file-input">
<label for="product-image">Product Image:</label></br>
<input type="file" name="product-image" id="product-image">
</div>
<div class="form-input">
<input type="submit" name="submit" value="Add">
</div>
</form>
</div>
<div class="table-container">
<h2>Products</h2>
<table id="products-table">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Price</th>
<th>Description</th>
<th>Image</th>
<th>Action</th>
</tr>
</thead>
<tbody id="product-table-body">
<?php
foreach($results as $row)
{
echo "<tr>";
echo "<td>".$row['id']."</td>";
echo "<td>".$row['name']."</td>";
echo "<td>".$row['price']."</td>";
echo "<td>".$row['description']."</td>";
echo "<td style='width:100px; height:100px;'><img src='".$row['image']."'
style='width:100%; height:100%;'></td>";
echo "<td style='text-align:center;'>";
echo "<div class='edit-product-button'>
<a href=edit.php?id=".$row['id'].">Edit</a>
</div>";
echo "<input type='submit' class='remove-product-button'
data-product-id=".$row['id']." data-product-image=".$row['image']."
value='Delete'>";
echo "</td>";
echo "</tr>";
}
?>
</tbody>
</table>
<br><br><br><br><br><br><br><br><br><br><br>
</div>
</div>
<script>
// Select all the buttons with class "remove-product-button"
const removeProductButton = document.querySelectorAll(".remove-product-button");
// Loop through each button and add an event listener for the 'click' event
removeProductButton.forEach(button=>{
button.addEventListener('click', event=>{
// Get the product ID and product image from the button's data attributes
const product_id = event.target.dataset.productId;
const product_image = event.target.dataset.productImage;
// Ask the user for confirmation before proceeding with the deletion
const confirmation = confirm("Are you sure you want to delete this product?");
// If the user confirms, send a request to delete-product.php
// passing the product ID and image as query parameters
if(confirmation)
{
fetch(`delete-product.php?id=${product_id}&image=${product_image}`)
.then(response=>{return response.json();})
.then(data=>{
// If the deletion was successful, show an alert and reload the page
if(data.success){
alert('Product removed successfully');
location.reload();
}
// If the deletion failed, show an alert
else{
alert('An erro occured while removing this product');
}
})
.catch(error=>{alert(error);});
}
});
});
// This code adds event listeners to all the remove-product-button elements
// and deletes a product when clicked.
// The product's ID and image are passed as query parameters to delete-product.php.
// If the deletion is successful, the page is reloaded, otherwise an alert is shown.
</script>
<script>
// close the alert
document.querySelectorAll(".close").forEach(function(closeButton){
closeButton.addEventListener("click", function(){
closeButton.parentElement.style.display = "none";
});
});
</script>
</body>
</html>
------------ The Add Product Page ------------
This file manages the form submission process for adding new products.
It validates the uploaded image, checking both its file type and size.
If the validation is successful, the script inserts the product details and the image path into the database. After processing, it redirects the user back to the manager page, displaying appropriate success or error messages based on the outcome of the operation.
<?php
//Include the db_connect.php file to connect to the database
require_once 'db_connect.php';
//Check if the form is submitted
if(isset($_POST['submit']))
{
session_start();
//Get the values from the form inputs and store them in variables
$name = $_POST['name'];
$description = $_POST['description'];
$price = $_POST['price'];
//Set the target directory for the image upload
$target_directory = "images/";
//Set the target file path for the image upload
$target_file = $target_directory.basename($_FILES["product-image"]["name"]);
//Get the file extension of the image
$imageFileType = strtolower(pathinfo($target_file, PATHINFO_EXTENSION));
// Check if the "product-image" file has been uploaded
if(isset($_FILES["product-image"]["tmp_name"]))
{
// Check if the size of the file is larger than 500000 bytes
if($_FILES["product-image"]["size"] > 80000){
// If the file size is too large, show error message using session
// and redirect to manage.php
$_SESSION['error'] = 'Error - File Size to Large';
header('Location: manager.php');
return;
}
// Check if the file type is not jpg, png, jpeg or gif
if($imageFileType != "jpg" && $imageFileType != "png" &&
$imageFileType != "jpeg" && $imageFileType != "gif")
{
// If the file type is invalid, show error message using session
// and redirect to manage.php
$_SESSION['error'] = 'Error - Wrong File Type';
header('Location: manager.php');
return;
}
// Check if the file was uploaded successfully
if(move_uploaded_file($_FILES["product-image"]["tmp_name"], $target_file))
{
try
{
// Prepare the insert statement to add the product details to the database
$stmt = $conn->prepare("INSERT INTO `product`(`name`, `description`, `price`, `image`)
VALUES (:name, :description, :price, :image)");
// Bind the parameters to the statement
$stmt->bindParam(':name', $name);
$stmt->bindParam(':description', $description);
$stmt->bindParam(':price', $price);
$stmt->bindParam(':image', $target_file);
// Execute the statement and check if it was successful
if($stmt -> execute())
{
// Redirect to the manage page with success message
$_SESSION['success'] = 'Product Added Successfully';
header('Location: manager.php');
return;
}
else
{
// Redirect to the manage page with error message
$_SESSION['error'] = 'Error - Product Not Added';
header('Location: manager.php');
return;
}
} catch(PDOException $e){
// If an error occurs, display an error message
$_SESSION['error'] = 'Error - '.$e->getMessage();
}
}
}
}
?>
------------ The Edit Product Page ------------
This file retrieves product details based on the provided product ID, displays an edit form for the product's name, description, price, and image, permits users to upload a new image or keep the existing one, manages form submissions for updating product details, offers success or error messages via session variables, and incorporates JavaScript to preview selected images before uploading.
<?php
require_once 'db_connect.php';
$product_id = filter_input(INPUT_GET, 'id', FILTER_VALIDATE_INT);
if($product_id === false){
die("Invalid Product ID.");
}
$stmt = $conn->prepare("SELECT * FROM product WHERE id = :id");
$stmt->bindParam(':id', $product_id);
$id = "";
$name = "";
$description = "";
$price = "";
$image = "";
if($stmt->execute())
{
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
if($results)
{
foreach($results as $row)
{
$id = $row['id'];
$name = $row['name'];
$description = $row['description'];
$price = $row['price'];
$image = $row['image'];
}
}
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" type="text/css" href="edit-style.css">
<title>Edit Product</title>
</head>
<body>
<div class="form-container">
<form action="edit-product.php" method="post" class="product" enctype="multipart/form-data">
<?php
session_start();
if(isset($_SESSION['error']))
{
echo '<div class="alert error">
<p>'.$_SESSION['error'].'</p>
<span class="close">×</span></div>';
}
elseif(isset($_SESSION['success']))
{
echo '<div class="alert success">
<p>'.$_SESSION['success'].'</p>
<span class="close">×</span></div>';
}
unset($_SESSION['success']);
unset($_SESSION['error']);
?>
<div class="form-image">
<img src="<?php echo $image ?>" alt="product image" id="preview">
<input type="file" id="product-image" name="product-image">
<br>
</div>
<div class="form-details">
<h2>Edit Product</h2>
<input type="hidden" name="id" value="<?php echo $id ?>">
<input type="text" name="name" placeholder="Product Name" value="<?php echo $name ?>">
<textarea name="description" placeholer="Product Description" value="
<?php echo $description ?>"><?php echo $description ?></textarea>
<input type="text" name="price" placeholder="Product Price" value="
<?php echo $price ?>">
<input type="submit" name="submit" value="Save Changes">
<span class="edit-product-button">
<a href="manager.php">Back to Manage</a>
</span>
</div>
</form>
</div>
<script>
// display the selected image
// Get the input element and the preview element
const input = document.querySelector('#product-image');
const preview = document.querySelector('#preview');
// Listen for the input event
input.addEventListener('change', ()=>{
// Get the selected file
const file = input.files[0];
// If a file was selected, create a FileReader object
if(file){
const reader = new FileReader();
// Set the callback function for when the file is loaded
reader.onload = () => {
// Update the preview element's source attribute with the loaded data
preview.src = reader.result;
}
// Read the file as a data URL
reader.readAsDataURL(file);
}
});
</script>
<script>
// close the alert
document.querySelectorAll(".close").forEach(function(closeButton){
closeButton.addEventListener("click", function(){
closeButton.parentElement.style.display = "none";
});
});
</script>
</body>
</html>
------------ The Delete Product Page ------------
This file processes requests to delete a product, receiving the product's ID and image path as GET parameters.
It then attempts to remove the corresponding product from the database and, if present, the associated image file.
After this operation, it sends a JSON response to indicate whether the deletion was successful or not.
<?php
// Set the content type to JSON
header('Content-Type: application/json');
// Include the database connection
require_once 'db_connect.php';
try
{
// Get the product ID and image from the GET request
$product_id = $_GET['id'];
$product_image = $_GET['image'];
// Prepare and execute the SQL query to delete the product
$stmt = $conn->prepare("DELETE FROM `product` WHERE `id`=:id");
$stmt->execute(["id"=>$product_id]);
// If the product image file exists, delete it from the server / folder
if(file_exists($product_image))
{
unlink($product_image);
}
// Check if any rows were affected by the SQL query
if($stmt->rowCount() > 0)
{
// If at least one row was affected, send a success JSON response
echo json_encode(["success"=>true]);
}
else
{
// If no rows were affected, send a failure JSON response
echo json_encode(["success"=>false]);
}
}
catch(PDOException $e)
{
// If there was an error with the database connection or query, send a failure JSON response
echo json_encode(["success"=>false]);
}
?>
////// OUTPUT :
PHP MySQL Project - Manage Products |
PHP MySQL Project - Add Product |
PHP MySQL Project - Edit Product |
PHP MySQL Project - Display Products |
if you want the source code click on the download button below
disclaimer: you will get the source code with the database script and to make it work in your machine is your responsibility and to debug any error/exception is your responsibility this project is for the students who want to see an example and read the code not to get and run.
Aucun commentaire:
Enregistrer un commentaire