Inventory Management System Project using PHP and MYSQL
Overview of the Inventory Management System Project
The Inventory Management System is a web-based application developed using PHP and MySQL to manage and streamline various tasks related to inventory, products, suppliers, stock levels, orders, and reporting. This project allows businesses to track product availability, monitor stock levels, handle supplier information, manage customer orders, and generate sales reports.
The system focuses on advanced-level functionalities,
designed to help businesses optimize inventory tracking, enhance customer
service, and ensure smooth operations by automating the core tasks involved in
inventory management.
Key Features:
- Product
Management:
- Add,
Edit, Delete Products: The system enables users to add new products,
update existing ones, or remove them from the system.
- Product
Details: Stores essential product details such as name, description,
price, and supplier information.
- Supplier
Management: Users can manage supplier details and assign products to
their respective suppliers for better tracking.
- Stock
Management:
- Stock
Levels: The system allows users to track stock levels for each
product.
- Stock
Updates: Users can manually update stock quantities, reflecting
inventory changes due to orders, purchases, or damages.
- Automated
Stock Reduction: Stock levels are automatically updated when an order
is placed, ensuring real-time monitoring of inventory.
- Order
Management:
- Customer
Orders: Users can place orders, specifying customer details,
products, quantities, and order dates.
- Order
Items: Each order can consist of multiple products, with quantities
and prices specified for each item.
- Order
Processing: The system deducts product quantities from stock when an
order is confirmed, ensuring accurate inventory tracking.
- Suppliers
Management:
- Manage
Suppliers: Add and update supplier information, including contact
details.
- Link
Products to Suppliers: Assign products to specific suppliers to track
from where the stock is sourced.
- Reports
and Analysis:
- Sales
Reports: Generate reports based on customer orders and display total
sales for specific time periods or for specific products.
- Stock
Reports: View reports on stock levels to ensure that products are
adequately stocked and can be reordered from suppliers as needed.
- Order
Reports: Track customer order histories and sales trends to help
businesses with decision-making.
- Data
Integrity and Security:
- Database
Operations: Uses MySQL to manage data storage with relational
database tables for products, orders, suppliers, and stock levels.
- Transaction
Management: For operations like order placement and stock updates,
the system uses transactions to ensure data consistency.
Technology Stack:
- Frontend:
Basic HTML forms and Bootstrap for styling the user interface and
providing a responsive design.
- Backend:
PHP for handling server-side logic and communication with the MySQL
database.
- Database:
MySQL to store product, order, supplier, and stock level information, with
relational tables.
- Bootstrap:
A CSS framework used to enhance the visual layout and create a responsive
user interface.
Core Functionalities:
- Product
CRUD Operations: Allows the creation, reading, updating, and deletion
of products from the inventory system.
- Stock
Tracking: Users can track and update stock levels for each product.
- Order
Placement: Customers' orders are placed and stored, and stock levels
are automatically reduced.
- Supplier
Management: Keeps track of product suppliers and provides detailed
information for procurement.
- Report
Generation: Generate sales and stock reports to analyze the system's
performance and make business decisions.
Advantages of the System:
- Real-Time
Inventory Tracking: The system provides a real-time view of stock
levels and ensures that the stock is automatically updated when orders are
placed.
- Streamlined
Order Management: With easy-to-use forms for placing orders and
tracking customers, the system simplifies the order process.
- Sales
Reporting: Users can track sales over time, helping businesses
evaluate performance and make informed decisions.
- Supplier
Coordination: The system facilitates supplier management by tracking
which products are sourced from which supplier.
- User-Friendly
Interface: Bootstrap integration ensures that the system is easy to
navigate, even for users with minimal technical knowledge.
Expansion Ideas:
In the future, the system can be expanded to include:
- User
Authentication and Roles: Implement user login and roles for managing
access levels (admin, sales team, etc.).
- Invoice
and Payment Management: Generate invoices and manage customer payments
for a more complete order lifecycle.
- API
Integration: Integrate with external APIs for advanced features like
real-time shipping calculations or product sourcing.
- Barcode
Scanning: Incorporate barcode scanning for quick stock updates and
product identification.
Conclusion:
The Inventory Management System is an essential tool
for businesses that need efficient inventory tracking, order processing, and
supplier management. With its user-friendly interface, real-time stock
tracking, and reporting capabilities, this system can help businesses minimize
stock discrepancies, improve supplier relations, and enhance decision-making
through detailed reports.
Developing an Inventory Management System in PHP and
MySQL involves several steps and code implementations to manage products, stock
levels, orders, and suppliers, and includes report generation. I'll guide you
through the development process with step-by-step explanations and code
examples for beginners. This will be an advanced-level project, and I will
break it down into sections.
Steps for Developing Inventory Management System:
1. Setting Up the Environment
- Install
XAMPP (or WAMP) for local development, which includes PHP, MySQL,
and phpMyAdmin.
- Install
Composer for managing PHP dependencies.
2. Create the MySQL Database
First, you need to create a MySQL database for the inventory
management system.
- Open
phpMyAdmin from XAMPP.
- Create
a new database named inventory_db.
3. Design the Database Tables
You’ll need multiple tables for the system:
- products:
Store product information.
- suppliers:
Store supplier details.
- orders:
Track customer orders.
- order_items:
Items included in each order.
- stock_levels:
Manage the stock levels of products.
-- Table: products
CREATE TABLE products (
id INT
AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(255) NOT
NULL,
description TEXT,
price DECIMAL(10, 2)
NOT NULL,
supplier_id INT,
created_at TIMESTAMP
DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP
DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
);
-- Table: suppliers
CREATE TABLE suppliers (
id INT
AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(255) NOT
NULL,
contact_info TEXT,
created_at TIMESTAMP
DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP
DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
);
-- Table: orders
CREATE TABLE orders (
id INT
AUTO_INCREMENT PRIMARY KEY,
customer_name VARCHAR(255)
NOT NULL,
order_date DATE,
total DECIMAL(10, 2),
created_at TIMESTAMP
DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP
DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
);
-- Table: order_items
CREATE TABLE order_items (
id INT
AUTO_INCREMENT PRIMARY KEY,
order_id INT,
product_id INT,
quantity INT NOT NULL,
price DECIMAL(10, 2),
created_at TIMESTAMP
DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP
DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
);
-- Table: stock_levels
CREATE TABLE stock_levels (
id INT
AUTO_INCREMENT PRIMARY KEY,
product_id INT,
quantity INT NOT NULL,
last_updated TIMESTAMP
DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
);
4. Setting Up Project Files and Folders
In your htdocs folder (XAMPP), create a new folder called inventory_system.
- Folder
structure:
- index.php
- includes/
(for header, footer, and database connection files)
- products/
(for product management files)
- orders/
(for managing orders)
- suppliers/
(for supplier management)
- stock/
(for stock management)
- reports/
(for report generation)
5. Connect PHP to the MySQL Database
In the includes/ folder, create a file db.php for the
database connection.
<?php
// db.php
$host = "localhost";
$user = "root";
$password = "";
$database = "inventory_db";
// Create connection
$conn = new mysqli($host, $user, $password, $database);
// Check connection
if ($conn->connect_error) {
die("Connection
failed: " . $conn->connect_error);
}
?>
6. Product Management
Add Product
Create a form to add a product (products/add.php).
<?php
include '../includes/db.php';
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$name = $_POST['name'];
$description = $_POST['description'];
$price = $_POST['price'];
$supplier_id = $_POST['supplier_id'];
$sql = "INSERT
INTO products (name, description, price, supplier_id)
VALUES ('$name',
'$description', '$price', '$supplier_id')";
if ($conn->query($sql))
{
echo "Product
added successfully!";
} else {
echo "Error:
" . $conn->error;
}
}
?>
<form method="POST">
<input type="text"
name="name" placeholder="Product Name" required>
<textarea name="description"
placeholder="Product Description"></textarea>
<input type="number"
step="0.01" name="price" placeholder="Product
Price" required>
<select name="supplier_id">
<!-- Fetch
supplier options from DB -->
<?php
$result = $conn->query("SELECT
id, name FROM suppliers");
while ($row = $result->fetch_assoc())
{
echo "<option
value='" . $row['id'] . "'>" . $row['name'] . "</option>";
}
?>
</select>
<button type="submit">Add
Product</button>
</form>
List Products
To view the list of products (products/index.php).
<?php
include '../includes/db.php';
$result = $conn->query("SELECT p.*, s.name as
supplier_name FROM products p LEFT JOIN suppliers s ON p.supplier_id =
s.id");
while ($row = $result->fetch_assoc()) {
echo "<div>";
echo "<h2>"
. $row['name'] . "</h2>";
echo "<p>Price:
$" . $row['price'] . "</p>";
echo "<p>Supplier:
" . $row['supplier_name'] . "</p>";
echo "<a
href='edit.php?id=" . $row['id'] . "'>Edit</a>";
echo "</div>";
}
?>
7. Stock Management
Update Stock Levels
In the stock/update.php, create a form to update the stock
levels of products.
<?php
include '../includes/db.php';
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$product_id = $_POST['product_id'];
$quantity = $_POST['quantity'];
$sql = "UPDATE
stock_levels SET quantity = '$quantity' WHERE product_id = '$product_id'";
if ($conn->query($sql))
{
echo "Stock
updated successfully!";
} else {
echo "Error:
" . $conn->error;
}
}
?>
<form method="POST">
<select name="product_id">
<!-- Fetch
product options from DB -->
<?php
$result = $conn->query("SELECT
id, name FROM products");
while ($row = $result->fetch_assoc())
{
echo "<option
value='" . $row['id'] . "'>" . $row['name'] . "</option>";
}
?>
</select>
<input type="number"
name="quantity" placeholder="New Quantity" required>
<button type="submit">Update
Stock</button>
</form>
8. Orders Management
Place Order
Create a form for placing orders (orders/add.php).
<?php
include '../includes/db.php';
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$customer_name = $_POST['customer_name'];
$order_date = $_POST['order_date'];
$product_id = $_POST['product_id'];
$quantity = $_POST['quantity'];
$conn->begin_transaction();
try {
// Insert
order
$sql = "INSERT
INTO orders (customer_name, order_date) VALUES ('$customer_name', '$order_date')";
$conn->query($sql);
$order_id = $conn->insert_id;
// Insert
order items
$sql = "INSERT
INTO order_items (order_id, product_id, quantity) VALUES ('$order_id', '$product_id',
'$quantity')";
$conn->query($sql);
// Reduce
stock
$sql = "UPDATE
stock_levels SET quantity = quantity - '$quantity' WHERE product_id = '$product_id'";
$conn->query($sql);
$conn->commit();
echo "Order
placed successfully!";
} catch (Exception
$e) {
$conn->rollback();
echo "Error:
" . $e->getMessage();
}
}
?>
<form method="POST">
<input type="text"
name="customer_name" placeholder="Customer Name"
required>
<input type="date"
name="order_date" required>
<select name="product_id">
<!-- Fetch
product options from DB -->
<?php
$result = $conn->query("SELECT
id, name FROM products");
while ($row = $result->fetch_assoc())
{
echo "<option
value='" . $row['id'] . "'>" . $row['name'] . "</option>";
}
?>
</select>
<input type="number"
name="quantity" placeholder="Quantity" required>
<button type="submit">Place
Order</button>
</form>
9. Report Generation
You can create reports using SQL queries and display them in
a page (reports/index.php).
Generate a Sales Report
<?php
include '../includes/db.php';
$result = $conn->query("SELECT o.*, SUM(oi.quantity
* oi.price) AS total_sales
FROM orders o
JOIN order_items oi ON o.id = oi.order_id
GROUP BY o.id");
while ($row = $result->fetch_assoc()) {
echo "<div>";
echo "<h2>Order
ID: " . $row['id'] . "</h2>";
echo "<p>Customer:
" . $row['customer_name'] . "</p>";
echo "<p>Total
Sales: $" . $row['total_sales'] . "</p>";
echo "</div>";
}
?>
10. Styling with Bootstrap
Add Bootstrap for styling the pages. Include the
following in your header.php:
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
Summary
This Inventory Management System involves creating:
- A
product management system with CRUD functionalities.
- Stock
level management to track product inventory.
- Order
management for placing orders.
- Supplier
management to keep track of suppliers.
- Report
generation to analyze sales.
You can expand on this system by adding authentication, more
complex reports, and enhanced front-end features.
To develop an Inventory Management System using PHP
and MySQL, it’s important to follow a well-organized project structure. This
structure ensures that the code is clean, maintainable, and scalable as the
system grows. Below is an extended and detailed directory structure for the
project.
Full Project Structure
inventory-management-system/
│
├── config/
│ └── db.php # Database connection settings
│
├── public/
│ ├── css/
│ │ └── styles.css # Custom CSS styles
│ ├── js/
│ │ └──
scripts.js # Custom JavaScript
scripts (if needed)
│ └── index.php # Homepage (Dashboard)
│
├── includes/
│ ├──
header.php # HTML header with
meta tags, CSS includes, etc.
│ ├──
footer.php # HTML footer with
closing tags and Bootstrap JS includes
│ ├──
navbar.php # Navigation bar to
access different pages
│ └──
sidebar.php # Optional: A
sidebar for admin navigation
│
├── templates/
│ ├──
products/
│ │ ├── list.php #
Product listing page
│ │ ├── add.php # Form
to add a new product
│ │ ├── edit.php # Form
to edit an existing product
│ │ └── delete.php # Delete product confirmation page
│ │
│ ├── orders/
│ │ ├── list.php # Order
listing page
│ │ ├── add.php # Form
to add a new order
│ │ ├── details.php # View
detailed information of an order
│ │ └── report.php # Generate and display sales reports
│ │
│ ├──
suppliers/
│ │ ├── list.php #
Supplier listing page
│ │ ├── add.php # Form
to add a new supplier
│ │ ├── edit.php # Form
to edit supplier details
│ │ └── delete.php # Delete supplier confirmation page
│ │
│ ├── stock/
│ │ ├── list.php # Stock
level overview page
│ │ ├── update.php # Form
to update stock levels
│ │ └── report.php # Generate and display stock reports
│ │
│ └── reports/
│ ├──
sales.php # Sales report page
│ ├──
stock.php # Stock report page
│ └──
order.php # Order history report
page
│
├── controllers/
│ ├──
ProductController.php # Handle CRUD operations for products
│ ├──
OrderController.php # Handle
order-related operations
│ ├──
SupplierController.php# Handle supplier-related operations
│ └──
StockController.php # Handle
stock-related operations
│
├── models/
│ ├──
Product.php # Product model for
database interactions
│ ├──
Order.php # Order model for
database interactions
│ ├──
Supplier.php # Supplier model
for database interactions
│ ├──
Stock.php # Stock model for
database interactions
│ └──
Report.php # Report model for
generating reports
│
├── assets/
│ ├── images/
│ │ └── product-images/ # Folder for storing product images
(optional)
│ └── uploads/ # General uploads (optional)
│
├── db/
│ ├──
create_tables.sql # SQL file for
creating database tables
│ ├──
dummy_data.sql # SQL file for
inserting dummy data (optional)
│ └──
backup.sql # Database backup
file
│
├── helpers/
│ ├──
functions.php # Helper functions
(common utility functions)
│ └──
validate.php # Form validation
functions
│
├── vendor/
# For composer dependencies if needed
│ └──
autoload.php # Autoloader for
third-party libraries (optional)
│
├── logs/
│ └── error.log # Log file for error logging
│
├── .htaccess
# Apache server configurations (if necessary)
├── composer.json
# PHP dependencies (optional, if using Composer)
├── README.md
# Project documentation and instructions
└── LICENSE
# Project license file
Detailed Explanation of the Structure:
1. config/
- Contains
the database connection settings.
- The db.php
file establishes a connection with the MySQL database.
2. public/
- index.php
is the homepage or dashboard where you can summarize key metrics (total
products, total sales, stock levels, etc.).
- css/:
Contains the stylesheets, including Bootstrap and custom styles.
- js/:
Contains any JavaScript code required for dynamic functionality.
3. includes/
- header.php:
Contains the meta tags and includes CSS files for the layout.
- footer.php:
Includes closing tags and JavaScript (e.g., Bootstrap JS).
- navbar.php:
The navigation menu to switch between pages.
- sidebar.php:
An optional sidebar for navigation (useful for admin dashboards).
4. templates/
- Contains
different folders for various entities (e.g., products, orders,
suppliers).
- products/:
Handles product CRUD operations with forms and product lists.
- orders/:
Manages customer orders and reports.
- suppliers/:
Manages suppliers, including adding, editing, and deleting suppliers.
- stock/:
Manages stock levels, including updating and viewing stock reports.
- reports/:
Contains pages to generate different types of reports (e.g., sales
reports).
5. controllers/
- Each
controller handles the business logic for a specific entity (e.g.,
products, orders, suppliers).
- ProductController.php:
Handles adding, editing, deleting, and viewing products.
- OrderController.php:
Handles the placement and processing of orders.
- SupplierController.php:
Manages supplier data.
- StockController.php:
Handles stock-related functions (updating stock, checking stock levels).
6. models/
- Each
model represents a database entity and handles database interactions.
- Product.php:
Handles product-related queries (e.g., adding, fetching, updating).
- Order.php:
Manages queries related to customer orders.
- Supplier.php:
Handles supplier-related queries.
- Stock.php:
Manages stock-related database operations.
- Report.php:
Generates sales and stock reports based on database data.
7. assets/
- images/:
Stores product images (optional).
- uploads/:
Handles any general uploads (e.g., CSV uploads for bulk product
importing).
8. db/
- create_tables.sql:
SQL file to create the database schema with tables such as products, orders,
suppliers, stock_levels, etc.
- dummy_data.sql:
Optional SQL file to insert dummy data for testing.
- backup.sql:
A backup of the database schema and data.
9. helpers/
- functions.php:
Contains helper functions like redirecting users, formatting dates, etc.
- validate.php:
Contains form validation functions (e.g., checking for empty fields,
validating email formats).
10. logs/
- error.log:
Logs any errors encountered in the system for debugging purposes.
11. vendor/ (optional)
- This
directory stores the third-party libraries if you're using Composer
to manage PHP dependencies.
12. .htaccess
- Contains
Apache server configuration for URL routing or security settings
(optional).
13. composer.json (optional)
- This
file lists PHP dependencies and libraries needed for the project (e.g.,
using a third-party reporting library).
14. README.md
- Documentation
about the project, how to set it up, and any special instructions for
running the system.
Database Structure:
The database consists of several tables for managing
products, orders, suppliers, and stock levels. Below is a simplified schema:
- products
CREATE TABLE products (
id INT
AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(255) NOT
NULL,
description TEXT,
price DECIMAL(10, 2),
supplier_id INT,
stock_level INT DEFAULT
0,
created_at TIMESTAMP
DEFAULT CURRENT_TIMESTAMP
);
- orders
CREATE TABLE orders (
id INT
AUTO_INCREMENT PRIMARY KEY,
customer_name VARCHAR(255),
total_sales DECIMAL(10,
2),
created_at TIMESTAMP
DEFAULT CURRENT_TIMESTAMP
);
- order_items
CREATE TABLE order_items (
id INT
AUTO_INCREMENT PRIMARY KEY,
order_id INT,
product_id INT,
quantity INT,
price DECIMAL(10, 2),
created_at TIMESTAMP
DEFAULT CURRENT_TIMESTAMP
);
- suppliers
CREATE TABLE suppliers (
id INT
AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(255),
contact_email VARCHAR(255),
contact_phone VARCHAR(20),
address TEXT,
created_at TIMESTAMP
DEFAULT CURRENT_TIMESTAMP
);
- stock_levels
CREATE TABLE stock_levels (
id INT
AUTO_INCREMENT PRIMARY KEY,
product_id INT,
quantity INT,
created_at TIMESTAMP
DEFAULT CURRENT_TIMESTAMP
);
This project structure and database schema provides a strong
foundation for building a fully functional Inventory Management System
in PHP.
Here is a list of all the files used in the Inventory Management System project, categorized based on their function within the directory structure:
1. config/
- db.php
- This file contains the database connection settings.
2. public/
- index.php
- The homepage or dashboard for the system.
CSS Directory (for stylesheets):
- styles.css
- Custom CSS for the system.
JavaScript Directory (for custom scripts):
- scripts.js
- Custom JavaScript for dynamic functionality (optional).
3. includes/
- header.php
- Contains the HTML <head> section, meta tags, and CSS includes.
- footer.php
- Contains the closing tags and JavaScript includes (e.g., Bootstrap JS).
- navbar.php
- The navigation bar with links to various sections (Products, Orders,
Suppliers, Reports, etc.).
- sidebar.php
- (Optional) Sidebar for admin navigation.
4. templates/
Products Directory:
- list.php
- Displays the list of products.
- add.php
- Form for adding a new product.
- edit.php
- Form for editing an existing product.
- delete.php
- Confirmation page for deleting a product.
Orders Directory:
- list.php
- Displays the list of orders.
- add.php
- Form for adding a new order.
- details.php
- Displays detailed information for a specific order.
- report.php
- Generates and displays sales reports.
Suppliers Directory:
- list.php
- Displays the list of suppliers.
- add.php
- Form for adding a new supplier.
- edit.php
- Form for editing supplier details.
- delete.php
- Confirmation page for deleting a supplier.
Stock Directory:
- list.php
- Displays an overview of stock levels.
- update.php
- Form for updating stock levels.
- report.php
- Generates and displays stock reports.
Reports Directory:
- sales.php
- Page to generate sales reports.
- stock.php
- Page to generate stock reports.
- order.php
- Page to generate order history reports.
5. controllers/
- ProductController.php
- Handles the logic for product CRUD operations.
- OrderController.php
- Handles the logic for managing orders.
- SupplierController.php
- Handles the logic for managing suppliers.
- StockController.php
- Handles the logic for stock management.
6. models/
- Product.php
- Represents the product model and handles database operations for
products.
- Order.php
- Represents the order model and handles database operations for orders.
- Supplier.php
- Represents the supplier model and handles database operations for
suppliers.
- Stock.php
- Represents the stock model and handles database operations for stock.
- Report.php
- Handles the logic for generating reports (sales, stock, and order
history).
7. assets/
Images Directory (Optional):
- product-images/
- Folder for storing product images.
Uploads Directory (Optional):
- uploads/
- For storing file uploads (if needed).
8. db/
- create_tables.sql
- SQL file for creating the database schema.
- dummy_data.sql
- SQL file for inserting dummy data (optional).
- backup.sql
- SQL file for backing up the database.
9. helpers/
- functions.php
- Contains common utility functions used across the system (e.g.,
redirecting users, date formatting).
- validate.php
- Contains form validation functions (e.g., checking for empty fields,
email validation).
10. logs/
- error.log
- A log file for recording system errors.
11. vendor/ (Optional if using Composer)
- autoload.php
- Autoloader for third-party libraries (automatically created by
Composer).
12. Root Directory Files:
- .htaccess
- Apache server configuration file for URL routing and security
(optional).
- composer.json
- PHP dependencies list (if using Composer).
- README.md
- Project documentation.
- LICENSE
- The project’s license file.
1. config/db.php
This file establishes a connection to the MySQL database.
<?php
$host = 'localhost';
$db_name = 'inventory_db';
$username = 'root';
$password = '';
try {
$conn = new PDO("mysql:host=$host;dbname=$db_name",
$username, $password);
// Set the PDO
error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE,
PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
echo "Connection
failed: " . $e->getMessage();
}
?>
2. public/index.php
The main entry point of the application, typically
displaying the dashboard.
<?php
session_start();
require '../config/db.php'; // Include database connection
require '../includes/header.php'; // Include header
require '../includes/navbar.php'; // Include navbar
?>
<div class="container">
<h1>Inventory
Management System Dashboard</h1>
<!-- You can display
summaries here -->
</div>
<?php require '../includes/footer.php'; // Include footer
?>
3. includes/header.php
Contains the HTML head section and linked stylesheets.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, initial-scale=1.0">
<link rel="stylesheet"
href="css/styles.css"> <!-- Link to your CSS file -->
<link rel="stylesheet"
href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
<title>Inventory Management System</title>
</head>
<body>
4. includes/footer.php
Contains closing HTML tags and scripts.
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.9.2/dist/umd/popper.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
</body>
</html>
5. controllers/ProductController.php
Handles CRUD operations for products.
<?php
require '../config/db.php';
class ProductController {
public function create($data)
{
global $conn;
$stmt = $conn->prepare("INSERT
INTO products (name, description, price, stock_level, supplier_id) VALUES (?,
?, ?, ?, ?)");
return $stmt->execute([$data['name'],
$data['description'], $data['price'], $data['stock_level'], $data['supplier_id']]);
}
public function read()
{
global $conn;
$stmt = $conn->prepare("SELECT
* FROM products");
$stmt->execute();
return $stmt->fetchAll(PDO::FETCH_ASSOC);
}
public function update($data)
{
global $conn;
$stmt = $conn->prepare("UPDATE
products SET name = ?, description = ?, price = ?, stock_level = ?, supplier_id
= ? WHERE id = ?");
return $stmt->execute([$data['name'],
$data['description'], $data['price'], $data['stock_level'], $data['supplier_id'],
$data['id']]);
}
public function delete($id)
{
global $conn;
$stmt = $conn->prepare("DELETE
FROM products WHERE id = ?");
return $stmt->execute([$id]);
}
}
?>
6. models/Product.php
Represents the product model for database interactions.
<?php
class Product {
public $id;
public $name;
public $description;
public $price;
public $stock_level;
public $supplier_id;
public function __construct($id,
$name, $description, $price, $stock_level, $supplier_id) {
$this->id =
$id;
$this->name
= $name;
$this->description
= $description;
$this->price
= $price;
$this->stock_level
= $stock_level;
$this->supplier_id
= $supplier_id;
}
}
?>
7. templates/products/list.php
Displays the list of products.
<?php
require '../../controllers/ProductController.php';
$productController = new ProductController();
$products = $productController->read();
?>
<div class="container">
<h2>Product List</h2>
<a href="add.php"
class="btn btn-primary">Add New Product</a>
<table class="table">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Description</th>
<th>Price</th>
<th>Stock
Level</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
<?php foreach
($products as $product): ?>
<tr>
<td><?php echo $product['id'];
?></td>
<td><?php echo $product['name']; ?></td>
<td><?php echo $product['description']; ?></td>
<td><?php echo $product['price']; ?></td>
<td><?php echo $product['stock_level']; ?></td>
<td>
<a href="edit.php?id=<?php echo $product['id']; ?>" class="btn
btn-warning">Edit</a>
<a href="delete.php?id=<?php echo $product['id']; ?>"
class="btn btn-danger">Delete</a>
</td>
</tr>
<?php endforeach;
?>
</tbody>
</table>
</div>
8. templates/products/add.php
Form for adding a new product.
<?php
require '../../controllers/ProductController.php';
$productController = new ProductController();
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$productController->create($_POST);
header('Location:
list.php');
}
?>
<div class="container">
<h2>Add New Product</h2>
<form method="POST">
<div class="form-group">
<label for="name">Product
Name:</label>
<input type="text"
class="form-control" name="name" required>
</div>
<div class="form-group">
<label for="description">Description:</label>
<textarea
class="form-control" name="description" required></textarea>
</div>
<div class="form-group">
<label for="price">Price:</label>
<input type="number"
step="0.01" class="form-control" name="price" required>
</div>
<div class="form-group">
<label for="stock_level">Stock
Level:</label>
<input type="number"
class="form-control" name="stock_level" required>
</div>
<div class="form-group">
<label for="supplier_id">Supplier
ID:</label>
<input type="number"
class="form-control" name="supplier_id" required>
</div>
<button type="submit"
class="btn btn-success">Add Product</button>
</form>
</div>
9. templates/products/edit.php
Form for editing an existing product.
php
Copy code
<?php
require '../../controllers/ProductController.php';
$productController = new ProductController();
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$productController->update($_POST);
header('Location:
list.php');
}
$product = $productController->read($_GET['id']);
?>
<div class="container">
<h2>Edit Product</h2>
<form method="POST">
<input type="hidden"
name="id" value="<?php echo $product['id']; ?>">
<div class="form-group">
<label for="name">Product
Name:</label>
<input type="text"
class="form-control" name="name" value="<?php echo
$product['name']; ?>" required>
</div>
<div class="form-group">
<label for="description">Description:</label>
<textarea
class="form-control" name="description" required><?php
echo $product['description']; ?></textarea>
</div>
<div class="form-group">
<label for="price">Price:</label>
<input type="number"
step="0.01" class="form-control" name="price" value="<?php
echo $product['price']; ?>" required>
</div>
<div class="form-group">
<label for="stock_level">Stock
Level:</label>
<input type="number"
class="form-control" name="stock_level" value="<?php
echo $product['stock_level']; ?>" required>
</div>
<div class="form-group">
<label for="supplier_id">Supplier
ID:</label>
<input type="number"
class="form-control" name="supplier_id" value="<?php
echo $product['supplier_id']; ?>" required>
</div>
<button type="submit"
class="btn btn-warning">Update Product</button>
</form>
</div>
10. templates/products/delete.php
Confirmation page for deleting a product.
<?php
require '../../controllers/ProductController.php';
$productController = new ProductController();
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$productController->delete($_POST['id']);
header('Location:
list.php');
}
$product = $productController->read($_GET['id']);
?>
<div class="container">
<h2>Delete Product</h2>
<p>Are you sure
you want to delete the product "<?php echo $product['name'];
?>"?</p>
<form method="POST">
<input type="hidden"
name="id" value="<?php echo $product['id']; ?>">
<button type="submit"
class="btn btn-danger">Delete</button>
<a href="list.php"
class="btn btn-secondary">Cancel</a>
</form>
</div>
11. SQL Scripts (db/create_tables.sql)
SQL script to create the necessary tables in your MySQL
database.
CREATE TABLE suppliers (
id INT AUTO_INCREMENT
PRIMARY KEY,
name VARCHAR(100),
contact_email VARCHAR(100),
phone VARCHAR(15),
address TEXT,
created_at TIMESTAMP
DEFAULT CURRENT_TIMESTAMP
);
CREATE TABLE products (
id INT
AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100),
description TEXT,
price DECIMAL(10, 2),
stock_level INT,
supplier_id INT,
created_at TIMESTAMP
DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY
(supplier_id) REFERENCES suppliers(id)
);
CREATE TABLE orders (
id INT AUTO_INCREMENT
PRIMARY KEY,
product_id INT,
quantity INT,
order_date TIMESTAMP
DEFAULT CURRENT_TIMESTAMP,
status ENUM('Pending',
'Completed', 'Cancelled'),
FOREIGN KEY
(product_id) REFERENCES products(id)
);
CREATE TABLE stock_levels (
id INT
AUTO_INCREMENT PRIMARY KEY,
product_id INT,
quantity INT,
created_at TIMESTAMP
DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY
(product_id) REFERENCES products(id)
);
12. assets/css/styles.css
Custom styles for the application.
css
Copy code
body {
padding: 20px;
}
.container {
margin-top: 20px;
}
.table {
margin-top: 20px;
}
13. assets/js/scripts.js
(Optional) Custom JavaScript functions.
javascript
Copy code
// Custom JavaScript can go here
14. README.md
Documentation for your project.
# Inventory Management System
## Overview
This is a PHP and MySQL-based Inventory Management System
that manages products, stock levels, orders, and suppliers. It includes
features for generating reports.
## Requirements
- PHP >= 7.4
- MySQL
- Apache/Nginx server
## Installation
1. Clone the repository.
2. Import `create_tables.sql` into your MySQL database.
3. Update the database configuration in `config/db.php`.
4. Run the application on your server.
## Features
- Manage Products
- Manage Orders
- Manage Suppliers