Backend Web Development
Backend Web Development
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
Types of DBMS
● Non-Relational
● Relational
Non-Relational Database Management
System(Non-RDBMS)
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
Here, this SQL command selects the first name and last name of all customers
from the customers table.
Cont
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
● 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
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.
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
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
● 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
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,
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( )
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,
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
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
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,
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 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
● 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.
● 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
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,
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
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( ).
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.
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
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
Before we can work with database tables, we must create a database first.
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
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
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
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,
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
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,
It is important to create database backups regularly so that out data won’t get
lost if the database gets corrupted.
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
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
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
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,
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.
For example,
SQL Constraints
Outlines
● SQL Constraints
● SQL Not Null Constraints
● SQL Unique Constraints
● SQL Primary Key
● SQL Foreign Key
SQL Constraints
SQL Constraints
For example, if a column has NOT NULL constraints, it means the column cannot
store NULL values.
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
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
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
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,
We can also add the UNIQUE constraint to an existing column using the ALTER
TABLE command. For example,
Error When Inserting Duplicate Values
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
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
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.
Here, the SQL command creates two foreign keys(buyer and seller) in the
Transcations table.
SQL Additional Topics
outlines
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
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,
This function is used to get the current timestamp in the system. For example,
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.
● Arithmetic operators
● Comparison operators
● Logical operators
SQL Arithmetic Operators
Comments are descriptions in the SQL code that help users better understand
the intent and functionality of the SQL command.
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
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 ).
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,
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?
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 originally stood for Personal Home Page. However, now , it stands for
Hypertext Preprocessor.
PHP is a sever-side language
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.
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.
● 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:
● 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
● 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
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.
● 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
Therefore, you don’t need to place a semicolon in the last statement in a PHP
block. For example:
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.
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
?>
</body>
PHP is awesome!
Con’t
Another sorter way to show the value of a variable on a page is to use the
following syntax:
<?php
?>
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
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
● 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.
<?php
$rate = 100;
$hours = 173;
<?php
/*
*/
Writing meaningful comments
In this tutorial, you will learn about PHP constants and how to use the define()
function and const keyword to define constants.
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
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 ){
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.
<?php
$balance = 100;
Con’t
<?php
$balance = 100;
var_dump($balance);
If you open the page on the web browser: you’ll see the following output:
<?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
d($message);
die();
Output:
● 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
<?php
$name = ‘John’;
And if you want to show a message that displays -> Hello John
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
echo $title[0]; // P
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’;
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
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
<?php
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 = [
];
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 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
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
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
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:
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”;
● 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;
$x = $y = 20;
Arithmetic assignment operators
Concatenation assignment operator
<?php
$greeting = ‘Hello ’;
$name = ‘John’;
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;
$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;
<?php
$x = 20;
$y = 10;
$x = 20;
$y = ‘20’;
<?php
$x = 10;
$y = 20;
<?php
$x = 10;
$y = 20;
<?php
$x = 20;
$y = 10;
<?php
$x = 20;
$y = 20;
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;
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 = true;
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;
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;
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;
PHP provides you with common arithmetic operators that allow you to perform
addition, subtraction, multiplication, division, exponentiation and modulus
operations.
<?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)
<?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 ){
$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 ) {
// 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 {
}
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 ( 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 ):
elseif ( $x < $y ):
else:
endif;
PHP elseif vs else if
if (expression){ if (expression){
statement; statement;
statement statement
} }
$is_user_logged_in = false;
if( $is_user_logged_in ) {
$title = ‘Logout’;
} else {
$title = ‘Login’;
<?php
Suppose that you’re building a website whose users have many roles like admin ,
editor , author , and subscriber.
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;
$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
$total = 0;
$number = 1;
$total += $number;
$number++;
while ( expression ) :
statement;
endwhile;
Con’t
$total = 0 ;
$number = 1;
$total += $number;
$number++;
endwhile;
<?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
}
For example
<?php
}
PHP foreach with an associative array
<?php
}
Con’t
$capitals = [
];
}
Using PHP break statement in a for loop
<?php
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 ( $k <= 10 ) {
if ( $k === 5 ) {
break;
$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
} }
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){
<?php
function_name();
function welcome(){
echo ‘Welcome!’;
welcome();
Con’t
<?php
function welcome_user($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 } ?>
PHP Function Parameters
A function can have zero or more parameters:
<?php
function function_name(parameter_list) {
<?php
}
Con’t
$greeting = concat(‘Welcome ’, ‘Admin’);
echo $greeting;
PHP Default Parameters
The following concat() function that concatenates two strings with a delimiter:
<?php
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
<?php
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(
$word: ‘awesome’
);
}
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’
);
● 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:
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;
echo $result;
Con’t
More interestingly , you can pass an integer and a numeric string into the add()
function , it will return an integer:
echo $result;
Con’t
If PHP fails to convert the string argument into an integer, it’ll issue an error. For
example:
echo $result;
To add a type hint to a parameter, you place a type in front of it like this:
// ..
}
Con’t
The following defines the add() function that accepts two integers:
return $x + $y;
$result = add(1,2);
echo $result; // 3
PHP type hints for function’s return value
function my_function(type $param1 , type $param2 , … ) : type
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:
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;
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.
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
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);
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.
<?php
$html = array();
$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
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
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
}
Cont’
<?php
}
PHP foreach with an associative array
To iterate over elements of an associative array, you use the following syntax:
<?php
}
Con’t
$capitals = [
];
}
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:
In this syntax:
‘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’
];
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:
In this syntax:
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.
In the syntax, the $array is the input array from which to return the last element.
$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.
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:
In this syntax:
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
];
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 this syntax:
];
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).
$numbers = [10,20,30];
$reversed = array_reverse($numbers);
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);
<?php
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
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
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:
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.
return $element * 2;
$list = [ 10 , 20 , 30 ];
print_r($double_list);
By passing the anonymous function
$list = [10 , 20 , 30 ];
return $element * 2;
} , $list);
print_r($results);
Scope of the anonymous function
<?php
$message = ‘Hi’;
$say = function () {
echo $message;
};
<?php
$message = ‘HI’ ;
echo $message;
};
$say();
Con’t
<?php
$message = ‘Hi’;
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
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(
$list
);
print_r( $results );
Return an arrow function from a function
function multiplier ( $x ) {
$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’);
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.
<?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
return isset($var);
}
Using PHP isset with array
If you pass an array element to isset(), it’ll return true. For example,
<?php
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.
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
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:
!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.
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 = [
];
<?php
$message = “Hello”;
<?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 ) {
print_r($areas);
Con’t
Alternatively , you can use the array_map() function that achieves the same
result:
<?php
},$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(
$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
$odd_numbers = [];
if ($number % 2 === 1) {
$odd_numbers[] = $number;
} // print_r($odd_numbers);
The array_filter() function makes the code more
expressive:
<?php
$odd_numbers = array_filter(
$numbers,
function ($number) {
); // 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.
<?php
$numbers = [10,20,30];
$total = 0;
$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];
});
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,
);
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:
<?php
// functions.php
function get_copyright()
return 'Copyright © ' . 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:
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
echo "<p>".__DIR__."</p>";
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.
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.
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.
setcookie (
string $name ,
$_COOKIE['cookie_name']
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'])) {
}
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']);
define('ONE_WEEK', 7 * 86400);
$returning_visitor = false;
if (!isset($_COOKIE['return'])) {
} else {
$returning_visitor = true;
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:
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'])) {
} else {
}
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']);
} else {
}
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
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'])) {
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]';
// ...
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]';
// ...
}
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:
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.
%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.
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:
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 {
}
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
// validate id
} else {
}
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.
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:
$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.
}
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";
}
}