What is VIEW in MySQL?

A VIEW in MySQL is a virtual table. It does not store data itself (except in special cases). Instead, it stores an SQL query, and whenever you access the view, MySQL executes that query and returns the latest data.

Think of it like this:

  • Table = Stores actual data.
  • View = Stores only the SQL query.

Why use Views?

In real PHP projects, views are mainly used for:

  • Simplifying complex queries.
  • Improving code readability.
  • Restricting access to sensitive columns.
  • Reusing the same query across multiple pages.
  • Reporting and dashboards.

Example Project

Suppose you’re building an E-commerce website.

Customers Table
CREATE TABLE customers (
    id INT PRIMARY KEY AUTO_INCREMENT,
    name VARCHAR(100),
    email VARCHAR(100)
);
Orders Table
CREATE TABLE orders (
    id INT PRIMARY KEY AUTO_INCREMENT,
    customer_id INT,
    total DECIMAL(10,2),
    order_date DATE
);

Without View

Every time you need to run this JOIN query to get customer orders:

JOIN Query
SELECT
customers.id,
customers.name,
customers.email,
orders.total,
orders.order_date
FROM customers
JOIN orders
ON customers.id = orders.customer_id;

Imagine using this query on:

  • Dashboard
  • Admin Panel
  • Customer Profile
  • Reports
  • Invoice

You would repeat it everywhere.

Create A View
CREATE VIEW customer_orders AS

SELECT
customers.id,
customers.name,
customers.email,
orders.total,
orders.order_date

FROM customers

JOIN orders
ON customers.id = orders.customer_id;

Now the complex JOIN is stored inside the view.

Using View

Instead of writing the JOIN again:

Use View
SELECT * FROM customer_orders;

OR

SELECT *
FROM customer_orders
WHERE total > 1000;

Much simpler.

Using in PHP
$conn = new mysqli("localhost","root","","shop");

$sql = "SELECT * FROM customer_orders";

$result = $conn->query($sql);

while($row = $result->fetch_assoc())
{
    echo $row['name'];
    echo $row['total'];
}

Notice that PHP doesn’t care whether customer_orders is a table or a view.

Scroll to Top