Structure a PHP project without a framework
A folder layout and a few habits that keep a growing PHP site tidy, secure and easy to maintain.
Design tables that avoid duplicated data: primary keys, foreign keys, one-to-many and many-to-many relationships.
Good design is decided before you write code. A poor design causes duplicated data, mistakes and slow queries that are hard to fix later.
Store each fact once. If a customer’s phone number is stored in 50 order rows, changing it means 50 updates, and one will be missed.
| order_id | customer_name | customer_phone | product | price |
|---|---|---|---|---|
| 1 | Ali | 0300… | Pen | 50 |
| 2 | Ali | 0300… | Book | 400 |
The customer details are repeated.
CREATE TABLE customers (
id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100) NOT NULL,
phone VARCHAR(30) NOT NULL
) ENGINE=InnoDB;
CREATE TABLE orders (
id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
customer_id INT UNSIGNED NOT NULL,
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (customer_id) REFERENCES customers(id)
) ENGINE=InnoDB;orders.customer_id).CREATE TABLE order_items (
order_id INT UNSIGNED NOT NULL,
product_id INT UNSIGNED NOT NULL,
quantity INT UNSIGNED NOT NULL DEFAULT 1,
unit_price DECIMAL(10,2) NOT NULL,
PRIMARY KEY (order_id, product_id),
FOREIGN KEY (order_id) REFERENCES orders(id) ON DELETE CASCADE,
FOREIGN KEY (product_id) REFERENCES products(id)
) ENGINE=InnoDB;Note unit_price is copied at the time of sale on purpose: later price changes must not rewrite old orders. Deliberate copies like this are fine; accidental ones are not.
INT, DATE, DECIMAL for money, never FLOAT).NOT NULL where a value is required, and UNIQUE where duplicates must be impossible.utf8mb4 for text.For reports and read-heavy pages, a copied or summary column can be faster. Do it deliberately, document it, and keep it updated, after you have measured a real problem.
A folder layout and a few habits that keep a growing PHP site tidy, secure and easy to maintain.
The layers that turn a basic login page into a hard target: password hashing, session settings, request checks, rate limiting and…