A structured, beginner-friendly guide covering procedural PHP and MySQLi from the ground up — no frameworks, no magic, just clear fundamentals.
// Chapter 01
Introduction to PHP
PHP is a server-side scripting language designed for web development. It powers over 75% of all websites that use a server-side language, including WordPress, Facebook (historically), and Wikipedia.
What Is PHP?
PHP (recursive: PHP: Hypertext Preprocessor) is an open-source, general-purpose scripting language especially suited for web development. It runs on the server and generates HTML that is sent to the browser.
Feature
Detail
Type
Interpreted, server-side scripting language
File Extension
.php
Current Version
PHP 8.x
License
Open Source (PHP License)
Runs On
Linux, Windows, macOS
How PHP Works — The Client-Server Model
Understanding this cycle is critical for every PHP developer:
User types a URL into the browser and presses Enter.
Browser sends an HTTP request to the web server.
Web server detects a .php file and passes it to the PHP interpreter.
PHP executes the code — connects to databases, processes logic, etc.
PHP returns pure HTML to the web server.
Web server sends the HTML response to the browser.
Browser renders the page. The user sees no PHP code, ever.
Key Insight
PHP code lives on the server. The browser only ever receives the final HTML output. This is why PHP is called a "server-side" language.
// Chapter 02
Environment Setup
To run PHP on your local machine, you need a web server (Apache), PHP interpreter, and MySQL database. All-in-one packages make this trivial.
Recommended Tools
Tool
OS
Link
XAMPPRecommended
Windows, macOS, Linux
apachefriends.org
WAMP
Windows
wampserver.com
LAMP
Linux
Built-in packages
Laragon
Windows
laragon.org
XAMPP Quick Start
Download XAMPP from apachefriends.org and install it.
Open the XAMPP Control Panel and start Apache and MySQL.
Navigate to C:\xampp\htdocs\ (Windows) or /opt/lampp/htdocs/ (Linux).
Create a folder, e.g. myphpapp, and place your .php files there.
Open a browser and visit http://localhost/myphpapp/index.php.
Your First PHP File
PHP<!-- File: htdocs/myphpapp/index.php --><?php// This is your first PHP scriptecho"<h1>Hello, PHP World!</h1>";
echo"<p>PHP version: " . phpversion() . "</p>";
?>
// Chapter 03
PHP Basics
The building blocks: syntax, variables, data types, operators, and control structures.
Syntax and Structure
PHP code is embedded inside <?php ... ?> tags. Every statement ends with a semicolon ;.
PHP<?php// Single-line comment/* Multi-line
comment */echo"This prints text to the page."; // semicolon requiredprint"print also outputs text.";
// Mixing PHP with HTML?><p>This is plain HTML.</p><?phpecho"Back in PHP.";
?>
Variables and Data Types
Variables start with $. PHP is loosely typed — you don't declare types.
Run these SQL commands in phpMyAdmin, or execute them via PHP:
SQL-- Run in phpMyAdmin or via PHP
CREATE DATABASE IF NOT EXISTS school_db;
USE school_db;
CREATE TABLE IF NOT EXISTS students (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100) NOT NULL,
email VARCHAR(150) NOT NULL UNIQUE,
course VARCHAR(100),
created_at DATETIME DEFAULT CURRENT_TIMESTAMP
);
// Chapter 07
CRUD Operations
Create, Read, Update, Delete — the four fundamental database operations.
⚠️ Educational Note — SQL Injection Risk
The examples below insert variables directly into SQL strings. This is intentionally simple for learning purposes. In a real production application, you must use prepared statements or strictly sanitize all input. See the Security chapter at the end of this guide for full details.
INSERT — Add a New Record
PHP<?phpinclude"db_connect.php";
// Data to insert (from a form, for example)$name = "Alice Johnson";
$email = "alice@example.com";
$course = "Computer Science";
// Build the SQL query string$sql = "INSERT INTO students (name, email, course)
VALUES ('$name', '$email', '$course')";
// Execute queryif (mysqli_query($conn, $sql)) {
$newId = mysqli_insert_id($conn); // get ID of inserted rowecho"Student added! ID = $newId";
} else {
echo"Error: " . mysqli_error($conn);
}
mysqli_close($conn);
?>
SELECT — Read Records
PHP<?phpinclude"db_connect.php";
// Select all students$sql = "SELECT * FROM students ORDER BY id DESC";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
echo"<table border='1'>";
echo"<tr><th>ID</th><th>Name</th><th>Email</th><th>Course</th></tr>";
// Fetch each row as an associative arraywhile ($row = mysqli_fetch_assoc($result)) {
echo"<tr>";
echo"<td>" . $row["id"] . "</td>";
echo"<td>" . $row["name"] . "</td>";
echo"<td>" . $row["email"] . "</td>";
echo"<td>" . $row["course"] . "</td>";
echo"</tr>";
}
echo"</table>";
} else {
echo"No students found.";
}
// Select a single student by ID$id = 1;
$sql = "SELECT * FROM students WHERE id = $id";
$result = mysqli_query($conn, $sql);
$row = mysqli_fetch_assoc($result);
echo"Name: " . $row["name"];
mysqli_close($conn);
?>
UPDATE — Modify a Record
PHP<?phpinclude"db_connect.php";
$id = 1;
$name = "Alice Smith";
$course = "Data Science";
$sql = "UPDATE students
SET name = '$name', course = '$course'
WHERE id = $id";
if (mysqli_query($conn, $sql)) {
$affected = mysqli_affected_rows($conn);
echo"Record updated. Rows affected: $affected";
} else {
echo"Update failed: " . mysqli_error($conn);
}
mysqli_close($conn);
?>
DELETE — Remove a Record
PHP<?phpinclude"db_connect.php";
$id = 1;
$sql = "DELETE FROM students WHERE id = $id";
if (mysqli_query($conn, $sql)) {
echo"Student deleted successfully.";
} else {
echo"Delete failed: " . mysqli_error($conn);
}
mysqli_close($conn);
?>
Key MySQLi Functions Reference
Function
Purpose
mysqli_connect()
Open a new connection to the MySQL server
mysqli_query()
Execute a query on the database
mysqli_fetch_assoc()
Fetch row as an associative array
mysqli_fetch_array()
Fetch row as both associative and numeric array
mysqli_num_rows()
Number of rows in a result set
mysqli_affected_rows()
Rows affected by last INSERT/UPDATE/DELETE
mysqli_insert_id()
Auto-generated ID of last INSERT
mysqli_error()
Error message for the last operation
mysqli_connect_error()
Error message for the connection attempt
mysqli_real_escape_string()
Escape special characters for use in SQL
mysqli_close()
Close the database connection
// Chapter 08
Sessions & Cookies
HTTP is stateless. Sessions and cookies allow PHP to "remember" users across multiple page requests.
Sessions
Sessions store data on the server. A session ID cookie is sent to the browser to identify the user.
PHP<?php// MUST call session_start() at the very top of every page that uses sessionssession_start();
// Store data in session$_SESSION["username"] = "Alice";
$_SESSION["user_id"] = 42;
$_SESSION["logged_in"] = true;
// Read session dataif (isset($_SESSION["logged_in"]) && $_SESSION["logged_in"]) {
echo"Welcome back, " . $_SESSION["username"] . "!";
} else {
echo"Please log in.";
}
// Delete a single session variableunset($_SESSION["username"]);
// Destroy entire session (logout)session_unset();
session_destroy();
echo"You have been logged out.";
?>
PHP<?phpinclude"db_connect.php";
$id = (int)$_GET["id"]; // cast to integer for safety// Handle UPDATEif ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = mysqli_real_escape_string($conn, trim($_POST["name"]));
$email = mysqli_real_escape_string($conn, trim($_POST["email"]));
$course = mysqli_real_escape_string($conn, trim($_POST["course"]));
$sql = "UPDATE students SET name='$name', email='$email',
course='$course' WHERE id=$id";
mysqli_query($conn, $sql);
header("Location: index.php");
exit();
}
// Fetch current data$result = mysqli_query($conn, "SELECT * FROM students WHERE id = $id");
$row = mysqli_fetch_assoc($result);
?>
<!DOCTYPE html>
<html><head><title>Edit Student</title></head><body>
<h2>Edit Student</h2>
<form method="post">
Name: <input type="text" name="name" value="<?= htmlspecialchars($row["name"]) ?>"><br>
Email: <input type="email" name="email" value="<?= htmlspecialchars($row["email"]) ?>"><br>
Course: <input type="text" name="course" value="<?= htmlspecialchars($row["course"]) ?>"><br>
<input type="submit" value="Save Changes">
<a href="index.php">Cancel</a>
</form>
</body></html>
delete_student.php
PHP<?phpinclude"db_connect.php";
$id = (int)$_GET["id"]; // integer cast prevents injectionmysqli_query($conn, "DELETE FROM students WHERE id = $id");
header("Location: index.php");
exit();
?>
// Chapter 11
Security Notes — SQL Injection & Best Practices
This is the most critical chapter. Please read it carefully before deploying any PHP application.
What is SQL Injection?
SQL Injection is an attack where a malicious user inserts SQL code into a form field or URL parameter, tricking your database into executing unintended commands.
⚠️ Dangerous Example — DO NOT USE IN PRODUCTION
The code below is intentionally vulnerable to illustrate the problem.
PHP — VULNERABLE ❌<?php// User enters: ' OR '1'='1 in the username field$username = $_POST["username"]; // NO sanitization!$sql = "SELECT * FROM users WHERE username = '$username'";
// Actual query becomes:
// SELECT * FROM users WHERE username = '' OR '1'='1'
// This returns ALL users — attacker is now logged in!?>
Defence Strategy 1: mysqli_real_escape_string()
This function escapes special characters before inserting them into a query. It is the minimum you should always do in this guide's style.
PHP — BETTER ✓<?php// Escape ALL user input before using in SQL$username = mysqli_real_escape_string($conn, $_POST["username"]);
$sql = "SELECT * FROM users WHERE username = '$username'";
?>
Defence Strategy 2: Integer Casting
For numeric IDs from URLs, always cast to integer:
PHP<?php// Safe — any non-integer becomes 0$id = (int)$_GET["id"];
$sql = "SELECT * FROM students WHERE id = $id";
?>
✅ Why Prepared Statements Are Better (Real-World Advice)
The examples in this guide use direct string interpolation for educational clarity. In a real production application, you should always use prepared statements with parameter binding. Prepared statements separate SQL code from data entirely — it's architecturally impossible for user data to be interpreted as SQL, regardless of what characters it contains. mysqli_real_escape_string() helps but has edge cases and relies on correct character encoding.