A beginner-friendly PHP learning guide with practical examples covering PHP fundamentals, forms, arrays, functions, sessions, password hashing, MySQL, MySQLi, phpMyAdmin, and database operations.
This repository is designed as a quick learning and revision resource for anyone getting started with PHP.
- Introduction to PHP
- Variables
- Operators
- GET & POST
- Math Functions
- If Statements
- Logical Operators
- Switch Statements
- For Loops
- While Loops
isset()- Arrays
- Associative Arrays
isset()andempty()- Radio Buttons
- Checkboxes
- Functions
- String Functions
- Sanitize & Validate
- Include Function
- Cookies
- Sessions
- Server Variables
- Hashing
- Connecting PHP to MySQL
- Creating a Table Using phpMyAdmin
- Insert Data into MySQL Using PHP
- Retrieve Data from MySQL
Basic PHP syntax:
<?php
// Body of code
?>echois used to display a message on the screen.<br>can be used to add a line break.//is used for a single-line comment./* */is used for a multiline comment.- PHP files can contain:
- HTML
- CSS
- JavaScript
- PHP
- In supported editors, typing
!and pressingTabcan generate HTML boilerplate code.
💻 Click Here to See the Code: View Code
A variable is a reusable container that stores data.
Variables can hold:
- String
- Integer
- Float
- Boolean
When a Boolean value is displayed:
trueis displayed as1falsedisplays nothing
Boolean values are commonly used inside:
- Conditional statements
- Loops
Use the escape sequence \ when you need to display a dollar sign inside a message involving variables.
💻 Click Here to See the Code: View Code
+
-
*
/
**
%
++
--
PHP evaluates operators in the following order:
()
**
* / %
+ -
💻 Click Here to See the Code: View Code
$_GET and $_POST are special variables used to collect data submitted through HTML forms.
Example:
<form action="some_file.php" method="get">With GET:
- Data is appended to the URL.
- It is not secure for sensitive information.
- There is a character limit.
- URLs can be bookmarked with their values.
- GET requests can be cached.
- GET is useful for search pages.
With POST:
- Data is packaged inside the body of the HTTP request.
- It is more secure than GET for sending data.
- There is no data limit mentioned in these notes.
- Requests cannot be bookmarked with submitted values.
- Requests are not cached.
- POST is better suited for submitting credentials.
💻 Click Here to See the Code: View Code
PHP provides several built-in mathematical functions.
| Function | Description |
|---|---|
abs($x) |
Returns the absolute value of $x |
round($x) |
Returns the rounded value |
floor($x) |
Rounds a value down |
ceil($x) |
Rounds a value up |
pow($x, $y) |
Returns $x raised to the power $y |
sqrt($x) |
Returns the square root |
max($x, $y, $z) |
Returns the maximum value |
min($x, $y, $z) |
Returns the minimum value |
pi() |
Returns the value of Pi |
rand() |
Returns a random value |
rand(min, max) |
Returns a random value between the given range |
💻 Click Here to See the Code: View Code
💻 Click Here to See the Code of Practice: View Code
An if statement executes code when a specified condition is true.
If the condition is false, the associated code is not executed.
- The order of
ifandelseconditions matters. - Conditional statements can work with Boolean variables.
💻 Click Here to See the Code: View Code
Logical operators are used to combine conditional statements.
There are three main logical operators.
| Operator | Symbol | Description |
|---|---|---|
| AND | && |
True when both conditions are true |
| OR | || |
True when at least one condition is true |
| NOT | ! |
Reverses the Boolean value |
true → false
false → true
💻 Click Here to See the Code: View Code
A switch statement can be used as an alternative to writing many elseif statements.
Benefits mentioned in the notes:
- Requires less code
- Can make multiple-condition logic easier to manage
💻 Click Here to See the Code: View Code
A for loop repeats a block of code a specified number of times.
It is useful when you already know approximately how many times the code should execute.
💻 Click Here to See the Code: View Code
A while loop also repeats code.
Its purpose is similar to a for loop, but its syntax and control structure are different.
The syntax is similar to loops commonly used in languages such as C++.
💻 Click Here to See the Code: View Code
isset() checks whether a variable exists and is not NULL.
Example:
isset($var)It returns:
trueif$varhas been declared and is notNULLfalseotherwise
You can check several variables at once:
isset($a, $b, $c)The function returns true only if all variables:
- Exist
- Are not
NULL
Example:
isset($_POST["stop"])This returns true only when:
- The
stopkey exists - Its value is not
NULL
isset() does not determine whether a value is empty or false-like.
Values such as:
0
""
false
are still considered set because they are not NULL.
Think of isset() as a:
Presence + non-null check
An array is a variable that can hold more than one value at a time.
Arrays can be declared using:
array()Adds one or more elements to the end of an array.
array_push($array, $value);Removes the last element.
array_pop($array);Removes the first element.
array_shift($array);Reverses the order of an array.
array_reverse($array);The returned array can be stored inside another variable and traversed using a foreach loop.
Returns the number of elements inside an array.
count($array);💻 Click Here to See the Code: View Code
An associative array stores information using:
key => value
Examples:
country => capital
id => username
item => price
Removes the last element.
array_pop($array);Removes the first element.
array_shift($array);Returns the keys of an associative array.
array_keys($array);Store the result in a variable and traverse it using a foreach loop.
Returns the values of an associative array.
array_values($array);Swaps keys and values.
array_flip($array);Changes the order of the array.
array_reverse($array);Returns the number of elements.
count($array);💻 Click Here to See the Code: View Code 💻 Click Here to See the Practice: View Code
Returns TRUE when a variable:
- Has been declared
- Is not
NULL
isset($variable);Returns TRUE when a variable is considered empty.
Examples mentioned in the notes include:
Not declared
false
NULL
""
Usage:
empty($variable);💻 Click Here to See the Code: View Code 💻 Click Here to See the Code of Login Form: View Code
When multiple radio buttons belong to the same group, their name attribute should be the same.
This allows the user to select only one option from that group.
💻 Click Here to See the Code: View Code
Basic checkbox syntax:
<input type="checkbox" name="" value="">To work with multiple checkbox values as an array, assign the same name and add [].
Example structure:
<input type="checkbox" name="items[]" value="">💻 Click Here to See the Code: View Code
Functions allow you to:
Write code once and reuse it whenever needed.
A function is invoked by writing its name followed by parentheses.
Example:
add();💻 Click Here to See the Code: View Code
PHP includes many built-in functions for manipulating strings.
| Function | Description |
|---|---|
strtolower($string) |
Converts letters to lowercase |
strtoupper($string) |
Converts letters to uppercase |
trim($string) |
Removes spaces before and after a string |
str_pad($string) |
Pads a string to a specified number of characters |
str_replace("-", "/", $string) |
Replaces - with / |
strrev($string) |
Reverses a string |
str_shuffle($string) |
Shuffles characters in a string |
strcmp($string1, $string2) |
Compares two strings |
strlen($string) |
Counts characters |
strpos($string, " ") |
Finds the position of a given argument |
substr(...) |
Creates part of a string |
explode(" ", $string) |
Converts a string into an array |
implode("Separator", $stringArray) |
Converts a string array into a normal string |
Example:
strcmp($string1, $string2);Possible results described in the notes:
0 → Strings are the same
1 → Different
-1 → Different
Example:
explode(" ", $string);This divides the string based on the supplied separator and returns an array.
Example:
implode("Separator", $stringArray);This joins array elements into a normal string.
💻 Click Here to See the Code: View Code
PHP provides filtering functions for user input.
Basic structure:
filter_input(method, input_name, filter_type);Sanitization is used to filter input.
FILTER_SANITIZE_SPECIAL_CHARSUsed for filtering special characters.
FILTER_SANITIZE_NUMBER_INTUsed with integer input.
FILTER_SANITIZE_EMAILUsed with email input.
Validation determines whether the supplied input follows the required format.
Invalid input may return false.
FILTER_VALIDATE_INTUsed to validate integer input.
FILTER_VALIDATE_EMAILUsed to validate an email format.
💻 Click Here to See the Code: View Code
The include() function allows content from another file to be included inside the current PHP file.
Example:
include("file.php");Files can include:
HTML
PHP
index.php
- Website sections become reusable.
- Changes only need to be made in one location.
- Duplicate code can be reduced.
💻 Click Here to See the Code: View Code
A cookie stores information about a user inside the user's web browser.
Cookies may be used for:
- Browsing preferences
- Targeted advertisements
- Other non-sensitive information
PHP uses the setcookie() function to create cookies.
Cookies can be accessed through the $_COOKIE superglobal.
setcookie(
"key",
"value",
expiration_time,
file_path
);Expiration time can be calculated using:
time()Cookies can usually be inspected through browser developer tools.
Typical process:
Right Click
↓
Inspect
↓
Application
↓
Storage
↓
Cookies
You can also open developer tools using:
F12
and navigate to the Application section.
The expiration time can be changed to expire a cookie.
Cookies can be accessed using:
$_COOKIEThe values can also be traversed as:
$key => $value
using a foreach loop.
💻 Click Here to See the Code: View Code
A session is used to store information about a user across multiple pages.
For example:
User Login
↓
Session Created
↓
Session ID Assigned
↓
User moves between pages
↓
User remains logged in
A common example is remaining logged into a website while navigating between different pages.
session_start();$_SESSIONIt can be used to store session information such as user credentials.
header("Location: filename.php");session_destroy();This can be used when a user logs out.
💻 Click Here to See the Code: View Code
$_SERVER is a PHP superglobal containing information related to:
- Headers
- Paths
- Script locations
- Web server environment
It behaves like an associative array.
Example:
$_SERVER[]$_SERVER["PHP_SELF"]Represents the location of the current PHP page.
When used inside a form action, it can automatically reflect the current filename.
The notes recommend enclosing it with htmlspecialchars() to help avoid cross-site scripting issues.
$_SERVER["REQUEST_METHOD"]This can be used to determine whether the current request uses:
GET
or:
POST
By default, a page request is GET.
After a form configured with the POST method is submitted, the request method becomes POST.
💻 Click Here to See the Code: View Code
Hashing transforms sensitive information, such as passwords, into a different representation consisting of letters, numbers, and symbols through a mathematical process.
Hashing is technically different from encryption.
It can be used to help prevent the original password from being directly exposed.
Use:
password_hash($string, PASSWORD_DEFAULT);First parameter
The original string or password.
$stringSecond parameter
The hashing algorithm or algorithm-related constant.
PASSWORD_DEFAULTUsed to compare a plain-text password against its stored hash.
password_verify();It returns either:
true
or:
false
depending on whether the password matches.
💻 Click Here to See the Code: View Code
There are two commonly used approaches mentioned in the notes:
- MySQLi Extension
- PDO — PHP Data Objects
For this beginner course, the notes use MySQLi.
When using XAMPP, phpMyAdmin can typically be accessed from:
localhost/phpmyadmin
It can also be opened through the Admin option in the XAMPP Control Panel.
Used to connect PHP with the database.
mysqli_connect(
$db_server,
$db_user,
$db_password,
$db_name
);$db_server
$db_user
$db_password
$db_nameThe connection file can be included inside another PHP file.
include("Connection Filename.php");This avoids rewriting the connection logic.
💻 Click Here to See the Code: View Code
phpMyAdmin provides a graphical interface for creating and managing MySQL databases and tables.
Follow these steps to create a table, configure its columns, insert data manually, and manage records.
- Start Apache and MySQL from the XAMPP Control Panel.
- Open your browser.
- Navigate to:
http://localhost/phpmyadmin/
- phpMyAdmin will open in your browser.
-
Click Databases from the top navigation bar.
-
If you already have a database, select it.
-
If you do not have one:
- Enter a database name.
- Click Create.
- Select the newly created database.
phpMyAdmin
↓
Databases
↓
Create / Select Database
After selecting the database:
- Enter the table name.
- Specify the number of columns required.
- Click Create.
Example:
Table Name: users
Number of Columns: 5
phpMyAdmin will display a form where you can define each column.
In the Name field, enter the name of each column.
Example structure:
| Column | Type | Length | Index | A_I |
|---|---|---|---|---|
id |
INT |
— | PRIMARY |
✅ |
username |
VARCHAR |
— | — | — |
password |
CHAR |
255 |
— | — |
email |
VARCHAR |
— | — | — |
created_at |
DATETIME |
— | — | — |
For an ID column:
- Set the column name, for example:
id
- Set its type to:
INT
- Set the Index to:
PRIMARY
- Enable:
A_I
A_I stands for Auto Increment.
This automatically increases the ID whenever a new row is inserted.
Example:
1
2
3
4
5
...
Different types of data require different MySQL data types.
VARCHAR is used for storing characters or strings.
Examples:
username
email
name
address
Example:
VARCHAR
INT is used for storing integer numbers.
Examples:
id
age
quantity
Example:
INT
In this project, CHAR is used for storing the password after applying a hashing algorithm.
Example:
CHAR(255)
The length is set to:
255
DATETIME is used for storing both date and time.
Example:
DATETIME
For the default value, use:
CURRENT_TIMESTAMP
This can automatically store the current date and time when a new row is created.
Before creating the table:
- Click Preview SQL.
- phpMyAdmin will display the SQL query that will be executed.
This allows you to review the SQL statement before applying it.
Example structure:
CREATE TABLE users (
id INT PRIMARY KEY AUTO_INCREMENT,
username VARCHAR(255),
password CHAR(255),
email VARCHAR(255),
created_at DATETIME DEFAULT CURRENT_TIMESTAMP
);After configuring all columns:
- Review your settings.
- Click Save.
- phpMyAdmin will create the table.
The table will now appear under your selected database.
To view the newly created table:
- Select the table.
- Click Browse.
Initially, you will see the column names, but there may be no rows because no data has been inserted yet.
Example:
users
id | username | password | email | created_at
------------------------------------------------
To manually add a row:
- Select your table.
- Click Insert.
- Enter values for the required columns.
Example:
username: Zeeshan
password: example_password
email: zeeshan@example.com
- Click Go.
phpMyAdmin will execute the insertion query.
After inserting the data:
- Click Browse.
- The newly inserted row will now appear inside the table.
Example:
id | username | password | email | created_at
---------------------------------------------------------------------------
1 | Zeeshan | example_password | zeeshan@example.com | ...
To delete a record:
- Open the table.
- Click Browse.
- Locate the row you want to remove.
- Click Delete.
- Click OK to confirm.
The selected row will be removed from the table.
| Setting | Purpose |
|---|---|
PRIMARY |
Sets a column as the primary key |
A_I |
Enables Auto Increment |
VARCHAR |
Stores strings or character data |
INT |
Stores integer numbers |
CHAR |
Stores fixed-length character data |
DATETIME |
Stores date and time |
CURRENT_TIMESTAMP |
Uses the current date and time as the default value |
| Preview SQL | Displays the SQL query before execution |
| Browse | Displays records stored in the table |
| Insert | Adds a new record manually |
| Delete | Removes an existing record |
A simple structure can use two PHP files:
Connection File
+
Index File
The database connection logic is placed inside the connection file.
The index file can include it using:
include("connection.php");Used to close the database connection.
mysqli_close($connection);Used to submit an SQL query to the database.
mysqli_query($connection, $query);Parameters:
$connection → Database connection
$query → SQL query
💻 Click Here to See the Code: View Code
The SQL SELECT statement is used to retrieve data.
Example:
SELECT * FROM users WHERE user = 'Zeeshan';Used to check how many rows were returned by a query.
mysqli_num_rows($result);Used to retrieve the next row from a result as an associative array.
mysqli_fetch_assoc($result);A while loop can be used with:
mysqli_fetch_assoc($result);to process multiple rows.
Write SQL Query
↓
Execute Query
↓
Receive Result Object
↓
Fetch Row
↓
Process Data
For multiple rows:
SQL Query
↓
mysqli_query()
↓
$result
↓
while loop
↓
mysqli_fetch_assoc()
↓
Display each row
💻 Click Here to See the Code: View Code
PHP Syntax
Variables
Operators
Math Functions
if
else
elseif
switch
&&
||
!
for
while
foreach
array()
array_push()
array_pop()
array_shift()
array_reverse()
array_keys()
array_values()
array_flip()
count()
$_GET
$_POST
isset()
empty()
strtolower()
strtoupper()
trim()
str_pad()
str_replace()
strrev()
str_shuffle()
strcmp()
strlen()
strpos()
substr()
explode()
implode()
filter_input()
FILTER_SANITIZE_SPECIAL_CHARS
FILTER_SANITIZE_NUMBER_INT
FILTER_SANITIZE_EMAIL
FILTER_VALIDATE_INT
FILTER_VALIDATE_EMAIL
$_COOKIE
setcookie()
$_SESSION
session_start()
session_destroy()
$_SERVER
PHP_SELF
REQUEST_METHOD
password_hash()
password_verify()
mysqli_connect()
mysqli_query()
mysqli_num_rows()
mysqli_fetch_assoc()
mysqli_close()
PHP
HTML
MySQL
phpMyAdmin
XAMPP
The fastest way to learn PHP is not by memorizing syntax.
Build small programs, submit forms, manipulate arrays, work with sessions, connect databases, intentionally create errors, and debug them.
Practice each concept independently before combining everything into a complete project.
Click the box below to visit the author's GitHub profile and explore more projects, open-source work, and contributions.
Muhammad Zeeshan Islam 💻 📖 |