HTML with PHP & MySQL
By the end of this lesson you will be able to write a PHP page that reads products from a MySQL database and prints them as a clean, valid HTML table. You will escape every value correctly, share one header and footer across pages, and handle a form that posts back to PHP without opening the door to SQL injection or broken markup.
What you should know first: HTML Tables Fundamentals, HTML Forms Introduction and Cross-Site Scripting (XSS) Prevention. If PHP is new to you, read PHP Introduction and SELECT first. This lesson is the HTML side of the story; HTML Integration with PHP goes deeper later.
How PHP turns code into HTML
PHP runs on the server, the computer that hosts the website. When a browser asks for products.php, the server runs the PHP code, and the code prints text. That text is HTML. The browser only ever receives the finished HTML; it never sees a single line of PHP.
Think of a dhaba in Rohtak. You order from the menu, the cook works in the kitchen, and a plate arrives at your table. You see the food, not the recipe. View Source in your browser shows the plate: the final HTML.
| Step | Where it happens | What exists |
|---|---|---|
1. Browser requests /products.php?category=Tea | Network | A URL |
| 2. PHP runs, asks MySQL for rows | Server | PHP variables and arrays |
| 3. PHP prints HTML with the data inside | Server | A text response |
| 4. Browser parses and draws the page | Browser | The DOM |
This has an important result. Every HTML rule from this course still applies, because the browser judges only the output. A missing alt, an unclosed tag or a duplicate id is just as wrong when PHP printed it.
Step 1: a template with short echo tags
A PHP file can mix HTML and PHP. Anything outside <?php ... ?> is sent as it is. The short echo tag <?= $x ?> prints a value, and it always works in modern PHP.
Never print a value raw. Wrap it in htmlspecialchars(), which turns <, >, &, " and ' into entities (safe text codes such as <). Typing the full function name everywhere is tiring, so most projects define a tiny helper called e():
<?php
declare(strict_types=1);
function e(string|int|float|null $value): string
{
return htmlspecialchars((string) $value, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
}
function rupees(string|float $amount): string
{
return '₹' . number_format((float) $amount, 2);
}Save that as includes/helpers.php. declare(strict_types=1); makes PHP refuse to quietly convert wrong types, so a mistake shows up as an error instead of odd output. It must be the first statement in each file. ENT_QUOTES also escapes both kinds of quote, which matters inside attributes. It is already part of the default since PHP 8.1, but writing it keeps older servers safe too.
Now a first template, hello.php. The loop uses the colon form (foreach (...): and endforeach;), which reads better between HTML lines than curly braces:
<?php declare(strict_types=1);
require __DIR__ . '/includes/helpers.php';
$customer = 'Priya';
$items = ['Assam tea', 'Ginger biscuits', 'Rusk'];
?>
<h1>Namaste, <?= e($customer) ?></h1>
<p>You have <?= count($items) ?> items in your bag:</p>
<ul>
<?php foreach ($items as $item): ?>
<li><?= e($item) ?></li>
<?php endforeach; ?>
</ul>Run php hello.php in a terminal and you see the HTML the browser would get:
<h1>Namaste, Priya</h1> <p>You have 3 items in your bag:</p> <ul> <li>Assam tea</li> <li>Ginger biscuits</li> <li>Rusk</li> </ul>
Step 2: one header and footer for every page
Copying the same <head> into twenty files means twenty places to fix a mistake. Instead, keep the shared parts in their own files and pull them in with require. (include does the same but only warns if the file is missing, so require is the safer choice for layout parts.) include & require covers the details.
<!-- includes/header.php -->
<!DOCTYPE html>
<html lang="en-IN">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title><?= e($pageTitle) ?> | Rohtak Chai Store</title>
</head>
<body>
<header><a href="/">Rohtak Chai Store</a></header>
<main><!-- includes/footer.php -->
</main>
<footer>Open daily, 8 am to 9 pm</footer>
</body>
</html>The page sets $pageTitle before it requires the header, so every page gets its own unique <title>. __DIR__ is the folder of the current file, which keeps paths working wherever the script is called from. (The HTML comments on the first lines are only labels for this lesson; leave them out of your real files, because nothing may come before the doctype.)
Step 3: read products with PDO and prepared statements
First, the table. Use InnoDB and utf8mb4 so names with any character, including ₹, are stored correctly:
CREATE TABLE products (
id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(120) NOT NULL,
category VARCHAR(40) NOT NULL,
price DECIMAL(10,2) NOT NULL,
in_stock BOOLEAN NOT NULL DEFAULT TRUE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;(XAMPP ships MariaDB. Older MariaDB versions, such as the one in XAMPP, do not know the utf8mb4_0900_ai_ci collation; use utf8mb4_unicode_ci there.) Next, one connection function in includes/db.php. PDO (PHP Data Objects) is PHP's standard database layer:
<?php
declare(strict_types=1);
function db(): PDO
{
static $pdo = null;
if ($pdo === null) {
$pdo = new PDO(
'mysql:host=localhost;dbname=chai_shop;charset=utf8mb4',
'shop_user',
getenv('DB_PASSWORD') ?: '',
[
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false,
]
);
}
return $pdo;
}The password comes from an environment variable, not from the code. Exceptions mode stops the page on a database error instead of printing half a table. Now the page itself, products.php:
<?php declare(strict_types=1);
require __DIR__ . '/includes/helpers.php';
require __DIR__ . '/includes/db.php';
$category = $_GET['category'] ?? 'Tea';
if (!is_string($category)) {
$category = 'Tea';
}
$stmt = db()->prepare(
'SELECT name, price, in_stock FROM products WHERE category = ? ORDER BY price'
);
$stmt->execute([$category]);
$products = $stmt->fetchAll();
$pageTitle = $category . ' prices';
require __DIR__ . '/includes/header.php';
?>
<h1><?= e($pageTitle) ?></h1>
<?php if ($products === []): ?>
<p>No products found in <?= e($category) ?>.</p>
<?php else: ?>
<table>
<caption><?= count($products) ?> products</caption>
<thead>
<tr><th scope="col">Product</th><th scope="col">Price</th><th scope="col">Stock</th></tr>
</thead>
<tbody>
<?php foreach ($products as $p): ?>
<tr>
<td><?= e($p['name']) ?></td>
<td><?= rupees($p['price']) ?></td>
<td><?= $p['in_stock'] ? 'In stock' : 'Sold out' ?></td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
<?php endif; ?>
<?php require __DIR__ . '/includes/footer.php'; ?>The ? is a placeholder. The SQL text and the visitor's value travel to MySQL separately, so a value like Tea' OR '1'='1 is only ever compared as a name, never run as SQL. That is what makes a prepared statement safe from SQL injection. Placeholders replace values only; table and column names can never be placeholders. Requesting /products.php?category=Tea with four products in the table returns:
<!DOCTYPE html>
<html lang="en-IN">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Tea prices | Rohtak Chai Store</title>
</head>
<body>
<header><a href="/">Rohtak Chai Store</a></header>
<main>
<h1>Tea prices</h1>
<table>
<caption>3 products</caption>
<thead>
<tr><th scope="col">Product</th><th scope="col">Price</th><th scope="col">Stock</th></tr>
</thead>
<tbody>
<tr>
<td>Masala Chai Mix 200 g</td>
<td>₹150.00</td>
<td>In stock</td>
</tr>
<tr>
<td>Assam CTC Tea 250 g</td>
<td>₹180.00</td>
<td>In stock</td>
</tr>
<tr>
<td>Kashmiri Kahwa 100 g</td>
<td>₹349.00</td>
<td>In stock</td>
</tr>
</tbody>
</table>
</main>
<footer>Open daily, 8 am to 9 pm</footer>
</body>
</html>Try a hostile URL such as ?category=<b>Juice</b>. The heading comes out as <h1><b>Juice</b> prices</h1>, so the visitor sees the tags as plain text and nothing is injected.
PHP cannot run in our Try-it editor, but the HTML it produces can. Here is the same data as product cards, exactly as a PHP loop would print it. Change the markup and see why the output must be valid HTML.
<!DOCTYPE html>
<html lang="en-IN">
<head>
<meta charset="utf-8">
<title>Tea prices | Rohtak Chai Store</title>
<style>
body { font-family: system-ui, sans-serif; margin: 16px; }
.cards { list-style: none; padding: 0; display: grid; gap: 12px;
grid-template-columns: repeat(auto-fill, minmax(180px, 1fr)); }
.card { border: 1px solid #ccc; border-radius: 8px; padding: 12px; }
.card h2 { font-size: 1.05rem; margin: 0 0 6px; }
.price { font-weight: bold; }
.sold-out { color: #b00020; }
</style>
</head>
<body>
<main>
<h1>Tea prices</h1>
<ul class="cards">
<li class="card">
<h2>Masala Chai Mix 200 g</h2>
<p class="price">₹150.00</p>
<p>In stock</p>
</li>
<li class="card">
<h2>Assam CTC Tea 250 g</h2>
<p class="price">₹180.00</p>
<p>In stock</p>
</li>
<li class="card">
<h2>Coorg Filter Coffee 500 g</h2>
<p class="price">₹299.00</p>
<p class="sold-out">Sold out</p>
</li>
</ul>
</main>
</body>
</html>Each card is an <li> inside one <ul>, so a screen reader announces "list, 3 items". In PHP, the <ul> sits outside the foreach and the <li> inside it.
Step 4: a form that posts back to PHP
A bulk-order form sends a name and a mobile number. The page validates on the server, shows errors next to the fields, keeps what the visitor typed (a sticky form), and saves good data with a prepared INSERT:
<?php declare(strict_types=1);
require __DIR__ . '/includes/helpers.php';
require __DIR__ . '/includes/db.php';
$name = trim((string) ($_POST['name'] ?? ''));
$phone = trim((string) ($_POST['phone'] ?? ''));
$errors = [];
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
if ($name === '') {
$errors['name'] = 'Please enter your name.';
}
if (!preg_match('/^[6-9][0-9]{9}$/', $phone)) {
$errors['phone'] = 'Enter a 10-digit mobile number.';
}
if ($errors === []) {
$stmt = db()->prepare('INSERT INTO enquiries (name, phone) VALUES (?, ?)');
$stmt->execute([$name, $phone]);
header('Location: /thanks.php', true, 303);
exit;
}
}
$pageTitle = 'Bulk order enquiry';
require __DIR__ . '/includes/header.php';
?>
<h1><?= e($pageTitle) ?></h1>
<form method="post" action="/enquiry.php">
<p>
<label for="name">Your name</label>
<input id="name" name="name" value="<?= e($name) ?>" autocomplete="name" required>
<?php if (isset($errors['name'])): ?>
<span class="error"><?= e($errors['name']) ?></span>
<?php endif; ?>
</p>
<p>
<label for="phone">Mobile number</label>
<input id="phone" name="phone" type="tel" value="<?= e($phone) ?>" autocomplete="tel" required>
<?php if (isset($errors['phone'])): ?>
<span class="error"><?= e($errors['phone']) ?></span>
<?php endif; ?>
</p>
<button type="submit">Send enquiry</button>
</form>
<?php require __DIR__ . '/includes/footer.php'; ?>Posting the name Kabir "KK" Singh with the phone 12345 (sent from a terminal, which skips the browser's own checks) gives this form back:
<form method="post" action="/enquiry.php">
<p>
<label for="name">Your name</label>
<input id="name" name="name" value="Kabir "KK" Singh" autocomplete="name" required>
</p>
<p>
<label for="phone">Mobile number</label>
<input id="phone" name="phone" type="tel" value="12345" autocomplete="tel" required>
<span class="error">Enter a 10-digit mobile number.</span>
</p>
<button type="submit">Send enquiry</button>
</form>The quotes became ", so the value attribute stays whole. On success the page answers with a 303 See Other redirect. This pattern is called Post/Redirect/Get: refreshing the thank-you page does not send the form twice. Browser validation (required) helps honest visitors, but the server check is the one that counts. A real form also needs a CSRF token, covered in Secure Form Handling and CRUD with Prepared Statements.
Escaping by context
htmlspecialchars() is right for text and quoted attribute values. Other places need other tools. The example below shows what goes wrong without escaping: it is the raw, unescaped output that a careless template would send.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Raw vs escaped output</title>
<style>
body { font-family: system-ui, sans-serif; margin: 16px; }
section { border: 1px solid #ccc; padding: 8px 12px; margin-bottom: 12px; }
input { width: 18rem; }
</style>
</head>
<body>
<section>
<h2>Printed raw</h2>
<p>Review by Meera: Best tea <b>ever</b>!!</p>
<label for="raw">Name</label>
<input id="raw" value="Kabir "KK" Singh">
</section>
<section>
<h2>Printed with htmlspecialchars()</h2>
<p>Review by Meera: Best tea <b>ever</b>!!</p>
<label for="safe">Name</label>
<input id="safe" value="Kabir "KK" Singh">
</section>
</body>
</html>In the raw version the visitor's <b> became real markup, and the input shows only Kabir because the first " ended the attribute. If a harmless tag can get in, so can a <script>. The escaped version shows exactly what was typed.
| Where the value goes | What to use |
|---|---|
| Text between tags | htmlspecialchars() (your e() helper) |
| A quoted attribute value | htmlspecialchars(), and always quote the attribute |
| Part of a URL query | rawurlencode() first, then e() on the whole URL |
Inside a <script> | json_encode() with JSON_HEX_TAG, or better, a data-* attribute |
| A full URL from a user | Allow only https: and http: schemes, then e() |
Common mistakes
- Escaping on input instead of output. Store the original text in the database and escape at the moment you print it, for the context you print it in.
- Unquoted attributes.
value=<?= e($x) ?>breaks at the first space. Always write the quotes. - Text before the doctype. A PHP warning or a stray blank line printed before
<!DOCTYPE html>can push the page into quirks mode, as you saw in DOCTYPE Declaration. <li>outside the loop's list. Put the<ul>or<table>outside theforeachand only the repeating row inside.- Showing database errors to visitors. Log the details on the server and show a friendly message.
Interview questions
1. Why does htmlspecialchars() matter if the data comes from your own database?
The database may hold text that users typed, such as names and reviews, so it is still untrusted. Escaping on output turns characters like < and " into entities, so the browser shows them as text instead of treating them as markup. This prevents stored XSS and also keeps the HTML valid.
2. How does a prepared statement prevent SQL injection?
The SQL text with placeholders is sent to the database first, and the values are sent separately with execute(). The database treats each value only as data, never as part of the query's structure. With PDO::ATTR_EMULATE_PREPARES set to false, PDO uses real server-side prepared statements.
3. What is the difference between include and require?
Both insert and run another PHP file. If the file is missing, include gives a warning and continues, while require stops with a fatal error. Layout parts and configuration should use require (or require_once), because a page without its header is broken anyway.
4. What is the Post/Redirect/Get pattern?
After a successful POST, the server redirects (usually with 303) to a GET page such as a thank-you page. Refreshing that page repeats only the GET, so the form is not submitted twice. It prevents duplicate orders and the browser's "resubmit form" warning.
5. Why put declare(strict_types=1) at the top of PHP files?
It makes scalar type declarations strict for calls made from that file, so passing a string where an int is expected throws a TypeError instead of converting silently. Bugs show up early and clearly. It must be the very first statement in the file.
Key points
- PHP runs on the server and prints HTML; the browser only sees the output, so all HTML rules still apply.
- Print every dynamic value with
<?= e($value) ?>, a helper aroundhtmlspecialchars()withENT_QUOTESand UTF-8. - Share the
<head>, header and footer withrequire, and let each page set its own$pageTitle. - Use PDO with exceptions,
utf8mb4and prepared statements; placeholders keep visitor input out of the SQL. - Validate forms on the server, keep sticky values escaped, and redirect after a successful POST.
- Escape for the context: HTML text, attribute, URL and script each need the right tool.
Exercise
Build search.php for the chai store. It shows a GET form with a <label>led search box named q, keeps the typed text in the box, and lists matching products as cards (<ul> of <li>) with name and price. Use a prepared statement with LIKE, show "No products match" when nothing is found, and make sure a search for "<i>chai</i>" is displayed as plain text in both the box and the message.
Show solution
<?php declare(strict_types=1);
require __DIR__ . '/includes/helpers.php';
require __DIR__ . '/includes/db.php';
$q = $_GET['q'] ?? '';
$q = is_string($q) ? trim($q) : '';
$products = [];
if ($q !== '') {
$stmt = db()->prepare('SELECT name, price FROM products WHERE name LIKE ? ORDER BY name');
$stmt->execute(['%' . $q . '%']);
$products = $stmt->fetchAll();
}
$pageTitle = 'Search';
require __DIR__ . '/includes/header.php';
?>
<h1>Search products</h1>
<form method="get" action="/search.php" role="search">
<label for="q">Product name</label>
<input id="q" name="q" type="search" value="<?= e($q) ?>">
<button type="submit">Search</button>
</form>
<?php if ($q !== '' && $products === []): ?>
<p>No products match "<?= e($q) ?>".</p>
<?php elseif ($products !== []): ?>
<ul class="cards">
<?php foreach ($products as $p): ?>
<li class="card"><h2><?= e($p['name']) ?></h2><p><?= rupees($p['price']) ?></p></li>
<?php endforeach; ?>
</ul>
<?php endif; ?>
<?php require __DIR__ . '/includes/footer.php'; ?>The % wildcards are added to the value, not to the SQL text, so the placeholder still protects the query. Both the input value and the "no match" message go through e(), so <i> appears as text. (A % or _ typed by the visitor still acts as a wildcard; escape them too if that matters.)
Quick Quiz
1. What does the browser receive when it requests a PHP page?
PHP runs on the server; the browser gets only the output.
2. Which line safely prints a visitor's name inside an attribute?
The value must be escaped and the attribute must be quoted.
3. In $stmt = $pdo->prepare('SELECT * FROM products WHERE category = ?'), what is the ??
Placeholders keep values apart from the SQL text, which blocks injection.
4. Why redirect with 303 after a successful form POST?
This is the Post/Redirect/Get pattern.
Learn HTML with a mentor
Free lessons get you started. Our Full Stack Web Development training adds real projects and code reviews from working developers.
- Project-based learning
- Mentor code reviews
- Free counselling call
