Database design: keys, relationships and normalization
Design tables that avoid duplicated data: primary keys, foreign keys, one-to-many and many-to-many relationships.
Combine rows from two tables with INNER JOIN and LEFT JOIN.
CREATE TABLE customers (id INT PRIMARY KEY, name VARCHAR(50));
CREATE TABLE orders (id INT PRIMARY KEY, customer_id INT, total DECIMAL(8,2));
INSERT INTO customers VALUES (1,'Ali'),(2,'Sara'),(3,'Omar');
INSERT INTO orders VALUES (10,1,50.00),(11,1,20.00),(12,2,75.00);Ali has two orders, Sara has one, Omar has none.
SELECT c.name, o.total
FROM customers c
INNER JOIN orders o ON o.customer_id = c.id;Omar is missing, because he has no order.
SELECT c.name, o.total
FROM customers c
LEFT JOIN orders o ON o.customer_id = c.id;Omar appears with NULL for the total.
SELECT c.name
FROM customers c
LEFT JOIN orders o ON o.customer_id = c.id
WHERE o.id IS NULL;ON condition. Forgetting it makes every row match every row.c, o) and prefix every column with them.orders.customer_id) so joins stay fast.Design tables that avoid duplicated data: primary keys, foreign keys, one-to-many and many-to-many relationships.
A folder layout and a few habits that keep a growing PHP site tidy, secure and easy to maintain.