0% found this document useful (0 votes)
82 views

Backend Web Development

The document provides information about backend web development. It discusses that backend development is server-side development that involves databases, backend logic, APIs, and servers. It focuses on MySQL as a database and introduces concepts like tables, rows, columns, and how SQL is used to manage and query relational databases. It provides an outline of SQL topics like SELECT statements, WHERE clauses, JOINs, aggregation functions, and more.

Uploaded by

CpA TB
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
82 views

Backend Web Development

The document provides information about backend web development. It discusses that backend development is server-side development that involves databases, backend logic, APIs, and servers. It focuses on MySQL as a database and introduces concepts like tables, rows, columns, and how SQL is used to manage and query relational databases. It provides an outline of SQL topics like SELECT statements, WHERE clauses, JOINs, aggregation functions, and more.

Uploaded by

CpA TB
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 801

Backend Web

Development
What’s Backend Development?
Backend Development is also known as server-side development. It is
everything that the users don’t see and contains behind-the-scenes
activities that occur when performing any action on a website. It
forces primarily on databases, backend logic, APIs and Servers.
Outlines
● MySQL (Database)
● PHP
● Backend Project
MySQL (Database)
Outlines
● Introduction
● SQL SELECT( I )
● SQL SELECT( II )
● SQL JOINS
● SQL Database and Table
● SQL Insert, Update and Delete
● SQL Constraints
● SQL Additional Topics
Introdution
Introduction

● Introduction to SQL
Introduction to Databases and SQL

A database is an organized collection of data so that it can be easily accessed. To


manage these databases, Database Management Systems(DBMS) are used.

Types of DBMS

In general, there are two common types of databases:

● Non-Relational
● Relational
Non-Relational Database Management
System(Non-RDBMS)

In Non-RDBMS, data is stored in key-value pairs. For example -


Cont

Here, customers’ data are stored in key-value pairs.

Commonly used Non-RDBMS:

● MongoDB, Amazon DynamoDB, Redis, etc…


Relational Database Management System(RDBMS)

In RDBMS, data is stored in tabular format. For example,


Cont

Here, customers is a table inside the database.

The first row is the attributes of the table. Each row after that contains the data
of customer.

In RDBMS, tow or more tables may be related to each other. Hence the term

“Relational”. For example


Cont

Here, orders and customers are related through customer_id.

Commonly used RDBMS: MySQL, PostgreSQL, MSSQL, Oracle etc.

Note: To access data from these relational databases , SQL(Structured Query


Language) is used.
Introduction to SQL

Structured Query Language(SQL) is a standard query language that is used to


work with relational databases.
We use SQL to
● create databases
● create tables in a database
● read data from a table
● insert data in a table
● update data in a table
● delete data from a table
● delete database tables
● delete databases
● and many more database operations
SQL Example: Read Data From a Table

Here, this SQL command selects the first name and last name of all customers
from the customers table.
Cont

SQL is used in all relational databases such as MySQL, Oracle, MSSQL ,


PostgreSQL etc.

Note: The major SQL commands are similar in all relational databases. However,
in some cases, SQL commands may differ.
SQL SELECT(I)
SQL SELECT (I)

● SQL SELECT
● SQL AND, OR, NOT
● SQL SELECT DISTINCT
● SQL SELECT AS
● SQL LIMIT, TOP, FETCH FIRST
● SQL IN Operator
● SQL BETWEEN Operator
● SQL IS NULL and NOT NULL
● SQL MIN( ) and MAX( )
● SQL COUNT( )
● SQL SUM( ) and AVG( )
SQL SELECT
SQL SELECT

The SQL SELECT statement is used to select (retrieve) data from a database
table. For Example,

Here, the SQL command selects the first_name and last_name of all Customers.
SQL SELECT ALL

To select all columns from a database table, we use the * character. For example,

Here, the SQL command selects all columns of the Customers table.
SQL SELECT WHERE Clause

A SELECT statement can have an optional WHERE clause. The WHERE clause
allows us to fetch records from a database table that matches specified
condition(s). For example,

Here, the SQL command selects all customers from the Customers table with
last_name Doe.
Example - 2

Here, the SQL command fetches age and country fields of all customers whose
country is USA.
SQL Operators

The WHERE clause uses operators to construct conditions. Some of the


commonly used operators are -

● Equal to Operator( = )

This SQL command selects all customers from the Customers table having
first_name John
● Greater than( > )

This SQL command selects all customers from the Customers table having age
greater than 25
● AND Operator( AND )

This SQL command selects all customers from the Customers table having
last_name Doe and country USA.
SQL AND, OR and NOT
Operators
SQL AND, OR, and NOT Operators

The AND, OR, and NOT operators in SQL are used with the WHERE or HAVING
clauses.
SQL AND Operator

The SQL AND operator selects data if all conditions are TRUE. For example,

Here, the SQL command selects first_name and last_name of all customers where
the country is USA and last_name as Doe from the Customers table.
SQL OR Operator

The SQL OR Operator selects data if any one condition is TRUE. For example -

Here, the SQL command selects first_name and last_name of all customers where
the country is USA or if their last name is Doe from the Customers table.
SQL NOT Operator

The SQL NOT operator selects data if the given condition is FALSE. For example,

Here, the SQL command selects first_name and last_name of all customers where
the country is not USA from the Customers table.
Combining Multiple Operator

It is also possible to combine multiple AND , OR and NOT operators in an SQL


statement. For example,

Let’s suppose we want to select customers where the country is either USA or
UK and the age is less than 26.
Example - 2

Here, the SQL command selects all customers where the country is not USA and
last_name is not Doe from the Customers table.
SQL SELECT DISTINCT
Statement
SQL SELECT DISTINCT Statement

The SQL SELECT DISTINCT statement selects unique rows from a database
table. For example -
Here, the SQL command selects rows if the combination of country and
first_name is unique.
DISTINCT with COUNT

If we need to count the number of unique rows, we can use the COUNT( )
function with DISTINCT.

Here, the SQL command returns the count of unique countries.


SQL SELECT AS Alias
SQL AS Alias

The As keyword is used to give columns or tables a temporary name that can be
used to identify that column or table later. For example,

Here, the SQL command selects the first_name of Customers. However, its
column name will be name instead of first_name in the result set.
SQL As With More Than One Column

We can use aliases with more than one column. For example -

Here, the SQL command selects customer_id as cid and first_name as name.
SQL AS With Expression

We can combine data from multiple columns and represent data in a single
column using the CONCAT( ) function. For example -

Here, the SQL command selects first_name and last_name. And, the name of the
column will be full_name in the result set.
SQL LIMIT, TOP, FETCH
FIRST
SQL LIMIT, TOP and FETCH FIRST

The SELECT TOP command is used to select a fixed number of rows from a
database. For example,

Here, the SQL command selects the first 2 rows from the table.
For example
SQL LIMIT Clause

The LIMIT keyword is used with the following database systems:

1. MySQL
2. PostgreSQL
3. SQLite

Here, the SQL command selects the first 2 rows from the table.
SQL LIMIT With OFFSET Clause

The OFFSET keyword is used to specify starting rows from where to select rows.
For example,

Here, the SQL command selects 2 rows starting from the fourth row. OFFSET 3
means the first 3 rows are excluded.
SQL TOP Clause

The TOP keyword is used with the following database systems:

● SQL Server
● MS Access

Example,

Here, the SQL command selects first_name and last_name of the first 2 rows.
SQL FETCH FIRST Clause

The FETCH FIRST n ROWS ONLY clause is used with the Oracle database
system.

Example,

Here, the SQL command selects the first 2 rows from the table.
SQL IN
SQL IN Operator

The IN operator is used with the WHERE clause to match values in a list. For
example,

Here, the SQL command selects rows if the country is either USA or UK.
SQL IN Operator With Columns

The IN operator can also be used to select rows in which a certain value exists in
the given field. For example,

Here, the SQL command selects the rows if the USA value exists in the country
field.
SQL NOT IN Operator

The NOT IN operator returns is used to exclude the rows that match values in
the list. It returns all the rows except the excluded rows. For example,

Here, the SQL command selects rows if UK or UAE is not in the country column.
SQL IN Operator With Duplicate Values

By the way, the IN operator ignores duplicates values in the list. For example,

is equivalent to
SQL IN Operator With Subquery

Here, the SQL command

1. selects customer_id from Orders table


2. Selects rows from Customers table where customer_id is in the result set of
subquery.
SQL BETWEEN Operator
SQL BETWEEN Operator

The BETWEEN operator is used with the WHERE clause to match values in a
range. For example,

Here, the SQL command selects all orders have amounts between 300 and 500
including 300 and 500.
SQL NOT BETWEEN Operator

The NOT BETWEEN operator is used to exclude the rows that match values in
the range. It returns all the rows. For example,

Here, the SQL command selects all orders except the rows that
SQL IS NULL and IS NOT
NULL
SQL IS NULL and IS NOT NULL

The IS NULL condition is used to select rows if the specified field is NULL. For
example,

Here, the SQL command selects employees who do not have email.
IS NOT NULL

In SQL, IS NOT NULL condition is used to select rows if the specified field is NOT
NULL. For example,

Here, the SQL command selects employees who have emails.


IS NULL With COUNT( )

We can use the COUNT( ) function with IS NULL to count the number of rows
with an empty field. For example,

Here, the SQL command returns the total number of employees that do not have
email.
Similarly, we can use the COUNT( ) function with IS NOT NULL to count the
number of non-empty fields.
SQL MAX( ) and MIN( )
SQL MAX( ) and MIN( )

● The MAX( ) function returns the maximum value of a column.


● The MIN( ) function returns the minimum value of a column.
SQL MAX( ) Function

Here, the SQL command returns the largest value from the age column.
SQL MIN( ) Function

Here, the SQL command returns the smallest value from the age column.
Aliases with MAX( ) and MIN( )

It is also possible to give custom names to these fields using the AS keyword. For
example,

Here, the field name MAX( age ) is replaced with max_age in the result set.
MAX( ) and MIN( ) with String

The MAX( ) and MIN( ) functions also work with other data types such as text, not
just numbers. For example,

Here, the SQL command selects the minimum value of first_name based on the
dictionary order.
Select Row Containing Max/Min Value

If we need to select the entire row(s) containing max/min value, we can use the
nested SELECT statement in this way:

Here, the SQL command selects all the rows having the lowest age value.
SQL COUNT( )
SQL COUNT( )

The COUNT( ) function returns the number of rows in the result set. For
example,

Here, the SQL command count rows and returns the total number of rows of the
Customers table.
Aliases with COUNT( )

It is possible to give custom names to these fields using the AS keyword. For
example,

Here, the field name COUNT( * ) is replaced with total_numbers in the result set.
COUNT( ) With WHERE

Here, the SQL command returns the count of customers whose country is UK.
COUNT( ) with DISTINCT

If we need to count the number of unique rows, we can use the COUNT( )
function with the DISTINCT clause. For example,

Here, the SQL command returns the count of unique countries.


COUNT( ) with GROUP BY

The COUNT( ) function can be used with the GROUP BY clause to count the
rows with similar values. For example,

Here, the SQL command returns the number of customers in each country.
COUNT( ) With HAVING Clause

Here, the SQL command:

1. counts the number of rows by grouping them by country.


2. returns the result set if their count is greater than 1.
COUNT With NULL Values

1. SELECT COUNT( * ) returns the count of all records in the result set
regardless of NULL values.
2. SELECT COUNT( attribute ) returns the count of records containing
non-NULL values of the specified column.
SQL SUM( ) AND AVG( )
SQL SUM( ) AND AVG( )

In SQL, SUM( ) and AVG( ) functions are used to calculate total and average
values in numeric columns.
SQL SUM( ) Function

The SQL( ) function is used to calculate the sum of numeric values in a column.
For example,

Here, the SQL command returns the sum of amounts of all orders.
Example-

Here, the SQL command returns the total amount to be paid by the customer
having id 4.
SQL AVG( ) Function

The SQL AVG( ) function is used to calculate the average of numeric values in a
column. For example -

Here, the SQL command returns the average age of all customers.
Example -

Here, the SQL command returns the average spending of each customer.
SQL SELECT( II )
Outlines

● SQL ORDER BY
● SQL GROUP BY
● SQL LIKE
● SQL Wildcards
● SQL UNION
● SQL Subquery
● SQL ANY and ALL
● SQL CASE
● SQL HAVING
● SQL EXISTS
SQL ORDER BY
SQL ORDER BY Clause

The SQL ORDER BY clause is used to sort the result set in either ascending or
descending order. For example,

Here, the SQL command selects all customers and then sorts them in ascending
order by first_name.
ORDER BY ASC (Ascending Order)

We can use ASC keyword explicitly to sort selected records in ascending order.
For example,

Here, the SQL command selects all the customers and then sorts them in
ascending order by age.
ORDER BY DESC (Descending Order )

We use the DESC keyword to sort the selected records in descending order. For
example,

Here, the SQL command selects all the customers and then sorts them in
descending order by age.
ORDER BY With Multiple Columns

We can also use ORDER BY with multiple columns. For example -

Here, the SQL command selects all the records and then sorts them by
first_name. If the first_name repeats more than once, it sorts those records by
age.
ORDER BY With WHERE

We can also use ORDER BY with the SELECT WHERE clause. For example,

Here,
● The SQL command first selects last_name and age fields from the Customers
table if their country is not UK.
● Then, the selected records are sorted in descending order by their
last_name.
SQL GROUP By
SQL GROUP BY

In SQL, the GROUP BY clause is used to group by one or more columns. For
example,

Here, the SQL command groups the rows by the country column, and counts the
number of each country (because of the COUNT( ) function ).
Example - 2 : GROUP BY in SQL

Here, the SQL command sums the amount after grouping rows with customer_id.
GROUP BY HAVING Clause

We can use the GROUP BY clause with the HAVING clause to filter the result set
based on aggregate functions. For example,

Here, the SQL command:

1. counts the number of rows by grouping them by country.


2. returns the result set if their count is greater than 1
SQL LIKE
SQL LIKE and NOT LIKE Operators

SQL LIKE Operator

The LIKE operator in SQL is used with the WHERE clause to get a result set that
matches the given string pattern. For example -

Here, the SQL command selects customers whose country is UK.


Example 2: SQL LIKE With Wildcards

Here, the SQL command selects customers whose country name starts with U
and is followed by only one character.
SQL NOT LIKE Operator

We also invert the working of LIKE operator and ignore the result set matching
with the given string pattern by using the NOT operator. For example,

Here, the SQL command selects all customers except those, whose country is
USA.
SQL LIKE With Multiple Values

We can use the LIKE operator with multiple string patterns to select rows by
using with the OR operator. For example,

Here, the SQL command selects customers whose last_name starts with R and
end with t, or customers whose last_name ends with e.
SQL Wildcards
SQL Wildcards

A Wildcards character in SQL is used with the LIKE clause to replace a single or
set of character in any string. For example,

Here, %(means zero or more characters) is a wildcard character. Hence, the SQL
command selects customers whose last_name starts with R followed by zero or
more characters after it.
% Wildcard in SQL

The % wildcard in SQL is used to represent zero or more characters. For example,

Here, the SQL command selects customers whose last name starts with R
followed by zero or more characters.
_Wildcard in SQL

The _ wildcard in SQL is used to represent exactly one character in a string. For
example,

Here, the SQL command selects customers whose country name starts with U
and is followed by only one character.
[ ] Wildcard in SQL

The [ ] wildcard in SQL is used to represent any one character inside brackets. For
example -

Here, the SQL command selects customers whose country name starts with U
and is followed by either K or A. Any number of characters are allowed
afterwards.
! Wildcards in SQL

The ! wildcards in SQL is used to exclude characters from a string. For example,

Here, the SQL command selects customers whose last_name does not start with
D and R.
SQL UNION
SQL UNION

In SQL, the UNION operator selects rows from two or more tables.

If rows of tables are the same, those rows are only included once in the result
set. For example,

Here, the SQL command returns the age column from the Teachers table and
Students table, ignoring the duplicate rows.
Things to Note While Using UNION

To use UNION in SQL, we must always remember,

● Columns count in all tables must be the same. For example, Teachers and
Students both tables have three columns.
● The data type of columns must be the same. For example, the age column in
Teachers is integer, so is the age in Students table.
● The columns must be in the same order in each table. For example, the order
of columns is id-name-age in Teachers, so in the Students table.
SQL UNION ALL Operator

The UNION All operator selects rows from two or more tables similar to UNION.
However, unlike UNION, UNION ALL doesn’t ignore duplicate rows.

Here, the SQL command selects rows from both tables including duplicate rows.
SQL UNION Vs UNION ALL
SQL UNION Vs SQL UNION JOIN
SQL Subquery
SQL Subquery

In SQL, It’s possible to place a SQL query inside another query known as
subquery. For example,
In a subquery, the outer query’s result is dependent on the result-set of the inner
subquery. That’s subqueries are also called nested queries.

Here, the SQL command

● executes the subquery first; selects minimum age from the Customers table.
● executes the outer query; selects rows where age is equal to the result of
subquery.
Example 2: SQL Subquery

Here, the SQL command

● selects customer_id from Orders table


● select rows from Customers table where customer_id is in the result set of
subquery.
SQL ANY and ALL
SQL ANY

SQL ANY compares a value of the first table with all values of the second table
and return the row if there is a match with any value.

For example, if we want to find teachers whose age is similar to any of the
student’s age we can use
Compares the student age( returned by subquery) with the teacher’s age. If there
is any match, the corresponding row of the Teachers is selected.
SQL ALL

SQL ALL compares a value of the first table with all values of the second table
and returns the rows if there is a match with all values.

For example, if we want to find teachers whose age is greater than all students,
we can use
ANY and ALL with Comparison Operators

We can use any comparison operators like =, > , <, etc. with the ANY and ALL
keywords.

Here, the SQL command selects rows if age in the outer query is less than any
age in a subquery.
SQL CASE
SQL CASE

The CASE statement in SQL is used to check conditions and perform tasks on
each row while selecting data. For example,
Here, the SQL command checks each row with the given case,

If age is greater than or equal to 18, the result set contains

● columns with customer_id and first_name with their values


● Allowed is returned as a can_vote column.
Example 2: SQL CASE Statement

We want to provide a 10% discount on each order for a Christmas sale if the
amount is more than 400.

Here, the SQL command checks if amount is greater than or equal to 400. If this
condition is satisfied, a new column offer_price will contain the values that’s
equal to
amount - amount*10/100
Multiple Cases

It is also possible to stack multiple conditions inside the CASE clause.

Here, the result set will contain a column named country_name along with customer_id
and first_name columns.
The value of country_name will be United States of America if the country is equal to
USA.
Similarly, the value of country_name will be United Kingdom if the country is equal to
UK.
CASE With ELSE in SQL

A CASE statement can have an optional ELSE clause. The ELSE clause is executed if
none of the conditions in the CASE statement is matched. For example,

Here, the result set will contain a field named country_name along with customer_id
and first_name.
● United States of America if the country is USA
● United Kingdom if the country is UK
● Unknown Country if the country is neither USA nor UK(because the ELSE clause)
SQL HAVING
SQL HAVING

The HAVING clause in SQL is used if we need to filter the result set based on
aggregate functions such as MIN( ) and MAX( ), SUM( ) and AVG( ) and COUNT( ).

Here, the SQL command:

● counts the number of rows by grouping them by country


● returns the result set if their count is greater than 1.
SQL HAVING Vs WHERE
SQL EXISTS
SQL EXISTS

The SQL EXISTS operator executes the outer SQL query if the subquery is not
NULL (empty result-set). For example,
SQL NOT EXISTS

We can also use the NOT operator to inverse the working of EXISTS clause. The
SQL command executes if the subquery returns an empty result-set. For
example,

Here, the SQL command returns a row from the Customers table if the related
row is not the Orders table.
SQL JOIN
Outlines

● SQL JOIN
● SQL INNER JOIN
● SQL LEFT JOIN
● SQL RIGHT JOIN
● SQL FULL OUTER JOIN
SQL JOIN
SQL JOIN

The SQL JOIN joins two tables based on a common column, and selects records
that have matching values in these columns.
Cont

Here, the SQL command selects customer_id and first_name columns (from the
Customers table) and the amount column (from the Order table).

And, the result set will contain those rows where there is a match between
customer_id (of the Customers table) and customer( of the Orders table).
Types of SQL JOINs

The JOIN command we performed earlier is INNER JOIN. There are mainly four
types of joins.

● INNER JOIN( Same as JOIN)


● LEFT JOIN
● RIGHT JOIN
● FULL OUTER JOIN
SQL JOIN and Aliases

We can use AS aliases with table names to make our snippet short and clean. For
example,
SQL INNER JOIN
SQL INNER JOIN

The SQL INNER JOIN joins two tables based on a common column, and selects
records that have matching values in these columns.

For example,
Cont

Here, the SQL command selects customer_id and first_name columns (from the
Customers table) and the amount column(from the Orders table).

And, the result set will contain those rows where there is a match between
customer_id (of the Customers table) and customer( of the Orders table).
Syntax of INNER JOIN
INNER JOIN With WHERE Clause

Here, the SQL command joins two tables and selects rows where the amount is
greater than or equal to 500.
SQL INNER JOIN With AS Alias

We can use As aliases inside INNER JOIN to make out snippet short and clean.
For example,

Here, the SQL command selects common rows between Category and Products
table.
SQL INNER JOIN With Three Tables

We can also join more than two tables using the INNER JOIN. For example,
Here, the SQL command

● joins Customers and Orders table based on customer_id


● and joins Customers and Status table based on customer_id

The command returns those rows where there is a match between column values
in both join on customer_id.
SQL LEFT JOIN
SQL LEFT JOIN

The SQL LEFT JOIN joins two tables based on a common column and selects in
these columns and remaining rows from the left table.
Here, the SQL command selects customer_id and first_name columns (from the
Customers table) and the amount column(from the Orders table).

And, the results set will contain those rows where there is a match between
customer_id ( of the Customers table) and customer(of the Orders table) along
with all the remaining rows from the Customers table.
Syntax of LEFT JOIN
LEFT JOIN With WHERE Clause

The SQL command can have an optional WHERE clause with the LEFT JOIN
statement. For example,

Here , the SQL command joins two tables and selects rows where the amount is
greater than or equal to 500.
SQL LEFT JOIN With AS Alias

We can use AS alias inside LEFT JOIN to make our snippet short and clean. For
example,

Here, the SQL command selects common rows between Category and Products
table.
SQL RIGHT JOIN
SQL RIGHT JOIN

The SQL RIGHT JOIN joins two tables based on a common column, and selects
records that have matching values in these columns and remaining rows from the
right table.

For example,
Here, the SQL command selects customer_id and first_name columns(from the
Customers table) and the amount column(from the Orders tale).

And, the result set will contain those rows where there is a match between
customer_id (of the Customers table) along with all the remaining rows from the
Orders table.
Syntax of RIGHT JOIN
RIGHT JOIN With WHERE Clause

The SQL command can have an optional WHERE clause with the RIGHT JOIN
statement . For example,

Here, the SQL command joins two tables and selects rows where the amount is
greater than or equal to 500.
SQL RIGHT JOIN With AS Alias

We can use AS aliases inside RIGHT JOIN to make our snippet short and clean.
For example,

Here, the SQL command selects common rows between Category and Products
table.
SQL FULL OUTER JOIN
SQL FULL OUTER JOIN

The SQL FULL OUTER JOIN joins two tables based on a common column, and
selects records that have matching values in these columns and remaining rows
from both of the tables.

Example,
Here, the SQL command selects customer_id and first_name columns (from the
Customers table) and the amount column(from the Orders table).

And, the result set will contain those rows where there is a match between
customer_id(f the Customers table) and customer(of the Orders table) along with
all the remaining rows from both of the tables.
Syntax of FULL OUTER JOIN
FULL OUTER JOIN With WHERE Clause

The SQL command can have an optional WHERE clause with the FULL OUTER
JOIN statement. For example,

Here, the SQL command joins two tables and selects rows where the amount is
greater than or equal to 500.
SQL FULL OUTER JOIN With AS Alias

We can use AS aliases inside FULL OUTER JOIN to make out snippet short and
clean. For example,

Here, the SQL command selects common rows between Category and Products
table.
SQL DATABASE & TABLE
Outlines

● SQL Create Database


● SQL Create Table
● SQL Drop Database
● SQL Drop Table
● SQL Alter Table
● SQL Backup Database
SQL CREATE DATABASE
Statement
SQL CREATE DATABASE Statement

Before we can work with database tables, we must create a database first.

The CREATE DATABASE statement is used to create database tables. For


example,

Here, the SQL command creates a database named my_db.


CREATE DATABASE IF NOT EXISTS

If there is already a database with the same name , SQL will throw an error while
creating a database.

In such situations, we can use the CREATE DATABASE IF NOT EXISTS statement
to create a database only if there is no existing database with the same name. For
example,

Here, the SQL command creates a database named my_db only if there is no
existing database with the same name.
LIst all Databases

There could be multiple databases in a database management system. To show


the list of databases, we can run the following statement.

Here, the SQL command lists all the available databases in the DBMS.
Switch Databases

We have to work across multiple databases from time to time. To switch between
available databases, we can run the following statement.

This code selects the my_db database and all SQL operations will be performed
inside this database.
SQL CREATE TABLE
Statement
SQL CREATE TABLE Statement

A database table is used to store records(data). To create a database table, we


use the SQL CREATE TABLE statement. For example,
Here, the SQL command creates a database named companies. The table
contains column(field) id, name, address, email, and phone.

The int, varchar(50) and text are data types that tell what data could be stored in
that field. Some commonly used data types are as follows.
CREATE TABLE IF NOT EXISTS

While creating a table that already exists, throws an error. To fix this issue, we
can add the optional IF NOT EXISTS command while creating a table. For
example,

Here, the SQL command will only create a table if there is not one with a similar
name.
CREATE TABLE AS

We can also create a table using records from any other existing table using the
CREATE TABLE AS command. For example,

Here, the SQL command creates a table name USACustomers and copies the
records of the nested query in the new table.
SQL DROP DATABASE
Statement
SQL DROP DATABASE Statement

In SQL, DROP DATABASE is used to delete the database in our Database


Management System. For example,

Here, the SQL command will delete a database named my_db.

Also make sure you have admin or Drop permission to run this command.
List all Databases

To verify the drop database, we can run the following command to list the
available databases.

Here, the SQL command lists all the available databases in the DBMS.
SQL DROP TABLE
Statement
SQL DROP TABLE Statement

In SQL , DROP TABLE is used to delete the tables n our databases. For example,

Here, the SQL command will delete a table named my_table.

Also make sure you have admin or DROP permission to run this command.
DROP TABLE IF EXISTS

While dropping a table that does not exist, throws an error. To fix this issue, we
can add an optional IF EXISTS command while dropping a table. For example,

Here, the SQL command will only drop a table if there is one with a same name.
SQL ALTER TABLE
Statement
SQL ALTER TABLE Statement

We can change the structure of a table using the ALTER TABLE command. We
can

● Add a column
● Rename a column
● Modify a column
● Delete a column
● Rename a table
Add Column in a Table

We can add columns in table using the ALTER TABLE command with the ADD
clause. For example,

Here, the SQL command adds a column named phone in the Customers table.
Add Multiple Columns in a Table

We can also add multiple columns at once in a table. For example,

Here, the SQL command adds the phone and age column in the Customers table.
Rename Column in a Table

We can rename columns in a table using ALTER TABLE command with the
RENAME COLUMN clause. For example,

Here, the SQL command changes the column name of customer_id to c_id in the
Customers table.
Modify Column in a Table

We can also change the column’s data type using the ALTER TABLE command
with MODIFY or ALTER COLUMN clause. For example,
Drop Column in a Table

We can also drop(remove) columns in a table using the ALTER TABLE command
with the DROP clause. For example,

Here, the SQL command removes the phone column from the Customers table.
Rename a Table

We can change the name of a table using the ALTER TABLE command with the
RENAME clause. For example,

Here, the SQL command renames the Customers table to newCustomers.


SQL BACKUP DATABASE Statement

It is important to create database backups regularly so that out data won’t get
lost if the database gets corrupted.

In SQL, we can create database backups using the BACKUP DATABASE


statement. For example,

Here, the SQL command creates a backup file of the my_db database inside C
drive, named my_db_backup.bak.
Backup Only New Changes in SQL

In SQL, we can also backup only the new changes compared with previous
backup by using the WITH DIFFERENTIAL command. For example,

Here, the SQL command appends only new changes to the previous backup file.
Hence, this command may work faster.
Restore Database From Backup

To restore a backup file to the database management system, we can use the
RESTORE DATABASE statement. For example,

Here, the SQL command restores the my_db_backup.bak file in the database
named my_db.
SQL Insert, Update and
Delete
Outlines

● SQL Insert Into


● SQL Update
● SQL Select Into
● SQL Insert Into Select
● SQL Delete and Truncate Rows
SQL INSERT INTO
Statement
SQL INSERT INTO Statement

In SQL, the INSERT INTO statement is used to insert new row(s) in a database
table. For example,

Here, the SQL command inserts a new row in the Customers table with the given
values.
Insert Row Providing Value Explicitly

It’s possible to provide default values to a column(for example, auto


incrementing a column). In a database table, the ID field is usually unique auto
incremented.

In such case, we can omit the value for that column during row insertion. For
example,

Here, the SQL command automatically sets the new customer_id for the new row
and inserts it in a table.
Insert Multiple Rows at Once in SQL

It’s also possible to insert multiple rows to a database table at once. For example,

Here, the SQL command inserts three rows to the Customers table.
SQL UPDATE Statement
SQL UPDATE Statement

The SQL UPDATE statement is used to edit existing rows in a database table. For
example,

Here, the SQL command changes the value of the first_name column will be
Johnny if customer_id is equal to 1.
Update Multiple Values in a Row

We can also update multiple values in a row at once. For example,

Here, the SQL command changes the value of the first_name column to Johnny
and last_name to Depp if customer_id is equal to 1.
Update Multiple Rows

The UPDATE statement can update multiple rows at once. For example,

Here, the SQL command changes the value of the country column to NP if age is
22. If there are more than one rows with age equals to 22, all the matching rows
will be edited.
Update all Rows

We can update all the rows in a table at once by omitting the WHERE clause. For
example,

Here, the SQL command changes the value of the country column to NP for all
rows.
SQL SELECT INTO
Statement
SQL SELECT INTO Statement

In SQL, we can copy data from one database table to a new table using the
SELECT INTO command. For example,

Here, the SQL command copies all data from the Customers table to the new
CustomersCopy table.
Copy Selected Columns Only

We can also copy selected columns from the old table to a new table. For
example,

Here, the SQL command only copies customer_id and country columns to the
CustomersCopy table.
Copy Records Matching a Condition

We can use the WHERE clause with SELECT INTO to copy those rows that match
the specified condition. For example,

Here, the SQL command


● creates the USACustomersAge table with customer_id and age column
● copies the rows to the new table if the value of the country column is USA
Copy to Another Database

By default, SELECT INTO creates a new table in the current database. If we want
to copy data to a table in a different database, we can do that by using the IN
clause. For example,

Here, the SQL command copies the Customers table to the CustomersCopy
table in the another_db.mdb database
Copy From Two Tables to One

We can also copy records from two different tables to a new table using the
JOIN clause with SELECT INTO. For example,

Here, the SQL command copies customer_id and first_name from the Customers
table and the amount from the Orders table to a new table CustomerOrders.
Copy Table Schema Only

We can also use the SELECT INTO statement to create a new table with the
given schema(without coping the data). For that, we use the WHERE clause with
a condition that returns false.

Here, the SQL command creates an empty table named NewCustomers with the
same structure as the Customers table.
SQL Select Into Insert
SQL Select Into Insert

The INSERT INTO SELECT statement is used to copy records from one table to
another existing table. For example,

Here, the SQL command copies all records from the Customers to the
OldCustomers table.
Copy Selected Columns Only

We can also copy the selected columns from one table to another. For example,

Here, the SQL command only copies records from the customer_id column and
country column to be OldCustomers table.
Copy Records Matching a Condition

We can use the WHERE clause with INSERT INTO to copy those rows that match
the specified condition. For example,

Here, the SQL command copies rows that are the value f the country column as
USA.
Copy From two Tables to One

We can also copy records from two different tables using the JOIN clause with
INSERT INTO SELECT . For example,

Here, the SQL command copies customer_id and first_name from the Customers
table and the amount from the Orders table in an existing table
OldCustomerOrders.
Avoid Duplicates in INSERT INTO SELECT
If there is already a row with a similar value, SQL may throw an error while using the INSERT INTO
SELECT command.

However, we can skip copying duplicate rows using the NOT EXISTS clause. For example,

Here, the SQL command will only copy row to a new table if the customer_id does not have the same
value.
SQL Delete and
Truncate Rows
SQL Delete and Truncate Rows

In SQL, we use the DELETE statement to delete row(s) from a database table. For
example,

Here, the SQL command will delete a row from the Customers table where
customer_id is 5.
Delete all Rows in a Table

The WHERE clause determines which rows to delete. However, we can delete all
rows at once if we omit the WHERE clause. For example,

Here, the SQL command deletes all rows from the table.
Truncate Table in SQL

The TRUNCATE TABLE clause is another way to delete all rows from a table at
once. For example,

Here, the SQL command does exactly the same thing the above command does.
Delete Vs Truncate

The main difference between both statements is that DELETE FROM statement
supports WHERE clause whereas TRUNCATE does not.

That means, we can delete single or multiple rows using the DELETE FROM
statement while the TRUNCATE statement deletes all records from the table at
once.

We can mimic the TRUNCATE statement with DELETE FROM statement by


omitting the WHERE clause.

For example,
SQL Constraints
Outlines

● SQL Constraints
● SQL Not Null Constraints
● SQL Unique Constraints
● SQL Primary Key
● SQL Foreign Key
SQL Constraints
SQL Constraints

In a database table, we can add rules to a column known as constraints. These


rules control the data that can be stored in a column.

For example, if a column has NOT NULL constraints, it means the column cannot
store NULL values.

The constraints used in SQL are:


NOT NULL Constraints

The NOT NULL constraints in a column means that the column cannot store
NULL values. For example,

Here, the college_id and the college_code columns of the colleges tables won’t
allow NULL values.
UNIQUE Constraint

The UNIQUE constraint in a column means that the column must have unique
value. For example,

Here, the value of the college_code column must be unique. Similarly, the value of
college_id must be unique as well as it cannot store NULL values.
PRIMARY KEY Constraints

The PRIMARY KEY constraints is simply a combination of NOT NULL and


UNIQUE constraints. It means that the column value is used to uniquely identify
the row. For example,

Here, the value of the college_id column is a unique identifier for a row. Similarly,
it cannot store NULL value and must be UNIQUE.
FOREIGN KEY Constraint

The FOREIGN KEY(REFERENCES in some databases) constraint in a column is


used to reference a record that exists in another table. For example,

Here, the value of the college_code column references the row in another table
named Customers.
It means that the value of customer_id in the Orders table must be a value from
the id column of the Customers table.
CHECK Constraint

The CHECK constraint checks the condition before allowing values in a table. For
example,

Here, the value of the amount column must be greater than or equal to 100. If
not, the SQL statement results in an error.
DEFAULT Constraints

The DEFAULT constraints is used to set the default value if we try to store NULL
in a column. For example,

Here, the default value of the college_country column is US. If we try to store the
NULL value in the college_country column, its value will be US.
SQL NOT NULL
Contraint
SQL NOT NULL Constraint

The NOT NULL constraint in a column means that the column cannot store NULL
values. For example,

Here, the college_id and the college_code columns of the Colleges table won’t
allow NULL values.
Remove NOT NULL Constraint

We can also remove the NOT NULL constraint if that is no longer needed. For
example,
NOT NULL Constraint With Alter Table

We can also add the NOT NULL constraint to a column in an existing table using
the ALTER TABLE command. For example,
Here, the SQL command adds the NOT NULL constraint to the column college_id
in an existing table.

Now when we try to insert records in a Colleges table without value for
college_id, SQL will give us an error. For example,

Here, the SQL command gives us an error because we cannot skip the college_id
field in a table because of the NOT NULL constraint.
SQL UNIQUE Constraint
SQL UNIQUE Constraint

In SQL, the UNIQUE constraint in a column means that the column must have
unique values. For example,

Here, the values of the college_code column must be unique. Similarly, the values
of college_id must be unique as well as it cannot store NULL values.
UNIQUE Vs DISTINCT

The UNIQUE constraint is used to make column’s value unique. However, to


select unique rows from the table, we have to use SQL SELECT DISTINCT. For
example,

Here, the SQL command selects unique countries from the Customers table.
Count UNIQUE Rows

If we need to count the number of unique rows, we can use the COUNT( )
function with the SELECT DISTINCT clause. For example,

Here, the SQL command returns the count of unique countries.


UNIQUE Constraint With Alter Table

We can also add the UNIQUE constraint to an existing column using the ALTER
TABLE command. For example,
Error When Inserting Duplicate Values

If we try to insert duplicate values in a column with the UNIQUE constraint, we


will get an error.

Here, we are trying to insert ARD12 in the college_code column in two different
rows. Hence, the INSERT INTO command results in our error.
CREATE UNIQUE INDEX for Unique Values

If we want to create indexes for unique values in a column, we use the CREATE
UNIQUE INDEX constraint. For example,

Here, the SQL command creates a unique index named college_index on the c

Colleges table using the college_code column.


SQL PRIMARY KEY
SQL PRIMARY KEY

In SQL, the PRIMARY KEY constraint is used to uniquely identify rows.


The PRIMARY KEY constraint is simply a combination of NOT NULL and
UNIQUE constraints. Meaning, the column cannot contain duplicate as well as
NULL values.

Here, the college_id column is the PRIMARY KEY. This means, the values of this
column must be unique as well as it cannot contain NULL values.
Primary Key Error

If we try to insert null or duplicate values in the college_id column-in the above
table-we will get an error. For example,

Here, the SQL command gives us an error because we cannot insert same value
for the college_id field in a table because of the UNIQUE constraint.
Try to insert records in the Colleges table,
Primary Key Constraint With Alter Table

We can also add the PRIMARY KEY constraint to a column in an existing table
using the ALTER TABLE command. For example,
Auto Increment Primary Key

It is a common practice to automatically increase the value of the primary key


when a new row is inserted. For example,
Remove Primary Key Constraint

We can remove the PRIMARY KEY constraint in a table using the DROP clause.
For example,
SQL FOREIGN KEY
SQL FOREIGN KEY

In SQL, we can create a relationship between two table using the between two
tables using the FOREIGN KEY constraint.
Here, the customer_id field in the Orders table is FOREIGN KEY which
references the id field in the Customers table.

This means that the values of the customer_id(of the Orders table) must be a
value from the id column(of the Customers table).
Creating FOREIGN Key
Here, the value of the customer_id column in the Orders table references the
row in another table named Customers with its id column.
Inserting Records in Table with Foreign Key
Why use Foreign Key?

To normalize data

The FOREIGN KEY helps us to normalize the data in multiple tables and reduce
the redundancy. This means, a database can have multiple tables that are related
to each other.

Prevent Wrong Data From Insertion

If two database tables are related through a field(attribute) , using FOREIGN


KEY makes sure that wrong data is not inserted in that field. This helps to
eliminate bugs in the database level.
Foreign Key With Alter Table

It is possible to add FOREIGN KEY constraint to an existing table using the


ALTER TABLE command. For example,
Multiple Foreign Key in a Table

A database table can also have multiple freign keys.

Here, the SQL command creates two foreign keys(buyer and seller) in the
Transcations table.
SQL Additional Topics
outlines

● SQL Data Types


● SQL Date and Time
● SQL Operator
● SQL Commands
SQL Data Types
SQL Data Types

In SQL, each column(in a table) has data type. This restricts the type of data that
can be stored in a column.

For example, if the data type of a column is INTEGER, we can only store integer
values such as 0, 1, -1 etc. in that column.

Various databases support various data types and some of most used types are
discussed here.
SQL Server Data Types

Different data types supported in SQL Server are,

Integer Data Types


MySQL Data Types

Different data types supported in MySQL are:


PostgreSQL Data Types

Different data types supported in PostgreSQL are,


Oracle Data Types

Different data types supported in Oracle are,


SQL Date and Time
SQL Date and Time

Working with data and time can be tricky because the date formats may vary for
different reasons. For example, the United States follows the data format of
mm-dd-yyyy whereas the United Kingdom follows the data format of
dd-mm-yyyy.

Moreover, different database systems use different data types to store date and
time. Here’s a quick overview of how data and time are stored by different
database systems.
There are too many date functions available in each database. However, we will
follow along with commonly used date functions in Microsoft SQL Server.
Creating a Table to store Date and Time

We have to create a column with date data type when creating a table. For
example,
Query Records Using Dates

We can also run queries to retrieve records filtering by dates. For example,
Commonly Used Date Functions

This function is used to get the current date and time. For example,

Here, the function returns the current date and time.


CURRENT_TIMESTAMP

This function is used to get the current timestamp in the system. For example,

Here, the function returns the current timestamp in the system.


SQL Operator
SQL Operator

The operators are symbols (and keywords) that are used to perform operations
with values.

These operators are used with SQL clauses such as: SELECT, WHERE, ON, etc.

The operators in SQL can be categorized as:

● Arithmetic operators
● Comparison operators
● Logical operators
SQL Arithmetic Operators

Arithmetic operators perform simple arithmetic operators such as addition,


substractions, multiplication ,etc.
Comparison Operators

We can compare two values using comparison operators in SQL. These


operators return either 1(means true) or 0 (means false).
Logical Operators

We can use logical operators to compare multiple SQL commands. These


operators return either 1(means true) or 0 (means false).

Logical operators available in SQL are,

● AND and ALL


● AND , OR and NOT
● BETWEEN
● EXISTS
● IN
● LIKE
● IS NULL
SQL Comments
SQL Comments

Comments are descriptions in the SQL code that help users better understand
the intent and functionality of the SQL command.

They are completely ignored by the database management systems.


Single Line Comments

In SQL, we use the double dash, –-, to write a single-line comment. The comment
starts from the - - and ends with the end of line. For example,
Comments With Statements

It’s possible to include comments within a line of SQL statements. For example,
Multi-line Comments

In SQL, multiple line comments starts with /* and end with */. For example,
Comments With Statements

Similar to a single-line comments, it’s possible to include multi-line comments


within a line of SQL statement. For example,
Using Comments to Debug Code

We want to skip certain SQL statement from execution. In such cases, instead of
removing the statements, we can simply comment it out.

This helps us to test our SQL code without removing them completely. For
example,
SQL Injection
SQL Injection
SQL Injection is a technique where SQL commands are executed from the form
input fields or URL query parameters. This leads to unauthorized access to the
database ( a typ of hacking ).

If SQL injection is successful , unauthorized people may read, create , update or


even delete records from the database tables.
Example 1 : SQL Injection Using Multiple
Statement
Suppose we have a search form to search products by their ID on our website.
The PHP code snippet to search product would look something like,
Con’t
Con’t
Example 2: SQL Injection Usings Always True
Condition
Another way to perform SQL injection is by passing a condition that always
results in TRUE so that the data is always fetched no matter what.

Let’s take a look at another PHP code snippte where we have a login form in our
website and we need to fetch users by providing credentials.
Con’t
If user inputs username as root and password as pass, the SQL will interpret,

SELECT * FROM Users WHERE username = "root" AND password =


"pass"

This code snippet looks fine when user inputs correct username and password.

What if the user inputs username as invalid_user” OR “1” = “1” and password as
invalid_pass” OR “1” = “1” ? Let’s take a look at how SQL interprets.
Con’t
Since “1” = “1” is always true, no matter what the username and password user
enters, SQL will fetch all the users from the database.
How to Protect SQL Statements From Injections?

Validate User Input


We should always validate user’s input data before actually sending
them to the database. Some best practices include, trimming spaces,
parsing special characters, limiting the input size, etc.

For Example,
Using Prepared Statements
Another best idea to protect SQL statements from being injected is by using
prepared statements.

Prepared statements are basically SQL statements but with placeholders. The
passed arguments are just replaced in place of placeholders.

For Example,
Con’t
Here, the values are only placed in place of ? and the structure of SQL statements
are preserved.
Preparing Our Database
For Online Shop Project
Preparing Our Database - ( online-shop )
● admins
● categories
● products
● orders
Table ( admin )
● id int(10) Primary Key
● fullname varchar(100)
● username varchar(100)
● password varchar(255)
Table - categories
● id int(10) Primary Key
● title varchar(100)
● image_name varchar(255)
● featured varchar(10)
● active varchar(10)
Table - products
● id int(10) Primary Key
● title varchar(100)
● description text
● price decimal (10,2)
● image_name varchar(255)
● category_id int(10)
● featured varchar(10)
● active varchar(10)
Table - orders
● id int(10) Primary Key
● product varchar(100)
● price decimal(10,2)
● qty int(11)
● total decimal(10,2)
● order_date datetime
● status varchar(30)
● customer_name varchar(100)
● customer_contact varchar(30)
● customer_email varchar(50)
● customer_address text
PHP
Introduction to PHP

PHP is one of the most popular programming languages for web development.

PHP allow syou to develop various web applications, including blogs, content
management systems ( CMS ) , and online stores.

PHP is a server-side and general-purpose scripting language that is especially


suited for web development.

PHP originally stood for Personal Home Page. However, now , it stands for
Hypertext Preprocessor.
PHP is a sever-side language

When you open a website on your web browser, for example,


https://www.learnprogrammingmm.com.

The web browser sends an HTTP request to a web server where


learnprogrammingmm.com locates. The web server recives the request and
responds with an HTML document.

In this example, the web browser is a client while the web server is the server.
The client requests for a page, and ther server serves the request.

PHP runs on the web server, processes the request , and returns the HML
document.
PHP is a general-pupose language

When it comes to the purpose of the programming languages, there are two main
types: domain-specific and general-purpose languages.

The domain-specific languages are used within specific application domains. For
example, SQL is a domain-specific language. It’s used mainly for querying data
from relational database. And SQL cannot be used for other purposes.

On there hand, PHP is a general-purpose language because PHP can develop


various applications.
PHP is a cross-platform language

PHP can run on all major operating system, including linux, windows, and macOS.

You can use PHP all leading web servers such asn Nginx, OpenBSD and Apache.
Some clude environments also support PHP like Microsoft Azure and Amazon
AWS.

PHP is quite flexible. It’s not just limited to processing HTML. PHP has build-in
support gengeraing PDF, GIF, JPEG, and PNG images.

One notable feature of PHP is that it supports many databases, including


MYSQL, PostgreSQL, MS SQL,db2,Oracle Database, and MongoDB.
What can PHP do

PHP has two main applications:

● Server-side scripting - PHP is well-suited for developing dynamic websites


and web application.
● Command-line scripting - like Python and Perl, you can rn PHP script from
the command like to perform administrative tasks like sending emails and
generating PDF files.
● In this course, we will mainly focus on server-side scripting.
How PHP Works
Con’t

● First, the web browser sends an HTTP request to the web server, e.g..
index.php.
● Seconds, the PHP preprocessor that locats on the web server processes
PHP code to generate the HTML document.
● Third, the web server sends the HTML document back to the web browser.
Advantages of PHP

Since PHP is designed for web in the first place, it brings many advantages to web
development:

● Simple - PHP is quite easy to learn and get started.


● Fast - PHP websites typically run very fast.
● Stable - PHP is stable since it has been in existence for a long time.
● Open-source and free - PHP is opensource and fee. It means that you don’t
have to pay a license fee to use PHP to develop software products.
● Community support - PHP has an active online community that helps you
whenever you face an issue.
Section 1

● Installing PHP
● Run PHP
Install PHP

Installing PHP on your computer allows you to safely develop and test a web
application without affecting the live system.
To work with PHP locally, you need to have the following software:
● PHP
● A web server that support PHP. We’ll use Apache webserver.
● A database server. We’ll use the MySQL database server.
Typically, you won’t install all this software separately because connecting them
is tricky and not intended for beginners.
Therefore , it’s easier to find an all-on-one software package that includes PHP, a
web server and a dababse sever. One of the popular PHP development
environment is XAMPP.
Start the xampp server
PHP Hello World on the web browser

● First, Open the folder htdocs under the xampp folder. Typically it locates: at

C:\xampp\htdocs

● Second, create a new folder called helloworld.


● Third, create a new file called index.php under the helloworld folder and
place the following code
Index.php
Run the php

● Browser -> localhost/helloworld/


● Command LIne -> php index.php
Section 2

● Syntax
● Variable
● Constants
● Comments
● var_dump
Syntax

PHP Code

● Like HTML, you need to have the opening tag to start PHP code: <? php
● If you mix PHP code with HTML, you need to have the enclosing tag: ?>
● For Example <h1><?php echo “PHP Syntax”; ?></h1>
● However, if a file contains only PHP code, the enclosing tag is option:

<? php

echo ‘PHP Syntax’;


Case sensitivity

PHP is partially case-sensitive. Knowing what are case sensitive and what is not
is very important to avoid syntax errors.

If you have a function such as count, you can use it as COUNT. It would work
properly.

The following are case-insensitive in PHP:

● PHP constructs such as if, if-else ,if - elseif , switch , while , do-while , etc.
● Keywords such as true and false .
● User-defined function & class names.

On the other hand, variable are case sensitive. E.g, $message and $MESSAGE are
different variables.
Statements

A PHP script typically consists of one or more statements. A statement is a code


that does something, e.g ., assigning a value to a variable and calling a function.
A statement always ends with a semicolon( ; ). The following shows a statement
taht assgns a literal string to the $message variable:
$message = “Hello”;
The above example is a simple statement. PHP also has a compound statement
that consists of one or more simple statements. A compound statement uses
curly braces to mark a block of code. For example,
If ($is_new_user) {
send_welcome_email();
} // you don’t need to place the semicolon after the curly brace ( } )
Con’t

The closing tag of a PHP block ( ?> ) automatically implies a semicolon ( ; ).

Therefore, you don’t need to place a semicolon in the last statement in a PHP
block. For example:

<?php echo $name ?>


Whitespace & line breaks

In most cases, whitespace and line breaks don’t have special meaning in PHP.
Therefore, you can place a statement in one line or span it across multiple lines.

For example, the following code snippets are equivalent:

Login ( $username, $password );

And

login(

$username,

$password

);
PHP Variables

A variable stores a value of any type, e.g, a string ,a number, an array or an object.
A variable has a name and is associated with a value. To define a variable, you use
the following syntax:
$variable_name = value;
When defining a variable, you need to follow these rules:
● The variable name must start with the dollar sign ( $ ).
● The first character after the dollar sign ( $ ) must be a letter ( a - z ) or the
underscore ( _ ). For Example, $name or $_name
● The remaining characters can be underscores, letters and numbers.
● PHP variables are case-sensitive. It means that $message and $Message
variable are entirely different.
Example

<body>

<?php

$title = ‘PHP is awesome!’;

?>

<h1><?php echo $title; ?></h1>

</body>

If you open the page , you’ll see the following message:

PHP is awesome!
Con’t

Another sorter way to show the value of a variable on a page is to use the
following syntax:

<?= $varaibale_name ?>

<?php

$title = ‘PHP is awesome’;

?>

<h1><?= $title; ?></h1>


Con’t

Mixing PHP code with HTML will make the code unmaintainable, especially
when the application grows. To avoid this, you can separate the code into
separate files. For example:

● Index.php - store the logic for defining and assigning value to variables.
● Indes.view.php - store the code that display the variables.
● Use te require construct ot include the code from the index.view.php in the
index.php
index.view.php

<!DOCTYPE html>
<html lang = “en”>
<head>
<title> PHP Variables </title>
</head>
<body>
<h1> <?= $title ?> </h1>
</body>
</html>
index.php

<?php

$title = ‘PHP is awesome!’;

require 'index.view.php’;

If you open the index.php file on the web browser, you’ll see the same output;.

By doing this, you separate the code responsible for logic and the code
responsible for displaying the file. This is called the separation of concerns (SoC)

in Programming.
PHP Comments

Comments are important parts of the code. Comments provide useful


information that will help you and other developer understand the meaning of
the code more quickly later.

PHP supports two types of comment:

● One-line comments
● Multi-line comments
One-line comments

The one-line comments is placed at the end of the line or at the current block.

A one-line comments starts with the ( # ) or ( // ). The rest of the text after these
symbols are ignored by the PHP interpreter.

The following example uses the // for a one-line comment:

<?php

$rate = 100;

$hours = 173;

$payout = $hour * $rate ; //payout calculation

$title = ‘PHP comment’; #set default title


Multi-line comments

A Multi-line comment start with ( /* ) and end with ( */ ). For example

<?php

/*

This is an example of multi-line comments

Which can span multiple lines.

*/
Writing meaningful comments

To document your code effectively, you use the following guidelines:


● Making the code speak for itself without using comments by naming meaningful
identifiers. Fo example, you can use the following:
$is_completed = true;
Instead of using a cryptic name with a comment:
$ic = true; // is completed
● Don’t write a comment to explain what code does, instead , explain why it does so.
For example:
//complete the task
$is_completed = true
● When writing a comment, make it as concise as possible.
PHP Constants

In this tutorial, you will learn about PHP constants and how to use the define()
function and const keyword to define constants.

Introduction to PHP Constants


A constant is simply a name that holds a single value. As its name implies, the
value of a constant cannot be changed during the execution of the PHP script.

To define a constant, you use the define() function.

The define() function takes the constant’s name as the first argument and the
constant value as the second argument.
For example:

<? php
define(‘WIDTH’ , ‘1140px’);
echo WIDTH;
By convention, constant name are uppercase. Unlike a varible, the constant name
doesn’t start with the dollar sign ( $ ).
By default, constant names are case-sensitive. Ite means that WIDTH and width
are different constants.
In PHP 5, a constant can hold a simple value like a number , a string , a boolean
value. From PHP 7.0, a constant can hold an array. For example
define ( ‘ORIGIN’, [0,0] ); like superglobal variables, you can access constants
form anywhere int the script.
The const keyword

PHP provides you with another way to define a constant via the const keyword .
Here’s the syntax:
const CONSTANT_NAME = value;
In this syntax, you define teh constant name after the const keyword. To assign a
value to a constant, you us the assignment operator ( = ) and the constant value.
The constant value can be a number, a string or an array.
For example,
const SALES_TAX = 0.85;
$gross_price = 100;
$net_price = $gross_price * ( 1- SALES_TAX);
define vs const

First, the define() is a function while const is a language construct.

It means that the define() function defines a constant a run-time , whereas the
const keyword defines a constant at compile time.

In other words, you can use the define() function to define a constant
conditionally like this:

If ( condition ){

define(‘WIDTH’ , ‘1140’); // const WIDTH = ‘1140

However, you cannot use the const keyword to define a constant this way!Invalid
PHP var_dump

In this tutorial, you will learn how touse the PHP var_dump() function to dump
the information about a variable.

Introduction to the PHP var_dump function


The var_dump() is a built-in function that allows you to dump the information
about a variable. The var_dump() function accepts a variable and displays its type
and value.

<?php

$balance = 100;
Con’t

To display the information of $balance variable, you place it within parentheses


that follow the var_dump() function name like this:

<?php

$balance = 100;

$message = ‘Insufficient balance’;

var_dump($balance);

If you open the page on the web browser: you’ll see the following output:

int(100) string(20) “Insufficient balance”


Con’t

<?php
$balance = 100;
echo ‘<pre>’; Output

var_dump($balance); int(100)
string(20) “Insufficient balance”
echo ‘</pre’;
$message = ‘Insufficient balance’;
echo ‘<pre>’;
var_dump($message);
echo ‘</pre>’;
Define a dump helper function : user defined functon

<?php
function d($data){
echo ‘<pre>’;
var_dump($data);
echo ‘</pre>’;
}
To use the d() funciton, you can pass a variable to it as follows:
d($amount);
d($message);
die() function

The die() function displays a message and terminat the execution of the script:

die($status);

Sometimes, you want to dump the information of a variable and terminate the
script immediately. In this case, you can combine the var_dump() with the die()
function.
For example

<?php

$message = ‘Dump and die example’;

d($message);

die();

echo ‘After calling the die function’;

Output:

string(20) “Dump and die example”


Section 3

● Datatypes
● Boolean
● Integer
● Float
● String
● Null
● Type Casting
● Type Juggling
PHP Data Types

A type specifies the amount of memory that allocates to a value associated with
it. A type also determines the operations that you can perform on it.

PHP has ten primitive types including for scala types, for compound types, and
two special types:
Con’t
Scalar Types

A variable is a scalar when it holds a single value of the type integer, float , string ,
or boolean.
Integer
Integers are whole numbers defined in the set { … -3 , -2 , -1, 0 , 1, 2,3,..}
The size of the integer depends on the platform where PHP runs. PHP use int
keyword to denote the integer type.
The following example illustrates some integers:
<?php
$count = 0;
$max = 1000;
Float

Float are floating-point numbers, which are also known as floats, doubles , or real
numbers.

PHP uses the float keywordto represent the floating-point numbers. The
following example illustrates the floating-point numbers in PHP:

<?php

$price = 10.25;

$tax = 0.08;
Boolean

Boolean represents a truth value that can either true or false. Since keywords are
case-insensitive , you can use true,True,TRUE,false,False, and FALSE to indicate
boolean values:

<?php

$is_admin = true;

$is_user_logged_in = false;

var_dump($is_admin);
String

A string is a sequence of characters surrounded by single quotes(‘) or double


quotes(“). For example:

<?php

$str = ‘PHP scalar type’;

$message = “PHP data types”;

$name = ‘John’;

And if you want to show a message that displays -> Hello John

echo ‘Hello’ . $name; OR echo “Hello {$name}”;

Note that PHP doesn’t substitute the value of variables in the single-qute string.
Accessing characters in a string

A string has a zero-based index. It means that the first character has an index of
0. The second character has an index of 1 and so on.

To access a single character in a string at a specific position, you use the following
syntax:

$str[index]

<?php

$title = ‘PHP string is awesome’;

echo $title[0]; // P

To get the length of a string, echo strlen($title);


PHP Heredoc

Heredoc are use to improve the readability of the code.

When you place variables in a double-quoted string, PHP will expand the
variable names. If a string contains the double quotes ( “ ) , you need to escape
them using the backslash character ( \ ). For example

<?php

$he = ‘Bob’;

$she = ‘Alice’;

$text = “$he said, \”PHP is awesome\”.

\”Of course.\” $she agreed.”;


Con’t

PHP heredoc strings behave like double-quoted strings, without the double - quotes. It
means that they don’t need to escape quotes and expand variables. For example,
<?php
$he = ‘Bob’;
$she = ‘Alice’;
$text = <<<TEXT
$he said “PHP is awesome”.
“Of course” $she agreed.”
TEXT;
echo $text;
Compound Types

Compound data includes the values that contain more than one value. PHP has
two compound types including array and object.

Array

An Array is an ordered map that associates keys with values. For example, you
can define a list of items in a shopping cart like this:

<?php

$carts = [ ‘laptop’, ‘mouse’, ‘keyborad’ ];

The $carts array contains three string values. It maps the index 0 , 1, 2 to the
values ‘laptop’ , ‘mounse’ and ‘keyboard’. The $cars is called an indexed array
because it uses numeric indexes as keys.
Con’t

To access a value in an array, you use the square brackets:

<?php

echo $carts[0]; // ‘laptop’

echo $carts[1]; // ‘mouse’

echo $carts[2]; // ‘keyboard’

Besides numeric indexes, you can use strings as keys for the array elements .
Theses arrays are knows are associated arrays. For example:
Con’t

<?php

$prices = [

‘laptop’ => 1000,

‘mouse’ => 50,

‘keyboard’ => 120

];

To access an element in an associative array, you specify the key in the square
brackets. For example:
Con’t

<?php

$prices[‘laptop’]; // 1000

$prices[‘mouse’]; // 50

$prices[‘keyboard’] // 120
Object

An object is an instance of a class. It’s a central concept in object-oriented


programming.

An object has properties. For example, a person object my have the first name,
last name , and age properties.

An object also has behaviors, which are known as methods. For example, a
person object can have a method called getFullName() that returns the full name.
Special Types

PHP has two special types: null and resource

Null

The null type has one value called null that represents a variable with no value.

$email = null;

var_dump(is_null($email)); //bool(true)

Resource

The resource type holds a reference to an external resource, e.g. a filehandler or


a database connection.
Type Casting

Type casting allows you to convert a value of one type to another. To cast a value,
you use the following casting operators:
For example
echo (int)12.5 . ‘<br>’; //12
$message = ‘Hi’;
echo (int) $message; // 0
If a string is numeric or leading numberic , then (int) will cast it to the
corresponding integer value. Otherwise, the (int) cast the string to zero. For
example
echo (int)’100 USD’; //100
Con’t

Note that (int) operator casts null to zero(0). For example:


$qty = null; echo (int) $qty;
Cast to a float
echo (float)100;
Cast to a string;
$amount = 100;
echo (string)$amount . “ USD”; // 100 USD
$is_user_logged_in = true;
echo (string)$is_user_logged_in; // 1
Type Juggling

PHP is a loosely typed programming language. It means that when you define a
variable, you don’t need to declare a type for it.Internally PHP will determine the
type by the context in which you use the variable.

For example, if you assign a string to a variable, its type will be string:

$my_var = ‘PHP’; // a string

$my_var = 100; // now an integer

PHP has a feature called type juggling. It means that during the comparison of
variables of different types, PHP will convert them to the common , comparable
type.
Con’t

<?php

$qty = 20;

if($qty == ‘20’){

echo ‘Equal’;

Output: Equal

Because of type guggling, PHP converts the string ‘20’ to an integer (20) and
compares it with the $qty variable. The result is true.
Con’t

The type juggling also works in arithmetic operations for variables of different
types. The following example illustrates how the type juggling works in
arithmetic operations:

<?php

$total = 100;

$qty = “20”;

$total = $total + $qty;

echo $total; //120


Section 4: Operators
Section 4 : Operators

● Assignment Operators
● Comparison Operators
● Logical AND Operator ( &&)
● Logical OR Operator( || )
● Logical NOT Operator( ! )
PHP Assignment Operators

PHP uses the = to represent the assignment operator. The Following shows the
syntax of the assignment operator:

$variable_name = expression;

$x = 10;

$y = 20;

$total = $x + $y;

In this example, we assigned 10 to $x , 20 to $y , and the sum of $x and $y to


$total.

$x = $y = 20;
Arithmetic assignment operators
Concatenation assignment operator

PHP users the concatenation operator(.) to concatenate two strings. For


example:

<?php

$greeting = ‘Hello ’;

$name = ‘John’;

$greeting = $greeting . $name; // $greeting .= $name;

echo $greeting;
PHP Comparison Operators

A comparison operator allows you to compare two values and return true if the
comparison is truthful and false otherwise.
Con’t
Equality Operator ( == )

<?php

$x = 10;

$y = 10;

var_dump( $x == $y); // bool ( true )

$x = ‘20’;

$y = 20;

var_dump( $x == $y ) ; // bool(true)
Not equal to operator ( != , <> )

<?php

$x = 20;

$y = 10;

var_dump( $x != $y ); // bool(true)
Identical Operator ( === )

The identical operator return true if both values are equal and have the same
type; otherwise return false.

<?php

$x = ‘20’;

$y = 20;

var_dump($x === $y); // bool(false)


Not Identical operator ( !== )

<?php

$x = 20;

$y = 10;

var_dump( $x !== $y ); // bool(true)

$x = 20;

$y = ‘20’;

var_dump( $x !== $y ); // bool(true)


Greater than ( > )

<?php

$x = 10;

$y = 20;

var_dump( $x > $y ); // bool(false)

var_dump($y > $x ); // bool(true)


Greater than or equal to ( >= )

<?php

$x = 10;

$y = 20;

var_dump($x >= $y); // bool(false)

var_dump($y >= $x); // bool(true)


Less than( < )

<?php

$x = 20;

$y = 10;

var_dump($x < $y); // bool(false)

var_dump($y < $x); // bool(true)


Less than or equal to ( <= )

<?php

$x = 20;

$y = 20;

var_dump($x <= $y); // bool(true)

var_dump($y <= $x); // bool(true)


PHP AND Operator

The logical AND operator accepts two operands and returns true if both
operands are true; otherwise, it returns false.

PHP user the and keyword to represent the logical AND operator:
PHP AND operator examples

<?php

$price = 100;

$qty = 5;

$discounted = $qty > 3 && $price > 99;

var_dump($discounted);

// bool(true)
Short-circuiting

When the value of teh first operand is false, the logical AND operator knows that
ther result must be also false. In this case, it doesn’t evaluate the second operand.
This process is called short-circuiting.

<?php

$debug = false;

$debug && print(‘PHP and operator demo!’); // print won’t work

$debug = true;

$debug && print(‘PHP and operator demo!’); // print will work


PHP OR Operator

The logical OR operator accepts two operands and return true if either operand
is true, otherwise, it returns false. In other words, the logical OR operator
returns false if both operands are false.

To represent teh logical OR operator, PHP users either the or keyword or the ||
as follows:
PHP OR operator examples

<?php

$expired = true;

$purged = false;

$clear_cache = $expired || $purged;

var_dump($clear_cacher); // bool(true)
Short-Circuiting

When the first operand is true, the logical OR operator knows that the result
must be also true. In this case, it doesn’t evaluate the second operand. This
process is called short-circuiting.

<?php

function connect_to_db(){

return false;

connect_to_db() || die(‘Cannot connect to the database.’);


PHP NOT operator

Unlike teh logical AND and OP operators that accept two operands , the logical
NOT operator accepts only one operand and negates the operands.

In other words, the logical NOT operator returns true if the operands is false and
returns false if the operand is true;

PHP uses the both not keyword and (!) to represent the logical NOT operator.
PHP NOT Opeartor examples

<?php

$priority = 5;

var_dump( ! $priority < 5 ); // bool(true)


PHP Arithmetic Operators

PHP provides you with common arithmetic operators that allow you to perform
addition, subtraction, multiplication, division, exponentiation and modulus
operations.

The arithmetic operators require numeric values. If you apply an arithmetic


operator to non-numeric values, it’ll convert them to numeric values before
performing the arithmetic operation.

The following table illustrates teh arithmetic operators in PHP:


Con’t
PHP arithmetic operator examples

<?php

$x = 20;

$y = 10;

echo $x + $y ; // 30

echo $x - $y; // 10

echo $x * y; // 200

$z = $x / $y ;
Section 5 : Control Flows
Control Flows
● if
● if else
● if elseif
● switch
● for
● while
● do while
● foreach
● break
● continue
PHP if
The if statement allows you to execute a statement if an expression evaluates to
true. The following shows the syntax of the if statement:

<?php

if( expression )

statement;
Flow Chart
Con’t
<?php

$is_admin = true;

if($is_admin)

echo ‘Welcome Admin!’;


Curly braces
If you want to execute multiple statements in the if block, you can use curly
braces to group multiple statements like this:

<?php

if ( expression ) {

statement1;

statement2;

// more statement

}
Con’t
The following example uses the if statement that executes multiple statements:

<?php

$can_edit = false;

$is_admin = true;

if ( $is_admin ){

echo ‘Welcome Admin!’;

$can_edit = true;

}
Con’t
It’s a good practice to always use curly brackets with the if statement even
though it has a single statement to execute like this:

<?php

if ( expression ) {

statement;

}
Nesting if statements
<?php

if ( expression 1 ) {

// do something

if ( expression 2 ){

// do other things

}
Con’t
<?php
$is_admin = true;
$can_approve = true;
$if ( $is_admin ) {
echo ‘Welcome , admin!’;
if ( $can_approve ) {
Echo ‘Please approve the pending items’;
}
}
Embed if statement in HTML
To embed an if statement in an HTML document, you can use the above syntax.
PHP provides a better syntax that allows you to mix teh if statement with HTML
nicely:

<?php if ( expression ) : ?>

<!-- HTML code Here - - >

<?php endif; ?>


Con’t
<?php $is_admin = true; ?>

<?php if ( $is_admin ) : ?>

<a href= “#”> Edit </a>

<?php endif; ?>

<a href = “#” > View </a>


PHP if else
The if statement allows you to execute one or more statements when an
expression is true:

<?php

if ( expression ) {

// code block

Sometimes, you want to execute another code block if the expression is false. To
do that, you add the else clause to the if statement:
Con’t
<?php

if ( expression ) {

// code block

} else {

// another block

}
Flow Chart
Con’t
<?php

$is_authenticated = false;

if ( $is_authenticated ) {

echo ‘Welcome!’;

} else {

echo ‘You are not authorized to access this page.’;

}
PHP if … else statement in HTML
Like the if statement, you can mix the if … else statement with HTML nicely using
the alternative syntax:

<?php if ( expression ) : ?>

<!-- Show HTML code when expression is true -->

<?php else: ?>

<!-- Show HTML code when expression is false →

<?php endif ?>


Con’t
<?php $is_autenticated = true; ? >

<?php if ( $is_authenticated ) : ?>

<a href = “#”> Logout </a>

<?php else: ?>

<a href = “#” > Login </a>

<?php endif ?>


PHP if elseif
The if statement can have one or more optional elseif clauses. The elseif is a
combination of if and else

<?php

if ( expression1 ) {

statement;

} elseif ( expression2 ) {

statement;

}…
Con’t
Con’t
<?php
$x = 10, $y = 20;
if( $x > $y ) {
echo ‘x is greater than y’;
} elseif ( $x < $y) {
echo ‘x is less than y’;
}else{
echo ‘x is equal to y’;
}
Alternative syntax
<?php

if ( expression ) :

statement;

elseif ( expression2 ):

statement;

else:

statement;

endif;
Con’t
$x = 10, $y = 20;

if ( $x > $y ):

echo ‘x is greater than y’;

elseif ( $x < $y ):

echo ‘x is less than y’;

else:

echo ‘x is equal to y’;

endif;
PHP elseif vs else if
if (expression){ if (expression){

statement; statement;

} else if ( expression 2) { } elseif ( expression 2) {

statement statement

} }

They have the same result


PHP Ternary Operator
The ternary operator is a shorthand for the if … else statement. Instead of writing
this:
<?php
if ( condition ) {
$result = value1;
} else {
$result = value2;
}
Instead of this, we can you
Con’t
$result = condition ? value1 : value2;

$is_user_logged_in = false;

if( $is_user_logged_in ) {

$title = ‘Logout’;

} else {

$title = ‘Login’;

$title = $is_user_logged_in ? ‘Logout’ : ‘Login’;


The shorthand ternary operator
Starting from PHP 5.3, you can use the shorthand ternary operator as follows:

$result = $initial ?: $default;

<?php

$path = ‘/about’; $path ;

$url = $path ?: ‘/’; $url

echo $url; // /about


Chaining ternary operators
Technically , you can chain ternary operators by using parentheses.
PHP switch
When the value of a single variable determines the number of different choice,
you can use the if … elseif statement.

Suppose that you’re building a website whose users have many roles like admin ,
editor , author , and subscriber.

The following example users an if elseif statement to display a different message


based on the role of user:
Con’t
Output:

Welcome the value of a single variable specifies the number of different choices,
it’s much cleaner to use the switch statement like this:
Switch Syntax
Switch - Flow Chart
PHP For Loop
The for statement allows you to execute a code block repeatedly. The syntax of
the for statement is as follows:
● The start is evaluated once when
<?php the loop starts.
● The condition is evaluated once in
for ( start; condition ; increment ) {
each iteration. If the condition is
statement; true, the statement in the body is
executed. Otherwise the loop
} ends
● The increment expression is
evaluated once after each
iteration.
Flow Chart
PHP for statement example
<?php

$total = 0;

for($i = 1 ; $i <= 10 ; $i ++) {

$total += $i;

echo $total;

// output 55
PHP while
The while statement executes a code block as long as an expression is true. The
syntax of the while statement is as follows:
● First, PHP evaluates the
<?php expression. If the result is true,
PHP executes the statement.
while ( expression ) {
● Then , PHP re-evaluates the
statement; expression again. If it’s still true,
PHP executes the statement
} again. However, if the expression
is false, the loop ends.
If the expression evaluates to false before

the first iteration starts, the loop ends immediately.


Flow Chart
PHP while loop example
<?php

$total = 0;

$number = 1;

while ( $number <= 10 ) {

$total += $number;

$number++;

echo $total; // Output: 55


The alternative syntax for the PHP while loop
<?php

while ( expression ) :

statement;

endwhile;
Con’t
$total = 0 ;

$number = 1;

while ( $number <= 10 ) :

$total += $number;

$number++;

endwhile;

echo $total; // Output 55


PHP do … while
The PHP do … while statement allows you to execute a code block repeatedly
based on a boolean expression. Here’s the syntax of the PHP do-while statement:

<?php

do {

statement;

} while ( expression );
Flow Chart
do … while VS while
● PHP executes the statement in do … while at least once, whereas it won’t
execute the statement in the while statement if the expression is false.
● PHP evaluates the expression in the do … while statement at the end of each
iteration. Conversely, PHP evaluates the expression in the while statement
at the beginning of each iteration.
PHP do … while loop statement example
<?php

$i = 0;

do {

echo $i;

} while ( $i < 0 );
PHP break;
The break statement terminates the execution of the current for , do … while ,
while or switch statement. This tutorial focus on how to use the break statement
with the loops.

Typical, you can use the break statement with the if statement that specifies the
condition for terminating loop.
PHP foreach
PHP provides you with the foreach statement that allows you to iterate over
elements of an array, either an indexed array or an associative array.

The foreach statement iterates over all elements in an array, one at a time. It
starts with the first element and ends with the last one. Therefore, you don’t
need to know the number of elements in an array upfront.
Flow Chart
PHP foreach with indexed arrays
To iterate over all elements of an indexed array, you can use the following syntax:

<?php

foreach( $array_name as $element) {

// process element here

}
For example
<?php

$colors = [‘red’, ‘green’ , ‘blue’ ];

foreach ( $colors as $color ) {

echo $color . ‘<br>’;

}
PHP foreach with an associative array
<?php

foreach ( $array_name as $key => $value ) {

// process element here

}
Con’t
$capitals = [

‘Japan’ => ‘Tokyo’,

‘France’ => ‘Paris’,

‘Germany’ => ‘Berlin’

];

foreach ( $capitals as $country => $capital ) {

echo “The capital city of {$country} is $capital” . “<br>”;

}
Using PHP break statement in a for loop
<?php

for ($i = 0 ; $i < 10 ; $i++) {

if( $i === 5 ) {

break;

echo “$i\n”;

}
Using PHP break statement in a do … while loop
<?php

$j = 0;

do {

if( $j === 5 ) {

break;

} while ( $j <= 10);


Using PHP break statement in a while loop
$k = 0;

while ( $k <= 10 ) {

if ( $k === 5 ) {

break;

echo “$k \n”;

$k++;

}
PHP continue
The continue statement is used within a loop structure such as for , do … while ,
and while loop. The continue statement allows you to immediately skip all the
statements that follow it and start the next iteration from the beginning.
<?php
for ( $i = 0 ; $i < 10 ; $i ++ ) {
if ( $i % 2 === 0 ) {
continue;
}
echo “$i\n”;
} // this will only print odd number only
PHP Section 6 :
Functions
PHP Functions
● Functions
● Function Parameters
● Default Parameters
● Named Arguments
● Variable Scopes
● Type Hints
● Strict Typing
● Variadic Functions
What is a function ?
A function is a named block of code that performs a specific task.

So far, we have learned how to use built-in functions in PHP , such as var_dump()
that dumps information about a variable.

In this tutorial, you’ll learn how to define your functions. These functions are
called user-defined functions.
welcome() function
function welcome(){

echo ‘Welcome!’;

<?php

welcome();
Define a function
To define a function, you can use the following syntax:

<?php

function function_name(){ function welcome(){

statement; echo ‘Welcome!’;

} }

The welcome() function doesn’t have input. It shows the welcome message.

In practice, functions often accept inputs. The inputs make functions reusable
and more useful. And the inputs of a function are called parameters.
Con’t
A function may have zero or more parameters. To add one or more parameters to
a function, you can use the following syntax:
<?php
function function_name( parameter1, parameter2, … ) {

Inside the function body, you can use the parameters like variables. In fact,
parameters are the local variables.
Con’t
For example, if you want to welcome users by their usernames , you can add a
$username parameter to the welcome function as follows:

funcion welcome_user($username){

echo ‘Welcome ’ . $username;

The welcome_user() function has a parameter $username . It displays a welcome


message to the user by concatenating the Welcome message with $username.
Call a function
When a function doesn’t have any parameter, you can call the function by using
its name followed by parentheses like this:

<?php

function_name();

function welcome(){

echo ‘Welcome!’;

welcome();
Con’t
<?php

function welcome_user($username){

echo ‘Welcome ’. $username;

welcome_user(‘Admin’);
Return a value
A function can return a value. To return a value from a function, you use the
return statement:
return value;
<?php
function welcome_user($username){
return ‘Welcome ’. $username . ‘!’;
}
$welcome_message = welcome_user(‘Admin’);
echo $welcome_message; // or echo welcome_user(‘Admin’);
HTML code inside the function
Typically, a function contains only PHP code. However, it’s possible to define a
function that contains HTML code. The following welcome() function displays
the welcome message wrapped in a span tag:

<?php function welcome_user($username) { ?>

<span> Welcome <?= $username ?></span>

<?php } ?>
PHP Function Parameters
A function can have zero or more parameters:

<?php

function function_name(parameter_list) {

<?php

function concat ($str1 , $str2){

return $str1 . $str2;

}
Con’t
$greeting = concat(‘Welcome ’, ‘Admin’);

echo $greeting;
PHP Default Parameters
The following concat() function that concatenates two strings with a delimiter:

<?php

function concat( $str1 , $str2 , $delimiter){

return $str1 . $delimiter . $str2 ;

$message = concat(‘Hi’ , ‘there!’ , ‘ ’);

echo $message;

When you call the concat() function , you need to pass exactly three arguments.
Default Parameter
PHP allows you to specify a default argument for a parameter. For example:

<?php

function concat($str1,$str2, $delimiter = ‘ ’){

return $str1 . $delimiter . $str2;

$message = concat(‘Hi’, ‘there!’);

echo $message; // Hi there


Con’t
However if you pass an argument for the $delimiter , the function will use that
argument instead:

<?php

function concat( $str1 , $str2 , $delimiter = ‘ ’){

return $str1 . $delimiter . $str2;

$message = concat( ‘Hi’, ‘there!’, ‘ , ’ );

echo $message;
PHP Named Arguments
Since PHP 8.0, you can use named arguments for functions. The named arguments
allow you to pass arguments to a function based on the parameter names rather than
the parameter positions.
The following example defines a function that finds the position of the first occurrence
of substring in a string:
<?php
function find($word, $text){
return strpos($text,$word);
}
To call the find() function, you pass the arguments based on the parameter positions like
this. find(‘awesome’, ‘PHP is awesome!’);
Con’t
Sometimes, you may accidentally make a mistake by passing the arguments in
the wrong order. For example:
find( ‘PHP is awesome!’, ‘awesome’);
This is buggy and difficult to troubleshoot.
To avoid this, you may add comments to the arguments like this:
find(
‘awesome’ , // word
‘PHP is awesome!’ // text
);
Con’t
The comment makes the code more clear. However , it’s not robust.
To improved this, PHP 8.0 introduced the name arguments that allow you to
specify the parameter names when passing arguments:
find(
word : ‘awesome’,
text : ‘PHP is awesome!’
);
Since you are using the parameter names, the positions are not necessary. For
example, you can sway the parameters like this:
Con’t
find(

$text: ‘PHP is awesome!’,

$word: ‘awesome’
);

It should work correctly.


Skipping default arguments
The following defines a function that creates an anchor element <a> from text,
href , title , and target:

function create_anchor( $text, $href = “#”, $title = ‘ ’, $target = ‘_self’ ){

$href = $href ? sprintf(‘href= “%s”’,$href) : ‘’;

$title = $title ? sprintf(‘title = “%s”’,$title) : ‘’;

$target = $target ? sprintf(‘target= “%s”’,$target) : ‘’;

return “<a $href $title $target>$text</a>;

}
Con’t
To create a link with the target is _blank, you must specify all the default
arguments until the one you want to change. For example:
$link = create_anchor(
‘PHP Tutorial’,
‘https://www.google.com’,
‘’,
‘_blank’
);
echo $link; // <a href = “https://www.google.com” target= “_blank”>PHP
Tutorial </a>
Con’t
In the previous example, you need to pass the space (‘’) to the third argument. If
you use the named arguments, you don’t have to specify all the defaults. For
example:

$link = create_anchor(
text : ‘PHP Tutorial’,
href: ‘https://www.google.com’,
target: ‘_blank’
);
Mixing named arguments with positional
argument
PHP allow you to call a function by using both positional arguments and named
arguments. And you need to place the named arguments after positional
arguments. For example,

$link = create_anchor(

‘PHP Tutorial’,

‘https://www.google.com’ ,

target: ‘_blank’

);
Con’t
If you place the name arguments before the positional arguments , you’ll get an
error. For example:
create_anchor(
target: ‘_blank’,
‘PHP Tutorial’,
‘https://www.google.com’
);

//This will cause the error!


PHP Functions
● Functions
● Function Parameters
● Default Parameters
● Named Arguments
● Variable Scopes
● Type Hints
● Strict Typing
● Variadic Functions
PHP Variable Scopes
The scope of a variable determines which part of the code can access it. The
locations where the variable can be accessible determine the scope of the
variable.

In PHP, variables have four types of scopes:

● Local
● Global
● Static
● Function parameters
Local Variable
When you define a variable inside a function, you can only access that variable
within the function. And it’s said that the variable is local to the function.

The following example defines the say() function that displays the ‘Hi’ message:

function say(){

$message = ‘Hi’;

echo $message;

}
Con’t
Inside say() function , we defined the $message variable. The $message variable
is a local variable. And you cannot access it from the outside of the say() function.

Also, the $message variable only exists during the execution of the say() function.
Once the say() function ends, the $message variable won’t exist anymore.
Global variables
When you declare a variable outside of a function, the variable is global. It means
that you can access the variable anywhere within the script except inside a
function. For example:
$message = ‘Hello’; // global variable
function say(){
$message = ‘Hi’; // local variable
echo $message;
}
echo $message; // Hello
Con’t
PHP allows you to access a global variable within a function by using the global
keyword. For example:

$message = “hello”;

function say(){

global $message;

echo $message; //

}
Superglobal variables
PHP has a list of build in variables, which are known as superglobal variables. The
superglobal variables provide information about the PHP script’s environment.

The superglobal variables are always available in all parts of the script. The
following table shows the list of PHP superglobal variables:
Static Variables
A static variable retains its value between function calls. Also , a static variable is
only accessible inside the function. To define a static variable, you use the static
keyword. For example,
function get_counter(){
static $counter = 1;
return $counter++;
}
echo get_counter(); // 1
echo get_counter(); //2
echo get_counter(); //3
Function Parameters
Function parameters are local to the function. Therefore, function parameters
can only accessible inside the function. For example,
function sum($items){
$total = 0;
foreach($items as $item){
$total += $item;
}
return $total;
} // echo sum( [10 , 20 , 30 ] );
PHP Type Hints
PHP is a dynamically typed language . When you define a function, you don’t
need to declare types for parameters. For example:

function add($x , $y){

return $x + $y;

$result = add ( 1 , 2 );

echo $result;
Con’t
The add() function accepts two arguments and returns the sum of them. In this
example, we pass two integers into the add() function and get the result as an
integer.

If you pass two float-point numbers into the add() function, you’ll get the sum of
the floats, which is a floating-point number;

$result = add ( 1.0 , 2.5 );

echo $result;
Con’t
More interestingly , you can pass an integer and a numeric string into the add()
function , it will return an integer:

$result = add(1, ‘2’);

echo $result;
Con’t
If PHP fails to convert the string argument into an integer, it’ll issue an error. For
example:

$result = add(‘Hi’ , ‘There’ );

echo $result;

Fatal error: Uncaught TypeError: Unsupported operand types: string + string


PHP type hints for function parameters
The type hints ensure that PHP will check the type of a value at the call time and
throw a TypeError if there is a mismatch.

To add a type hint to a parameter, you place a type in front of it like this:

function my_function ( type $param1, type param2 , … ){

// ..

}
Con’t
The following defines the add() function that accepts two integers:

function add ( int $x , int $y ) {

return $x + $y;

$result = add(1,2);

echo $result ; //3


Con’t
However, if you pass two floats , you’ll get the result as an integer:

$result = add(1, 2.5);

echo $result; // 3
PHP type hints for function’s return value
function my_function(type $param1 , type $param2 , … ) : type

function add( int $x , int $y) : int {

return $x + $y;

echo add ( 10 , 20 );
Con’t
Starting from PHP 7.0, if a function doesn’t return a value, you use the void type.
For example

function dd($data):void{

echo ‘<pre>’;

var_dump($data);

echo ‘</pre>’;

}
PHP strict_types
Type hints allow you to declare types for function parameters and return values.
For example:
function add( int $x , int $y){
return $x + $y;
}
echo add (1.5 , 2.5 ); // 3
In this example, the add() function accepts two integers and returns the sum of
them. However , when you pass two floats 1.5 and 2.5 , the add() function returns
3 because PHP implicitly convert the values to the target types by default.
In this case, PHP convert the floats into integers.
Con’t
To enable strict typing, you can use the declare( strict_types = 1 ); directive ate
the beginning of the file like this:
declare(strict_types = 1);
function add( int $x , int $y ) {
return $x + $y;
}
echo add( 1.5, 2.5 );
Fatal error: Uncaught TypeError: Argument 1 passed to add() must be of the type
int, float given , called in …
PHP Variadic Functions
So far , you’ve learned how to define functions that accept a fixed number of
parameters. A variadic function accepts a variable number of parameters.

The following example defines a function called sum() that returns the sum of
two integers:

function sum ( int $x , int $y ) {

return $x + $y;

echo sum(10 , 20 ); // 30
Con’t
To allow the sum() function to accept a variable of arguments , you need to use func_get_args()
function. The func_num_args() function returns an array that contains all function arguments.
For example:
function sum(){
$numbers = func_get_args();
$total = 0;
foreach($numbers as $n){
$total += $n;
}
}
echo sum(10,20); echo sum(10,20,30);
Con’t
In the previous example, we don’t specify any parameter for the sum() function .
When calling the sum() function , we can pass any number of arguments into it.

Inside the function, the func_get_args() returns an array that contains all the
arguments. To sum up all the arguments, we use a foreach loop.

PHP 5.6 introduced the … operator. When you place the … operator in front of a
function parameter, the function will accept a variable number of arguments, and
the parameter will become an array inside the function. For example:
Con’t
funcion sum(...$numbers){

$total = 0;

foreach($numbers as $n){

$total += $n;

return $total;

echo sum(10, 20 ) ; // echo sum(10,20,30);


Con’t
PHP 7 allows you to declare types for variadic arguments. For example,
function sum( int …$numbers): int{
$total = 0;
foreach($numbers as $n){
$total += $n;
}
return $total;
}
In this example , the sum() function will accept only integers and return the sum of
integers.
PHP Section 7 : Arrays
PHP Arrays
● Indexed arrays
● Associative arrays
● Foreach Loop
● unshift()
● push()
● pop()
● shift()
● keys()
● in_array()
● array_revese()
● array_merge
PHP Arrays
An array is a list of elements. So, for example, you may have an array that
contains a list of products.

PHP provides you with two types of arrays: indexed and associative.

The keys of the indexed array are integers that start at 0. Typically , you use
indexed arrays when you want to access the elements by their positions.

The keys of an associative array are strings. And you use associative arrays when
you want to access elements by string keys.
Creating Arrays
In PHP , you can use the array() construct of [] syntax to define an array. The []
syntax is shooter and more convenient.

1. Creating an array using array() construct

To define any array, you use the array() construct. The following example
creates an empty array:

<?php

$empty_array = array();
Con’t
To create an array with some initial elements, you place a comma-separated list
of elements within parentheses of the array() construct.

For example, the following defines an array that has three numbers:

<?php

$scores = array(1,2,3);
2 . Creating an array using the [] syntax
PHP provides a more convenient way to define arrays with the shorter syntax [],
known as JSON notation. The following example uses [] syntax to create a new
empty array:

<?php

$empty array = [];

The following example uses the [] syntax to create a new array that consists of
three numbers:

<?php

$scores = [1,2,3];
Displaying arrays
To show the contents of an array, you use the var_dump() function. For example:

<?php

$scores = [1,2,3];

var_dump($scores);

Or you can use the print_r() function:

print_r($scores);
Accessing array elements
To access an element in an array, you specially the index of the element within
the square brackets:

$array_name[index]

Note that the index of the first element of an array begins with zero , not one.

The following example shows how to access the first element of the array:

<?php

$scores = [1,2,3];

echo $scores[0];
Adding an element to the array
To add an element to an array, you use the following syntax:
$array_name[] = new_element;
PHP will calculate the highest numerical index plus one each time you assign an
element to the array.
The following example shows how to add the number 4 to the $scores array:
<?php
$scores = [1,2,3];
$scores[] = 4;
It’s possible to use an index when you add a new element to the array. For
example, $scores[3] = 4;
Changing array elements
The following statement changes the element located at the index to the
$new_element:

$array_name[index] = $new_element;

For example, to change the first element of the $scores array from 1 to zero, you
do it as follows:

<?php

$scores = [1,2,3];

$scores[0] = 0;
Removing array elements
To remove an element from an array , you use the unset() function. The following
removes the second element of $scores array:

<?php

$scores = [1,2,3];

unset($scores[1]);
Getting the size of an array
The get the number of elements in an array, you use the count() function. For
example:

<?php

$scores = [ 1, 2, 3, 4, 5 ];

echo count($scores);

//Output - 5
PHP Associative Arrays
Associative arrays are arrays that allow you keep track of elements by names
rather than by numbers.

Creating an associative arrays

To create an associative array, you use the array() construct:

<?php

$html = array();

Or the JSON notation syntax:

$html = [];
Adding elements to an associative array
To add an element to an associative array, you need to specify a key. For example,
the following adds the title and description to the $html array:

<?php

$html[‘title’] = ‘PHP Associative Arrays’;

$html[‘description’] = ‘Learn how to use associative arrays in PHP’;

print_r($html);
Accessing elements in an associative array
To access an element in an associative array, you use the key. For example, the
following shows how to access the element whose key is title in the $html array:

<?php

$html[‘title’] = ‘PHP Associative Arrays’;

echo $html[‘title’];
PHP foreach
PHP provides you with the foreach statement that allows you to iterate over
elements of an array, either an indexed array or an associative array.

The foreach statement iterates over all elements in an array, one at a time. It
starts with the first element and ends with the last one. Therefore, you don’t
need to know the number of elements in an array upfront.
Flowchart of Foreach
PHP foreach with indexed arrays
To iterate over all elements of an indexed array, you use the following syntax:

<?php

foreach ( $array_name as $element ) {

// process element here

}
Cont’
<?php

$colors = [ ‘red’ , ‘green’ , ‘blue’ ];

foreach( $colors as $color ) {

echo $color. ‘<br>’;

}
PHP foreach with an associative array
To iterate over elements of an associative array, you use the following syntax:

<?php

foreach( $array_name as $key => $value ) {

//process key and value here

}
Con’t
$capitals = [

‘Japan’ => ‘Tokyo’,

‘France’ => ‘Paris’,

‘Germany’ => ‘Berlin’

];

foreach ($catitals as $country => $capital){

echo “The capital city of $country is $capital”. “<br>”;

}
Array Methods
● unshift()
● push()
● pop()
● shift()
● keys()
● in_array()
● array_revese()
● array_merge()
Introduction to the PHP array_unshift() function
To prepend one or more elements to an array, you use the array_unshift()
function:

array_unsift(array &$array, mixed … $values) : int

In this syntax:

● $array is the input array


● $values is the values to prepend

The array_unshift() returns the new number of elements in the array.


Example
$permissions = [

‘edit’,

‘delete’,

‘view’

];

array_unshift($permissions, ‘new’);

print_r($permissions);
How it works
● First, define an array with three elements
● Second, prepend the ‘new’ element to the beginning of the array.
● Third, show the elements of the array using the print_r() function.
Prepend three elements
$permission = [

‘edit’ ,

‘delete’,

‘view’

];

array_unshift($permissions, ‘new’ , ‘approve’ , ‘reject’ );

print_r($permissions);
Prepending an element to the beginning of an
associative array
To prepend an element to an associative array, you use + operator. For example:
<?php
$colors = [
‘red’ => ‘#ff0000’,
‘green’ => ‘#00ff00’,
‘blue’ => ‘#0000ff’
];
$colors = [‘black’ => ‘#000000’] + $colors;
print_r($colors)
PHP array_push
The array_push() function adds one or more elements to the end of an array. The
syntax of the array_push() function is as follows:

array_push( array &$array , mixed … $values ) : int

In this syntax:

● $array is the input array.


● $values is one or more elements to push onto the end of the input array.

The array_push() function returns the new number of elements in the array.
PHP array_push() function examples
<?php

$numbers = [1,2,3];

array_push($numbers, 4,5);

print_r($numbers);
Push an element to the end of an associative
array
To add an element to an associative array, you use the following syntax:
$array[key] = values;
$roles = [
‘admin’ => 1,
‘editor’ => 2
];
$roles[‘approver’] = 3;
print_r($roles);
PHP array_pop
The array_pop() function removes an element from the end of an array and
returns that element.

Here’s the syntax of the array_pop() function:

array_pop( array &$array ) : mixed

In the syntax, the $array is the input array from which to return the last element.

If the input array is empty , the array_pop() function returns null.


PHP array_pop() function example
<?php

$numbers = [1,2,3];

$last_number = array_pop($numbers);

echo $last_number;

print_r($numbers);
PHP array_shift
The array_shift() function removes the first element from an array and returns it.

The following shows the syntax of the array_shift() function:

array_shift(array &$array): mixed

In this syntax, the $array is the input array from which you want to remove the
first element. If the $array is empty or is not an array, the array_sift() function
returns null.
PHP array_shift() function example
<?php

$numbers = [1,2,3];

$first_number = array_shift($numbers);

print_r($numbers);
PHP array_keys
The PHP array_keys() function accepts an array and returns all the keys or a
subset of the keys of the array.
Array_keys ( array $array, mixed $search_value , bool $strict = false )
In this syntax:
● $array is the input array.
● $search_value specifies the value of the keys to search for.
● $strict if it sets true, the array_keys() function uses the identical operator(
=== ) for matching the search_value with the array keys. Otherwise, the
function uses the equal ( == ) for matching.
The array_keys() function returns an array that contains all the keys in the input
array.
PHP array_keys() function examples
<?php

$numbers = [10,20,30];

$keys = array_keys($numbers);

print_r($keys);
Con’t
<?php

$numbers = [10,20,30];

$keys = array_keys($numbers , 20 );

print_r($keys);
PHP array_key_exists
The PHP array_key_exists() function checks if a key exists in an array. Here’s the
syntax of the array_key_exists() function:

array_key_exists ( string | int $key , array $array ) : bool

In this syntax:

● $key is the key to check


● $array is an array with keys to check

The array_key_exists() function searches for the key in the first dimension of the
$array only.
PHP array_key_exists() function example
$roles = [

‘admin’ => 1,

‘approver’ => 2,

‘editor’ => 3,

‘subscriber’ => 4

];

$result = array_key_exists(‘admin’ , $roles);

var_dump($result); // bool(true)
PHP in_array
The in_array() function returns true if a value exists in an array. Here’s the syntax
of the in_array(function):

in_array( mixed $needle, array $haystack, bool $strict = false ) : bool

In this syntax:

● $needle is the searched value


● $haystack is the array to search
● $strict if the $strict sets to true, the in_array function will use the strict
comparison. ( default -> false == , true === )
PHP in_array() function examples
$actions = [

‘new’ , ‘edit’ , ‘update’ , ‘view’ , ‘delete’

];

$result = in_array(‘update’, $actions );

var_dump($result); // bool (true)


Con’t
<?php

$user_ids = [10, ‘15’ , ‘20’ ,30];

$result = in_array(15,$user_ids , true);

var_dump($result); // bool(false)
PHP array_reverse
The array_reverse() function accepts an array and returns a new array with the
order of elements in the input array reversed).

The following shows the array_reverse() function:

array_reverse ( array $array, bool $preserve_keys = false ) : array

The array_reverse() function has two parameters:

● $array is the input array


● $preserve_keys determines if the numeric keys should be preserved. If the
$presever_keys is true, the numeric key of elements in the new array will be
preserved. The $preservied_keys doesn’t affect the non-numeric keys:
PHP array_reverse() function examples
<?php

$numbers = [10,20,30];

$reversed = array_reverse($numbers);

print_r($reversed); // new array

print_r($numbers); // original array


Using the PHP array_reverse() function to
preserve numeric keys
<?php
$book = [
‘PHP Awesome’,
999,
[‘Programming’, ‘Web Development’],
];
$preserved = array_reversed($book,true);
print_r($preserved);
Con’t
PHP array_merge
To merge one or more array into an array, you use the array_merge() function:

array_merge( array …$arrays) : array


Example 1
$server_side = [‘PHP’];

$client_side = [‘Javascript’, ‘CSS’ , ‘HTML’];

$full_stack = array_merge($server_side , $client_side);

print_r($full_stack);
Using array_merge() function with string keys
$before = [

‘PHP’ => 2,

‘JavaScript’ => 4,

‘HTML’ => 4,

‘CSS’ => 3

];

after = [

‘PHP’ => 5,

‘Javascript’ => 5,

‘MySQL’ => 4,

];
Con’t
$skills = array_merge($before, $after);

print_r($skills);
Section 8 - Sorting
Arrays
Sorting Arrays
● sort
● ksort()
PHP array sort() function
The sort() function sorts the elements of an array in place in ascending order. The
following shows the syntax of the sort() function:
sort(array &$array, int $flags = SORT_REGULAR) : bool
The sort() function has two parameters:
● $array is the input to sort
● $flag argument is one or a combination of multiple flags that change the sorting
behavior of the function.
The $flags parameter defaults to SORT_REGULAR. It means that the function will
compare elements of the input array using comparison operators.
The combine multiple flags, you use | character, for example, SORT_STRING |
SORT_FLAG_CASE . The sort() function returns true on success or false on failure.
PHP array sort function examples
<?php

$numbers = [2,1,3];

sort($numbers);

print_r($numbers);

This example uses the SORT_REGULAR flag.


Con’t
The following examples use the sort() function to sort an array of strings
alphabetically:

<?php

$names = [ ‘Bob’ , ‘John’ , ‘Alice’];

sort($names,SORT_STRING);

print_r($names);

This example uses the SORT_STRING flag that compares array elements as
strings.
Con’t
The following example uses the sort() function to sort an array of strings:

<?php

$fruits = [ ‘apple’ , ‘Banana’ , ‘orange’];

sort($fruits);

print_r($fruits);
Con’t
To sort an array of strings case-insensitively , you combine the SORT_STRING
flat with the SORT_FLAG_CASE flag like this:

<?php

$fruits = [ ‘apple’, ‘Banana’ , ‘orange’];

sort($fruits, SORT_FLAG_CASE | SORT_STRING);

print($fruits);
PHP ksort() function
The ksort() function sorts the elements of an array by their keys. The ksort() is
mainly useful for sorting associative arrays.
The following shows the syntax of the ksort() function:
ksort(array &$array, int $flags = SORT_REGULAR) : bool
The ksort() function has two parameters:
● $array is the input array
● $flags changes the sorting behavior using one or more values
SORT_REGULAR, SORT_NUMERIC, SORT_STRING,
SORT_LOCAL_STRING,SORT_NUATRUAL, and SORT_FLAG_CASE
The ksort() function returns true on success or false on failure.
PHP krsort() Function
The krsort() function is like the ksort() function except that it sorts the keys of an
array in descending order:

krsort(array &$array, int $flags = SORT_REGULAR) : bool


Section 9
Advanced Function
Advanced Functions
● Anonymous function
● Arrow Function
● Variable Function
Introduction to anonymous functions
When you define a function, you specify a name for it. Later , you can call the
function by its name.
For example, to define a function that multiplies two numbers, you can do it as
follows:
<?php
function multiply($x,$y){
return $x * $y;
}
multiply(10,20); // calling the function
Con’t
An anonymous function is a function that doesn’t have a name.
The following example defines an anonymous function that multiplies two
numbers:
<?php
function ($x,$y) {
return $x * $y;
};
Since the function doesn’t have a name, you need to end it with a semicolon ( ; )
because PHP treats it as an expression
Con’t
This anonymous function is not useful at all because you cannot use it like a
named function.
To use an anonymous function , you need to assign it to a variable and call the
function via the variable.
The following example assigns the anonymous function to the $multiply variable:
<?php
$multiply = function($x,$y){
return $x * $y;
};
echo $multiply( 10 , 20);
Passing an anonymous function
PHP has many built-in functions that accept a callback function, for example , the
array_map() function.

The array_map() function accepts a callback function and an array. It applies the
callback function to each element and includes the results in a new array.

The following example shows how to double each number in an array:


Con’t
function double_it( $element ) {

return $element * 2;

$list = [ 10 , 20 , 30 ];

$double_list = array_map( double_it , $list );

print_r($double_list);
By passing the anonymous function
$list = [10 , 20 , 30 ];

$results = array_map( function ($element) {

return $element * 2;

} , $list);

print_r($results);
Scope of the anonymous function
<?php

$message = ‘Hi’;

$say = function () {

echo $message;

};

$say(); // will generate error


Con’t
To use the variables from the parent scope inside an anonymous function , you
place the variables in the use construct as follows.

<?php

$message = ‘HI’ ;

$say = function ( ) use ($message){

echo $message;

};

$say();
Con’t
<?php

$message = ‘Hi’;

$say = function ( ) use ($message){

$message = ‘Hello’; // This will not change the original value

echo $message;

};

$say();

echo $message;
PHP Arrow Functions
PHP 7.4 introduced the arrow functions that provide a more concise syntax for the anonymous
functions.
The following illustrates the basic syntax for arrow functions:
fn ( arguments ) => expression;
In this syntax, an arrow function
● Start with the fn keyword.
● Can have only one expression and return this expression.
The arrow function is functionally equivalent to the following anonymous function:
function ( arguments ) { return expression; }
Unlike anonymous functions , arrow functions can automatically access variables from their
parent scopes.
PHP arrow function examples
<?php

$eq = fn ( $x , $y ) => $x == $y;

echo $eq(100, ‘100’ ); // 1 ( or true )

How it works.

● First, define an arrow function and assign it to the $eq variable. The arrow
function returns true if the two arguments are equal.
● Second, call the arrow function via the $eq variable
Pass an arrow function to a function example
$list = [ 10 , 20 , 30 ];

$results = array_map(

fn ( $item ) => $item * 2,

$list

);

print_r( $results );
Return an arrow function from a function
function multiplier ( $x ) {

return fn ( $y ) => $x * $y;

$double = multiplier ( 2 );

echo $double(10); // 20
PHP Variable Functions
Variable functions allow you to use a function like a function. When you append
parentheses () to a variable, PHP will look for the function whose name is the
same as the value of the variable and execute it. For example,

<?php

$f = ‘strlen’;

echo $f(‘Hello’);

Output : 5
Con’t
If PHP cannot find the function name , it’ll raise an error. For example,

<?php

$f = ‘len’;

echo $f(‘Hello’);

Error: This will generate error


PHP Section 10
Variable Constructs
Variable Constructs
● isset - return true if a variable is set and not null
● empty - returns true if a variable doesn’t not exist or is false
● is_null - returns true if a variable doesn’t not exist or is null
PHP isset() construct
PHP isset() returns true if a variable is set and not null.

isset(mixed $var): bool

The isset() is a language construct , not a function . Therefore , you cannot assign
it to a variable, return it from a function or call it dynamically via a variable
function.

The following example will result in an error:

<?php

$f = isset;
Con’t
To work around it, you can create a function that uses the seet() construct and
call that function using the variable functions. For example:

<?php

function isset_and_not_null($var): bool {

return isset($var);

}
Using PHP isset with array
If you pass an array element to isset(), it’ll return true. For example,

<?php

$colors = [‘primary’ => ‘blue’]; // ‘secondary’ => null

var_dump(isset($colors[‘primary’]));

Output: bool(true)

var_dump(isset($colors[‘secondary’]));
Con’t
The asset() accepts multiple variables and returns true if all variables are set.
The isset() evaluates the variables from left to right and stops when it encounters
an unset variable.
isset(mixed $v1 , mixed $v2 , … ) bool
The following example returns true because all variables $x, $y and $z are set:
<?php
$x = 10;
$y = 20; // what if $y == null; then isset will return false
$z = 30;
var_dump(isset($x,$y,$z));
Summary
● isset() is a language construct , not a function
● isset() returns true if a variable is set and not null.
● isset() returns true if an array element exists an not null.
● isset() returns true if a string index valid or false otherwise
● isset() return true if all variables are set and not null. It’ll stop evaluating
once it encounter an unset variable.
PHP empty
The empty() construct accepts a variable and return true if the variable is empty.
Otherwise, it returns false.

empty(mixed $v): bool

A variable is empty when if it doesn’t exist of if its value is equal to false. In other
words, a variable that is not set is empty or its value equals the following:
Con’t
The false

The integer 0

The float 0.0 and -0.0

The String “0”

The empty String ‘’

An array with no element

null
Con’t
Like the isset() construct, the empty() is a language construct , not a function().
Therefore, you cannot call it using variable functions.

However , you can work around it by defining a function that uses the empty()
construct and call that function using variable functions:
<?php
function not_exist_or_false($var):bool{
return empty($var);
}
When to use the PHP empty() construct
In practice, you use the empty() construct is the situation that you’re not sure if a
variable even exists.

For example, suppose you receive an array $data from an external source. E.g. an
API call or a database query.

To check if the $data array has an element with the key ‘username’ and it is not
empty, and you may use the following expression:

isset($data[‘username’] && $data[‘username’] !== ‘’)

However, it’s shorter you use the empty() construct:

!empty($data[‘username’]);
Summary
Use the PHP empty() construct to check if a variable is not set or it’s value is false
PHP is_null
PHP is_null() accepts a variable and returns true if that variable is null. Otherwise
, it returns false.

is_null(mixed $v) : bool

For example

$count = 1;

var_dump(is_null($count));
PHP is_null() with array
The following example uses the is_null() to check if the element with key link is
null or not. It returns true because the element doesn’t exist:

<?

$colors = [

‘text’ => ‘black’,

‘background’ => ‘white’

];

var_dump(is_null($colors[‘link’])); // will return a notice


PHP is_null() with string index
The following example uses the is_null() to check if the element at index 5 in the
string $message is null or not.

<?php

$message = “Hello”;

var_dump(is_null($message[5])); // will generate a notice


Summary
The is_null() checks a value and returns true if that value is null. Otherwise, it
returns false.
Section 11
Advanced Array Operations
Advanced Array Operations
● Map - map array elements using the array_map() function
● Filter - filter the elements of an array by a callback using the
array_filter() function
● Reduce - reduce an array to a single value by a callback function using
the array_reduce()
Introduction PHP array_map() function
Suppose that you have an array that holds the lengths of squares:

<?php

$lengths = [10,20,30];

To calculate the areas of squares, you came up with the foreach loop like
this:
Con’t
<?php

$lengths = [10,20,30];

$areas = [];

foreach($lengths as $length ) {

$areas[] = $length * $length;

print_r($areas);
Con’t
Alternatively , you can use the array_map() function that achieves the same
result:

<?php

$areas = array_map( function($length){

return $length * $length;

},$lengths);

print_r($areas);
Con’t
From PHP 7.4 , you can use an arrow function instead of an anonymous function
like this:

<?php

$areas = array_map(

fn($length) => $length * $length,

$lengths

);

print_r($areas);
Introduction to PHP array_filter() function

When you want to filter elements of an array, you often iterate over the
elements and check whether the result array should include each element.

The following example uses the foreach statement to iterate over the elements
of the $numbers array and filter the odd numbers:
Con’t
<?php

$numbers = [1, 2, 3, 4, 5];

$odd_numbers = [];

foreach ($numbers as $number) {

if ($number % 2 === 1) {

$odd_numbers[] = $number;

} // print_r($odd_numbers);
The array_filter() function makes the code more
expressive:
<?php

$numbers = [1, 2, 3, 4, 5];

$odd_numbers = array_filter(

$numbers,

function ($number) {

return $number % 2 === 1;

); // print_r($odd_nubmers);
Con’t
From PHP 7.4, you can use the arrow function instead of the anonymous function like this:

<?php
$numbers = [1, 2, 3, 4, 5];
$odd_numbers = array_filter(
$numbers,
fn ($number) => $number % 2 === 1
);
print_r($odd_numbers);
Introduction to the PHP array_reduce() function
The array_reduce() function reduces an array to a single value using a callback
function. It’s easier to understand the array_reduce() function by example.

The following example calculate the sum of all numbers in an array:

<?php

$numbers = [10,20,30];

$total = 0;

foreach ($numbers as $number) {

$total += $number;

} // echo $total
Con’t
Alternatively, you can use the array_reduce() function to achieve the same
result without using the foreach statement:

<?php

$numbers = [10,20,30];

$total = array_reduce($numbers, function ($previous, $current) {

return $previous + $current;

});

echo $total; // 60
Con’t
Since PHP 7.3, you can use an arrow function rather than an anonymous
function as the callback function like this:

<?php

$numbers = [10,20,30];

$total = array_reduce(

$numbers,

fn ($previous, $current) => $previous + $current

);
PHP Section 12
Organizing PHP Files
PHP Organizing Files

● include
● include_once
● require & require_once
● Using __DIR__ with a file include
include Construct
The include construct allows you to load the code from another file into a file.
Here’s the syntax of the include construct:
include 'path_to_file';
In this syntax, you place the path to the file after the include keyword. For
example, to load the code from the functions.php file into the index.php file,
you can use the following include statement:
<?php

// index.php file
include 'functions.php';
Con’t
If PHP cannot find the 'functions.php' file in the src directory, it’ll issue a warning.
For example:

Warning: include(functions.php): failed to open stream: No such file or directory


in ... on line 4

Warning: include(): Failed opening 'functions.php' for inclusion


(include_path='\xampp\php\PEAR') in ... on line 4
Con’t
When PHP loads the functions.php file, it actually executes the code inside the functions.php
file. For example, if you place the following code in the functions.php file:

<?php

// functions.php

function get_copyright()

return 'Copyright &copy; ' . date('Y') . ' by Let’s Learn Programming. All Rights Reserved!';

echo get_copyright();
Con’t
and include the functions.php in the index.php file, you’ll see the following
output when you run the index.php file:

Copyright © 2021 by Let’s Learn Programming. All Rights


Reserved!
include_once
In the include tutorial, you learned how to load the code from another file using
the include construct.

Sometimes, you may have a file that is included more than once.

If the included file has a function, you’ll get a fatal error because the function is
already redeclared in the first load. For example:
function.php
<?php

function dd($data)

echo '<pre>';

var_dump($data);

echo '</pre>';

die();

}
index.php
<?php
include 'function.php';
include 'function.php';
PHP will issue the following error if you run the index.php file:
To avoid including a file more than once, you can use the include_once
statement:
include_once 'path_to_file';

include 'function.php';
include 'function.php';
Con’t
Image that you have a file called index.php that loads two other files:

● Logger.php
● Database.php

The Database.php file also loads the Logger.php file. In this case, the
Logger.php file is used twice, once in the Database.php file and another in the
index.php.
Con’t
require and require_once Construct
Same as include and include_once.

Summary

● Use require construct to load the code from another file into the script.
● Use require_once construct to load the code from another file once and
won’t include the file again if the file has been loaded.
● The require and require_once are language constructs, not functions.
__DIR__
PHP 5.3 introduced a new magic constant called __DIR__. When you reference
the __DIR__ inside a file, it returns the directory of the file. The __DIR__ doesn’t
include a trailing slash e.g., / or \ except it’s a root directory.

When you use the __DIR__ inside an include, the __DIR__ returns the directory of
the included file.
For example - test_dir.php

include __DIR__ . "/widget/header.php";

echo "<p>".__DIR__."</p>";

include __DIR__ . "/widget/footer.php";


widget/header.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,
initial-scale=1.0">
<title>PHP __DIR__ Demo</title>
</head>
<body>
<?php echo __DIR__; ?>
widget/footer.php
<p><?= __DIR__ ?></p>
</body>
</html>
Summary
__DIR__ is used to get the current file’s directory
Section 13
State Management
State Managements
● cookie
● session
cookie
The web works based on the HTTP protocol. The HTTP protocol is stateless.

When the web browser requests a page from a web server, the web server
responds with the page content. Later, the same web browser requests the
same page again, and the webserver has no information that the request is
from the same web browser.

Cookies solve this stateless challenge.

A cookie is a piece of data that a web server sends to the web browser. The
web browser may store it and send it back in the subsequent requests to the
same web server. The web server knows that two requests come from the
same web browser by using the same cookie.
Con’t
Cookies are also known as web cookies, HTTP cookies, or browser cookies.
We’ll use the cookies to make it short.

The following flow chart illustrates how cookies work:


How it works?
● First, the web browser sends a request to the web server. The web server
doesn’t have any information about the web browser. The web server creates a
cookie with a name return and a value 1 and attaches the cookie to the HTTP
response header. To create a cookie, you’ll use the setcookie() function.
● Second, the web browser stores the cookie.
● Third, the web browser sends the second request with the stored cookie in the
header of the HTTP request to the web server. On the web server, PHP can
access the cookie via the $_COOKIE superglobal variable and do something
accordingly.
● Finally, the web server responds with the content of the request. Typically, it
responds to the web browser with the content based on the value of the
cookie.
Con’t
A web browser can store a cookie with a maximum size of 4KB. However, it’s
different between web browsers.

A cookie has an expiration date. Typically, web browsers store cookies for a
specific duration. And the web server can specify the expired time for a cookie.

A cookie also stores the web address (URL) that indicates the URL which
created the cookie. And the web browser can send back the cookie that was
originally set by the same web address. In other words, a website won’t be able
to read a cookie set by other websites.

Most modern web browsers allow users to choose to accept cookies.


Therefore, you should not wholly rely on cookies for storing critical data.
Why using Cookies?
In general, websites use cookies to enhance user experiences. For example,
you would have to log in to a website again after you leave it without cookies.
Typically, you’ll use cookies for the following purposes:
● Session management: cookies allow a website to remember users and
their login information or anything else that the web server should
remember.
● Personalization: cookies can store user’s preferences, themes, and other
settings.
● Tracking: cookies store user behavior. For example, on an Ecomerce
website, you can use cookies to record the products that users previously
viewed. Later, you can use this information to recommend the related
products that users might be interested in.
Setting a Cookie in PHP
PHP makes it easy to work with cookies using the setcookie() function. The
setcookie() function allows you to send an HTTP header to create a cookie on
the web browser.
Con’t
<?php
setcookie (
string $name ,
string $value = "" ,
int $expires = 0 ,
string $path = "" ,
string $domain = "" ,
bool $secure = false ,
bool $httponly = false
): bool
The following table illustrates the arguments of the setcookie() function:
Con’t
Con’t
As of PHP 7.3.0, you can use the same setcookie() function with an alternative
signature:

setcookie (

string $name ,

string $value = "" ,

array $options = [] ) : bool


Con’t
The $options argument is an array that has one or more keys, such as expires,
path, domain, secure, httponly and samesite.

The setcookie() function returns true if it successfully executes. Notice that it


doesn’t indicate whether the web browser accepts the cookie or not. The
setcookie() function returns false if it fails.
$_COOKIE
The $_COOKIE an associative array that stores the HTTP cookies. To access a
cookie by a name, you use the following syntax:

$_COOKIE['cookie_name']

To check if a cookie is set, you use the isset() function:

if(isset($_COOKIE['cookie_name'])) {

}
Reading a Cookie
Before reading a cookie value, you should always check if it has been set by
using the isset() function

<?php

if (isset($_COOKIE['cookie_name'])) {

// process the cookie value

}
To check if a cookie equal a value

if (isset($_COOKIE['cookie_name']) &&
$_COOKIE['cookie_name'] == 'value') {

// ...

}
Deleting a cookie
If you don’t use a cookie, you can force the browser to delete it. PHP doesn’t
provide a function that directly deletes a cookie. However, you can delete a
cookie using the setcookie() function by setting the expiration date to the past.

The following code deletes a cookie with the cookie_name in the subsequent
page request:

unset($_COOKIE['cookie_name']);

setcookie('cookie_name', null, time()-3600);


PHP cookie example
The following example shows how to use a cookie to display a greeting
message to a new or returning visitor.
<?php

define('ONE_WEEK', 7 * 86400);

$returning_visitor = false;

if (!isset($_COOKIE['return'])) {

setcookie('return', '1', time() + ONE_WEEK);

} else {

$returning_visitor = true;

echo $returning_visitor ? 'Welcome back!' : 'Welcome to my website!';


Con’t
And if you open the web developer tool, you’ll see the cookie as shown in the
following picture:
Introduction to PHP Sections
The HTTP protocol is stateless. For example, when you visit the product page
product.php, the web server responds with the page:
Con’t
Suppose, you click the add to cart button on the product.php page and
navigate to the cart.php page, the web server won’t know that you have added
the product to the cart.

To persist the information across the pages, the web server uses sessions. In
this example, when you click the add to cart button, the web server will store
the product on the server.

When you view the cart.php page, the web server gets the products from the
session and displays them on the cart.php page:
Con’t
Create a new Session
To create a new session, you call the session_start() function:

<?php

session_start();
Where the PHP session data store
By default, PHP stores session data in temporary files on the web server. You
can find the location of the temporary files using directive session.save_path in
the PHP configuration file.
The ini_get() function returns the value of the session.save_path directive:
<?php
echo ini_get('session.save_path');
Or you can use
echo session_save_path();
Typically, the session data is stored in the /tmp folder of the web server e.g,
/xampp/tmp .
Accessing session data
Unlike cookies, you can store any data in the session. To store data in the
session, you set the key and value in the $_SESSION superglobal array.

For example, in the index.php file, you store the user string and roles array in
the session as follows:
Con’t
profile.php
Deleting the session data
Whenever you close the web browser, PHP automatically deletes the session.
Sometimes, you want to explicitly delete a session, e.g., when you click the
logout link. In this case, you can use the session_destroy() function:

<?php

session_destroy();
PHP Section 14
Processing Forms
Processing Forms
● PHP Form
● filter_has_var()
● filter_var()
● filter_input()
● CheckBox
● Multiple CheckBoxes
● Radio Button
● Select
● Flash Message
● File Upload
● Upload Multiple Files
PHP Form
To create a form, you use the <form> element as follows:
<form action="form.php" method="post">
</form>
The <form> element has two important attributes:
● action: specifies the URL that processes the form submission. In this
example, the form.php will process the form.
● method: specifies the HTTP method for submitting the form. The most
commonly used form methods are POST and GET. In this example, the
form method is post.
Con’t
The form method is case-insensitive. It means that you can use either post or
POST. If you don’t specify the method attribute, the form element will use the
get method by default.

Typically, a form has one or more input elements including text, password,
checkbox, radio button, select, file upload, etc. The input elements are often
called form fields.

An input element has the following important attributes name, type, and value.
The name attribute will be used for accessing the value in PHP.
HTTP POST Method
If a form uses the POST method, the web browser will include the form data in
the HTTP request’s body. After submitting the form, you can access the form
data via the associative array $_POST in PHP.
For example, if a form has an input element with the name email, you can
access the email value in PHP via the $_POST['email']. If the form doesn’t have
an email input, the $_POST won’t have any element with the key 'email'.
To check if the form data contains the email, you use the isset() like this:
if(isset($_POST['email']) {
// process email
}
Con’t
The following shows a form with an input element:

<form action="form.php" method="post">


<div>
<label for="email">Email:</label>
<input type="email" id="email" name="email" />
</div>
<button type="submit">Submit</button>
</form>
Con’t
In the form.php file, you can access the email value as follows:

if (isset($_POST['email'])) {

var_dump($_POST['email']);

}
HTTP GET Method
When you submit a form using the GET method, you can access the form data
in PHP via the associative array $_GET.

Unlike the POST method, the GET method appends the form data in the URL
that processes the form. Suppose the URL that processes the form is
http://localhost/form.php. When you enter the email as [email protected]
and submit a form, you’ll see that the email value is appended to the URL like
this:

http://localhost/form.php?email=someone%40gmail.com
Con’t
In PHP, you can use the isset() to check if the form data contains the email:

if(isset($_GET['email']) {

// process email

If the form has multiple input elements, the web browser will append the form
inputs to the URL in the following format:

http://localhost/form.php?name1=value1&name2=value2&name3=
value3
Con’t
The following shows the same form that has an email input. However, the form
uses the GET method instead:
<form action="form.php" method="get">
<div>
<label for="email">Email:</label>
<input type="email" id="email" name="email" />
</div>
<button type="submit">Submit</button>
</form>
Con’t
And the following shows the form.php file:

if (isset($_GET['email'])) {

var_dump($_GET['email']);

Note that both $_POST and $_GET arrays are superglobal variables. It means
that you can access them anywhere in the script.
HTTP GET OR POST
In general, you should use the GET method when the form only retrieves data
from the server. For example, a search form that allows users to search for
information should use the GET method.

When you have a form that causes a change in the server, you should use the
POST method. For example, a form that allows users to subscribe to a
newsletter should use the POST method.
PHP Form Example
index.php
subscribe.php
if (isset($_POST['name'], $_POST[ 'email'])) {

$name = $_POST[ 'name'];

$email = $_POST[ 'email'];

// show the $name and $email

echo "Thanks $name for your subscription.<br>" ;

echo "Please confirm it in your inbox of the email $email." ;

} else {

echo 'You need to provide your name and email address.' ;

}
Escaping the Output
The subscribe.php page directly displays the form data. If malicious hackers
intentionally enter bad data, the page won’t work properly.
For example, if the following JavaScript code is entered in the name field and
the form is submitted.
<script>alert('Hello');</script>
…you’ll see that the page displays an alert.
Imagine that the script doesn’t just show an alert but loads the malicious code
from another server to the user’s web browser, the risk is higher. This type of
attack is called cross-site scripting (XSS) attack.
Therefore, before displaying user input on a webpage, you should always
escape the data. To do that, you use the htmlspecialchars() function:
Con’t
if (isset($_POST['name'], $_POST['email'])) {

$name = htmlspecialchars($_POST['name']);

$email = htmlspecialchars($_POST['email']);

// show the $name and $email

echo "Thanks $name for your subscription.<br>";

echo "Please confirm it in your inbox of the email $email."


;

} else {

echo 'You need to provide your name and email address.';

}
filter_has_var() function
The filter_has_var() function checks if a variable of a specified type exists.
Here’s the syntax of the filter_has_var() function:
filter_has_var ( int $input_type , string $var_name ) : bool

The filter_has_var() function has the following parameter:


● $input_type is the type of input that you want to search for a variable. The
valid input types are INPUT_GET, INPUT_POST, INPUT_COOKIE,
INPUT_SERVER, or INPUT_ENV.
● $var_name is the name of the variable to check.
The filter_has_var() function returns true if the $var_name exists in the
$input_type or false otherwise.
Check the name variable in the post request

if (filter_has_var(INPUT_POST, 'name')) {
echo 'The name variable exists:' .
htmlspecialchars($_POST['name']);
} else {
echo 'The name is required!';
}
filter_has_var vs. isset
The isset() function returns true if a variable is declared and not null. For
example, the following checks if the name variable in the $_POST array:

if(isset($_POST['name'])) {

// process the name

In this example, the isset() checks if the $_POST variable has a key 'name' and
the $_POST['name'] is not null. However, the isset() doesn’t check if the name
variable comes from the HTTP request or not. For example:
Con’t
<?php

$_POST['email'] = '[email protected]';

if(isset($_POST['email'])) { // return true

// ...

In this example, we first manually set the $_POST['email'] to a value. And then
we use the isset() function to check if the email variable exists. As a result, the
isset() function returns true.
Con’t
Unlike the isset() function, the filter_has_var() function doesn’t read the
contents of the $_POST array. It checks the variables in the request’s body.
Therefore, the following example returns false:

<?php

$_POST['email'] = '[email protected]';

if(filter_has_var(INPUT_POST, 'email')) { // return false

// ...

}
filter_var() function
When dealing with external data, you need to sanitize and validate it for
security purposes. The external data may come from user inputs or third-party
API.

A good rule of thumb is that you should never trust external data. And you
should always:

● Sanitize and validate data before storing it in the database.


● Espace data before displaying it on a web page.

Suppose, you have a URL that contains a query string like this:

http://localhost:8080/index.php?id=10
Con’t
And you want to display the $id on the page:

echo $_GET['id'];

In this case, you see that the page displays the number 10.

However, a malicious hacker may change the value of id to something code


like this:

%3Cscript%3Ealert(%27Hi%27)%3C/script%3E

OR

<script>alert(“HELLO”)</script>
Con’t
To prevent this, you need to sanitize and validate data before processing it.

● Sanitization disables potential malicious code from data before


processing it.
● Validation ensures that the data is in the correct format regarding data
type, range, and value.

PHP has the filter_var() function that supports you to both sanitize and validate
data. Here’s the syntax of the filter_var() function:
filter_var ( mixed $value , int $filter = FILTER_DEFAULT ,
array|int $options = 0 ) : mixed
Con’t
The filter_var() function the following parameters:

● $value is the value will be filtered.


● $filter is the filter id to apply. The filter id determines how the filter_var()
function filters the $value.
● $options is an associative array of options or a list of flags separated by
the pipe character (|).

The filter() function returns the filtered value, or false if the filter fails.
Example
if (filter_has_var(INPUT_GET, 'id')) {

// sanitize id

$id = filter_var($_GET['id'],
FILTER_SANITIZE_NUMBER_INT);

// show the id

var_dump($id);

} else {

echo 'id is required.';

}
Con’t
The filter_var() function with the FILTER_SANITIZE_NUMBER_INT filters will
remove all characters except the digits, plus, and minus signs from the id
variable. Check out all the filter ids that you can use to sanitize data.
Using the PHP filter_var() function to validate data
if (filter_has_var(INPUT_GET, 'id')) {

// sanitize id

$clean_id = filter_var($_GET['id'], FILTER_SANITIZE_NUMBER_INT);

// validate id

$id = filter_var($clean_id, FILTER_VALIDATE_INT);

// show the id if it's valid

echo $id === false ? 'Invalid id' : $id;

} else {

echo 'id is required.';

}
PHP filter_input()
The PHP filter_input() function allows you to get an external variable by its
name and filter it using one or more built-in filters.

The following shows the syntax of the filter_input() function:

filter_input ( int $type , string $var_name , int $filter


= FILTER_DEFAULT , array|int $options = 0 ) : mixed
Con’t
The filter_input() function has the following parameters:

● $type is one of INPUT_GET, INPUT_POST, INPUT_COOKIE, INPUT_SERVER, and


INPUT_ENV.
● $var_name is the name of the variable to filter.
● $filter is the filter id to apply. Here’s the list of valid filters. If you omit the $filter
argument, the filter_input() function will use the FILTER_DEFAULT filter id, which
doesn’t filter anything.
● $options is an associative array that consists of one or more options. When a filter
accepts the options, you can use one or more flags. If you want to use multiple
flags, you need to separate them by the (|) e.g., FILTER_SANITIZE_ENCODED |
FILTER_SANITIZE_SPECIAL_CHARS.
Con’t
The filter_input() function returns null, false, or the filtered value according to
the following rules:

● If the $var_name is not set, the filte_input() function returns null.


● If the filter fails, the filter_input() function returns false.
● Otherwise, it returns the filtered value of the requested variable.
PHP filter_input example()
Check box
Multiple CheckBox
Radio Button
Select
Processing Forms
● PHP Form
● filter_has_var()
● filter_var()
● filter_input()
● CheckBox
● Multiple CheckBoxes
● Radio Button
● Select
● Flash Message
● File Upload
● Upload Multiple Files
PHP File Upload
The <input> element with the type="file" allows you to select one or more files
from their storage and upload them to the server via the form submission.
The following shows the file input element:
<input type="file" id="file" name="file">
The value of the <input> element will hold the path to the selected file. To
upload multiple files, you add the multiple attribute to the <input> element like
this:
<input type="file" id="file" name="file" multiple>
Con’t
To allow certain file types to be uploaded, you use the accept attribute. The
value of the accept attribute is a unique file type specifier, which can be:

● A valid case-insensitive file name extension e.g., .jpg, .pdf, .txt


● A valid MIME type string
● Or a string like image/* (any image file), video/* (any video file), audio/*
(any audio file).

If you use multiple file type specifiers, you need to separate them using a
comma (,). For example, the following setting allows you to upload only .png
and .jpeg images:
Con’t
<input type="file" accept="image/png, image/jpeg"
name="file">

The <form> element that contains the file input element must have the enctype
attribute with the value multipart/form-data:

<form enctype="multipart/form-data" action="index.php"


method="post">
</form>

If it doesn’t, the browser won’t be able to upload files.


Handling the file upload in PHP
● To access the information of an uploaded file, you use the $_FILES array.
For example, if the name of the file input element is file, you can access the
uploaded file via $_FILES['file'].
● The $_FILE[‘file’] is an associative array that consists of the following keys:
● name: is the name of the uploaded file.
● type: is the MIME type of the upload file e.g., image/jpeg for JPEG image or
application/pdf for PDF file.
● size: is the size of the uploaded file in bytes.
● tmp_name: is the temporary file on the server that stored the uploaded
filename. If the uploaded file is too large, the tmp_name is "none".
● error: is the error code that describes the upload status e.g.,
UPLOAD_ERR_OK means the file was uploaded successfully
Con’t
The following defines MESSAGES constant that maps the error code with the
corresponding message:
Con’t
The following defines MESSAGES constant that maps the error code with the
corresponding message:

$message = MESSAGES[$_FILES['file']['error']];
Con’t
When a file is uploaded successfully, it is stored in a temporary directory on the
server. And you can use the move_uploaded_file() function to move the file
from the temporary directory to another one.

The move_uploaded_file() function accepts two arguments:

● filename: is the file name of the uploaded file which is


$_FILES['file']['tmp_name'].
● destination: is the destination of the moved file.

The move_uploaded_file() function returns true if it moves the file successfully;


otherwise, it returns false.
Upload Example
if(isset($_FILES['image']['name'])){
//upload the image
$image_name = $_FILES['image']['name'];
$source_path = $_FILES['image']['tmp_name' ];
$destination_path = __DIR_. "/".$image_name ;
//upload the image
$upload = move_uploaded_file ($source_path ,$destination_path );
//check whether the image is uploaded or not
if($upload){
// uploaded successfully
}

}
Upload Multiple Files
for($i = 0; $i < $file_count; $i++) {
$filename = $files['name'][$i];
$source_path = $files['tmp_name'][$i];
$destination_path = __DIR__."/".$file_name;
$upload = move_uploaded_file($source_path,$destination_path);

if($upload){
echo "Multiple File Uploaded Successfully";
}else{
echo "something wrong";
}
}

You might also like