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

PHP Notes

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

PHP Notes

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

REPUBLIC OF RWANDA

MINISTRY OF EDUCATION

RWANDA TVET BOARD

GLORY ACADEMY

MODULE CODE: SFDWA501

MODULE NAME: WEB APPLICATION DEVELOPMENT

HOURS:120

LEVEL 5 SOFTWARE DEVELOPMENT

TRAINER NAMES: BIZIMANA Mathias

ACADEMIC YEAR:2022-2023
LU1: APPLY PHP FUNDAMENTALS

LO 1.1. Define PHP language and its basics

1.1.1 Introduction to PHP as a scripting language

1. What PHP stands for?

PHP stands for Hypertext Preprocessor, that earlier stood for Personal Home Pages. This confuses
many people because the first word of the acronym is the acronym. This type of acronym is called
a recursive acronym.
2. Purpose of PHP

The PHP is a scripting language that allows web developers to create dynamic content that interacts
with databases. PHP is basically used for developing web-based software applications.

PHP is often used to build dynamic web pages. A dynamic web page is one where each visitor to
the web gets a customized page that can look different than how the site looks to another visitor.
This is in contrast to static web pages which provide the same contents to each visitor.

3.PHP files

PHP files have the. php extension can contain text, HTML tags and scripts (script is a set of
programming instructions that is interpreted at runtime.). These files are processed by a remote
server and are then returned to the user's web browser as plain HTML.

4.PHP program structure

1|Page
A PHP script can be placed anywhere in the document and It starts with

<?php and ends with ?>:

<?php

// PHP code goes here

?>

A PHP file normally contains HTML tags, and some PHP scripting code.

1.1.2 Difference between scripting and programming languages

You can different the scripting and programming languages on the following elements:
1.Server-side processes

The scripting languages needs the server for being processed whereas the programming
languages does not require the server for processing.

2.Compiler and interpreter

Compiler is a translator which takes high level language, and produces an output of low level
language i.e. machine or assembly language. The compiler scans the whole program in one go.

Interpreter is a program that translates a programming language into a comprehensible


language.

For programming languages, the code has to be compiled before it can be executed. This means
that the compiler is needed before the execution.

For scripting languages, the code has to be interpreted before it can be executed. This means that
the interpreter is needed before the execution.

Generally, compiled programs run faster than interpreted programs because they are first converted
native machine code. Also, compilers read and analyze the code only once, and report the errors
collectively that the code might have but the interpreter will read and analyze the code statements
each time it meets them and halts at that very instance if there is some error.
3.Inside HTML files
The scripting languages run inside another program (like PHP runs inside HTML file). It is usually
embedded into other software environments whereas the programming languages run independent
of a parent program.

2|Page
The scripting languages require a host means that they need the servers which are used for
processing the scripts before the output whereas the programming languages does not require a
host. They are self-executable.

LO 1.2 Describe PHP Syntax, data types, variables, operators and arrays

1.2.1 Variable declaration

Variables are used to store a value that can change during the program execution.

Rules for PHP variables:

 A variable starts with the $ sign, followed by the name of the variable.
 A variable name must start with a letter or the underscore character.
 A variable name cannot start with a number.
 A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9,
and _ )
 Variable names are case-sensitive ($option and $OPTION are two different variables)
 The assignment operator (=) used to assign value to a variable.

In PHP variable can be declared as: $var_name = value;


Example:
<?php
// Declaring variables
$txt = "Hello World!";
$number = 10;

// Displaying variables value


echo $txt; // Output: Hello World!
echo $number; // Output: 10
?>

1.2.2 Primitive data types

PHP supports total eight primitive data types: Integer, Floating point number or Float, string,
booleans, array, object, resource and null. These data types are used to construct variables.

1.Integers
Integers are whole numbers, without a decimal point (..., -2, -1, 0, 1, 2, ...). Integers can be
specified in decimal (base 10), hexadecimal (base 16 - prefixed with 0x) or octal (base 8 -
prefixed with 0) notation, optionally preceded by a sign (- or +).

3|Page
Example:
<?php
$a = 123; // decimal number
echo $a;
echo "<br>";

$b = -123; // a negative number


echo $b;
echo "<br>";

$c = 0x1A; // hexadecimal number


echo $c;
echo "<br>";

$d = 0123; // octal number


echo $d;
?>
Note: Since PHP 5.4+ you can also specify integers in binary (base 2) notation. To use binary
notation, precede the number with 0b (e.g. $var = 0b11111111;).
Example:

<?php
$var = 0b11111111;
echo $var;
?>

2.Strings
Strings are sequences of characters, where every character is the same as a byte.
A string can hold letters, numbers, and special characters. The simplest way to specify a string is
to enclose it in single quotes (e.g. 'Hello world!'), however you can also use double quotes ("Hello
world!").
Example:
<?php
$a = 'Hello world!';
echo $a;
echo "<br>";

$b = "Hello world!";
echo $b;
echo "<br>";

$c = 'Stay here, I\'ll be back.';

4|Page
echo $c;
?>

3.Floating Point Numbers


Floating point numbers (also known as "floats", "doubles", or "real numbers") are decimal or
fractional numbers.
Example:
<?php
$a = 1.234;
echo $a;
echo "<br>";

$b = 10.2e3;
echo $b;
echo "<br>";

$c = 4E-10;
echo $c;
?>

4.Booleans
Booleans are like a switch it has only two possible values either 1 (true) or 0 (false).

Example
<?php
// Assign the value TRUE to a variable
$show_error = true;
echo $show_error;
?>

5.Arrays
An array is a variable that can hold more than one value at a time. It is useful to aggregate a
series of related items together, for example a set of country or city names.
An array is formally defined as an indexed collection of data values. Each index (also known as
the key) of an array is unique and references a corresponding value.

5|Page
Example

<?php

// Define array

$cities = array("London", "Paris", "New York");

// Display the cities array

var_dump($cities);// array(3) { [0]=> string(6) "London" [1]=> string(5) "Paris" [2]=> string(8)
"New York" }

?>

6.Objects
An object is a data type that not only allows storing data but also information on, how to process
that data. An object is a specific instance of a class which serve as templates for objects. Objects
are created based on this template via the new keyword.
Every object has properties and methods corresponding to those of its parent class. Every object
instance is completely independent, with its own properties and methods, and can thus be
manipulated independently of other objects of the same class.
Here's a simple example of a class definition followed by the object creation.

Example

<?php
class SayHello{
function hello()
{
echo "Hello World";
}
}
$obj=new SayHello;
$obj->hello();
?>
7.Null
The special Null value is used to represent empty variables in PHP. A variable of type Null is a
variable without any data. Null is the only possible value of type null.

6|Page
Example

<?php
$a=NULL;
echo $a;
echo "<br>";

$b="Hello World!";
$b=NULL;
echo $b;
?>

When a variable is created without a value in PHP like $var; it is automatically assigned a value
of null. Many novice PHP developers mistakenly considered both $var1 = NULL; and $var2 =
""; are same, but this is not true. Both variables are different, the $var1 has null value
while $var2 indicates no value assigned to it.

8.Resources
A resource is a special variable, holding a reference to an external resource.
Resource variables typically hold special handlers to opened files and database connections.

Example

<?php
// Open a file for reading
$handle = fopen("note.txt", "r");
var_dump($handle);
echo "<br>";

// Connect to MySQL database server with default setting


$link = mysql_connect("localhost", "root", "");
var_dump($link);
?>

1.2.3 Constants
A constant is a name or an identifier for a simple value. A constant value cannot change during
the execution of the script. By default, a constant is case-sensitive. By convention, constant
identifiers are always uppercase. A constant name starts with a letter or underscore, followed by
any number of letters, numbers, or underscores. If you have defined a constant, it can never be
changed or undefined.

7|Page
To define a constant, you have to use define() function and to retrieve the value of a constant,
you have to simply specifying its name. Unlike with variables, you do not need to have a constant
with a $. You can also use the function constant() to read a constant's value if you wish to obtain
the constant's name dynamically.

PHP introduced a keyword const to create a constant. The constant defined using const keyword
are case-sensitive.

Syntax: define(name, value, case-insensitive)

1. name: It specifies the constant name.


2. value: It specifies the constant value.
3. case-insensitive: Specifies whether a constant is case-insensitive. Default value is false. It
means it is case sensitive by default.

Example1:

<?php

define("MINSIZE", 50);

echo MINSIZE;

echo constant("MINSIZE"); // same thing as the previous line

?>

Example2:

<?php
define("MESSAGE","Hello PHP",true);
echo MESSAGE, "</br>";
echo message;
?>
Example 3:

<?php

const MESSAGE="Hello const by PHP";

echo MESSAGE,"<br>";

?>

8|Page
1.2.4 Operators
PHP language supports following type of operators.

 Arithmetic Operators
 Comparison Operators
 Logical (or Relational) Operators
 Assignment Operators
 Conditional (or ternary) Operators
Let’s have a look on all operators one by one.

i)Arithmetic Operators
There are following arithmetic operators supported by PHP language. Assume variable A holds
4 and variable B holds 2 then

Operator Name Description Example

+ Addition Adds two operands $A + $B will give


6

- Subtraction Subtracts second operand from the first $A - $B will give


2

* Multiplication Multiply both operands $A *$ B will give


8

/ Division Divide numerator by de-numerator $B / $A will give


2

% Modulus Modulus operator and remainder of after an $B % $A will give


integer division 0

++ Increment Increment operator, increases integer value $A++ will give 5


by one

9|Page
-- Decrement Decrement operator, decreases integer value $A-- will give 3
by one

** Exponentiation Result of raising $x to the $y'th power $A**$B will give


16

ii)Comparison Operators
There are following comparison operators supported by PHP language. Assume variable A holds
10 and variable B holds 20 then

Operator Description Example

== Checks if the value of two operands are equal or not, if yes (A == B) is


then condition becomes true. not true.

!= Checks if the value of two operands are equal or not, if values (A != B) is


are not equal then condition becomes true. true.

> Checks if the value of left operand is greater than the value of (A > B) is not
right operand, if yes then condition becomes true. true.

< Checks if the value of left operand is less than the value of (A < B) is
right operand, if yes then condition becomes true. true.

>= Checks if the value of left operand is greater than or equal to (A >= B) is
the value of right operand, if yes then condition becomes true. not true.

<= Checks if the value of left operand is less than or equal to the (A <= B) is
value of right operand, if yes then condition becomes true. true.

10 | P a g e
iii)Logical Operators
There are following logical operators supported by PHP language. Assume variable A holds 10
and variable B holds 20 then

Operator Description Example

and Called Logical AND operator. If both the operands are true (A and B) is
then condition becomes true. true.

or Called Logical OR Operator. If any of the two operands are (A or B) is


non-zero then condition becomes true. true.

&& Called Logical AND operator. If both the operands are non- (A && B) is
zero then condition becomes true. true.

|| Called Logical OR Operator. If any of the two operands are (A || B) is


non-zero then condition becomes true. true.

! Called Logical NOT Operator. Use to reverses the logical state !(A && B)
of its operand. If a condition is true then Logical NOT operator is false
will make false.

iv)Assignment Operators
There are following assignment operators supported by PHP language

Operator Description Example

= Simple assignment operator, assigns values from C = A + B will assign


right side operands to left side operand value of A + B into C

+= Add AND assignment operator, It adds right operand C += A is equivalent


to the left operand and assign the result to left to C = C + A
operand

11 | P a g e
-= Subtract AND assignment operator, It subtracts right C -= A is equivalent to
operand from the left operand and assign the result to C=C-A
left operand

*= Multiply AND assignment operator, It multiplies C *= A is equivalent


right operand with the left operand and assign the to C = C * A
result to left operand

/= Divide AND assignment operator, It divides left C /= A is equivalent to


operand with the right operand and assign the result C=C/A
to left operand

%= Modulus AND assignment operator, It takes modulus C %= A is equivalent


using two operands and assign the result to left to C = C % A
operand

v)Conditional operator
There is one more operator called conditional operator. This first evaluates an expression for a
true or false value and then execute one of the two given statements depending upon the result of
the evaluation. The conditional operator has this syntax

Operator Description Example

?: Conditional If Condition is true ? Then value X : Otherwise value


Expression Y

$x = expr1 ? expr2 : expr3

Example

<?php
$A=45;
$B=20;

12 | P a g e
$result=($A>$B)?"The value of A is greater than the value of B":"The value of B is greater than
the value of A";
echo $result;
?>
1.2.5 Expressions
An expression can be evaluated to produce a value. The simplest expressions are literal values and
variables. A literal value evaluates to itself, while a variable evaluates to the value stored in the
variable. More complex expressions can be formed using simple expressions and operators.
Expressions are the most important building blocks of PHP. In PHP, almost anything you write is
an expression. The simplest yet most accurate way to define an expression is "anything that has a
value".

The most basic forms of expressions are constants and variables. When you type "$a = 5", you're
assigning '5' into $a.

PHP is an expression-oriented language, in the sense that almost everything is an expression.

1.2.6 Arrays

An array is a data structure that stores one or more similar type of values in a single value. For
example, if you want to store 100 numbers then instead of defining 100 variables it’s easy to
define an array of 100 lengths.

There are three different kind of arrays and each array value is accessed using an ID which is
called array index.

1.Numeric array /Indexed array − An array with a numeric index. Values are stored and
accessed in linear fashion.

Example:
<html>
<body>
<?php
/* First method to create array */

$numbers = array( 1, 2, 3, 4, 5);


foreach( $numbers as $value )

13 | P a g e
{
echo "Value is $value <br />";
}
/* Second method to create array */
$numbers[0] = "one";
$numbers[1] = "two";
$numbers[2] = "three";
$numbers[3] = "four";
$numbers[4] = "five";
foreach( $numbers as $value ) {

echo "Value is $value <br />";


}
?>
</body>
<html>
2.Associative array − An array with strings as index. This store element values in association
with key values rather than in a strict linear index order.

Example:

<html>

<body>

<?php

/* First method to associate create array. */

$salaries = array("Paul" => 2000, "Anitha" => 1000, "Divin" => 500);

echo "Salary of Paul is ". $salaries['Paul'] . "<br />";

echo "Salary of Anitha is ". $salaries['Anitha']. "<br />";

echo "Salary of Divin is ". $salaries['Divin']. "<br />";

/* Second method to create array. */

14 | P a g e
$salaries['Paul'] = "high";

$salaries['Anitha'] = "medium";

$salaries['Divin'] = "low";

echo "Salary of Paul is ". $salaries['Paul'] . "<br />";

echo "Salary of Anitha is ". $salaries['Anitha']. "<br />";

echo "Salary of Divin is ". $salaries['Divin']. "<br />";

?></body>
</html>
3.Multidimensional array − An array containing one or more arrays and values are accessed
using multiple indices.

A multi-dimensional array each element in the main array can also be an array. And each element
in the sub-array can be an array, and so on. Values in the multi-dimensional array are accessed
using multiple index.

Example
In this example we create a two-dimensional array to store marks of three students in three
subjects.

<?php

$marks = array( "Paul" => array ("physics" => 35,"maths" => 30,"chemistry" => 39
),"Anitha" => array ( "physics" => 30, "maths" => 32,"chemistry" => 29), "Divin" => array
("physics" => 31, "maths" => 22, "chemistry" => 39 ) );

/* Accessing multi-dimensional array values */

echo "Marks for Paul in physics : " ;

echo $marks['Paul']['physics'] . "<br />";

echo "Marks for Anitha in maths : ";

echo $marks['Anitha']['maths'] . "<br />";

echo "Marks for Divin in chemistry : " ;

echo $marks['Divin']['chemistry'] . "<br />";

15 | P a g e
?>

</body>
</html>

The output:

Marks for Paul in physics: 35


Marks for Anitha in maths : 32
Marks for Divin in chemistry : 39

1.3 Introduce PHP comments


1.3.1 Introduction to PHP comments
1.Purpose of comments

A comment in PHP code is a line that is not read/executed as part of the program. Its only purpose
is to be read by someone who is looking at the code.

Comments can be used to:

 Let others understand what you are doing.


 Remind yourself of what you did. Most programmers have experienced coming back to
their own work a year or two later and having to re-figure out what they did. Comments
can remind you of what you were thinking when you wrote the code

2.Types of comments

PHP has two types. The first type we will discuss is the single line comment. The single line
comment tells the interpreter to ignore everything that occurs on that line to the right of the
comment. To do a single line comment type "//" or "#" and all text to the right will be ignored by
PHP interpreter.

The second type is multi-line comment can be used to comment out large blocks of code or
writing multiple line comments. The multiple line comment begins with " /* " and ends with " */
".

1.3.2 Use of PHP comments

To use the PHP comments in php you can // or # for single line comments.

Here, there is example that shows how you can use single line comment

<?php

16 | P a g e
echo "Hello World!"; // This will print out Hello World!

echo "<br />"; # This will print out a new line

echo " You can't see my PHP comments!";

?>

The output is:

Hello World!
You can't see my PHP comments!

To use the PHP comments in php you can /* */ for multiple line comments.

Here, there is example that shows how you can use multiple line comment

<?php
/* This echo statement will print out my message to the
the place in which I reside on. */
echo "Hello World!";
?>

17 | P a g e
LU 2 IMPLEMENT PHP LOGIC
LO2.1: Use PHP control structures
2.1.1 Application of program flow control

1. Conditional statements

PHP lets programmers evaluate different conditions during of a program and take decisions based
on whether these conditions evaluate to true or false.
These conditions, and the actions associated with them, are expressed by means of a programming
construct called a conditional statement.

PHP supports different types of conditional statements.

A.if Statement

The if Statement is the simplest conditional statements. In if statements output will appear when
only condition must be true.
If statement works much like the English language statement, “if X happens, then do Y.”

The syntax is:

if (condition) {
code to be executed if condition is true;
}

Example:

<?php
$t = date("H");

if ($t < 20) {


echo "Have a good day!";
}
?>

Exercises:

1.Write a program to check even number. (Number entered by user)


2.Write a program to check given number is Positive

18 | P a g e
B. if-else Statement

The if statement is quite basic because in If statement output will display when condition must be
true, if the condition is false it display nothing(blank) as the message.
But if-else statements allows you to display output in both the condition (if condition is true
display some message otherwise display other message).
In English, this statement would read, “if X happens, do Y; otherwise do Z”.

The syntax is:

if (condition) {
code to be executed if condition is true;
} else {
code to be executed if condition is false;
}

The example below will output "Have a good day!" if the current time is less than 20, and "Have
a good night!" otherwise.

Example:

<?php
$t = date("H");

if ($t < 20) {


echo "Have a good day!";
} else {
echo "Have a good night!";
}
?>
Exercises:

1. Write a program to check given inputted number is negative or positive.

2. Write a program to check given inputted number is even or odd.


C.if-elseif-else Statement

The if-elseif-else statement lets you chain together multiple if-else statements, thus allowing the
programmer to define actions for more than just two possible outcomes.

19 | P a g e
The syntax is:

if (condition) {
code to be executed if this condition is true;
} elseif (condition) {
code to be executed if this condition is true;
} else {
code to be executed if all conditions are false;
}

The example below will output "Have a good morning!" if the current time is less than 10, and
"Have a good day!" if the current time is less than 20. Otherwise it will output "Have a good
night!"

Example:

<?php
$t = date("H");

if ($t < 10) {


echo "Have a good morning!";
} elseif ($t < 20) {
echo "Have a good day!";
} else {
echo "Have a good night!";
}
?>
Exercises:

1.Write a program to check given character is vowel or consonant.

2. Write a php program to print related day name according to inputted number (1 – 7).

D.Switch statement

Switch… case is similar to the if then… else control structure.

It only executes a single block of code depending on the value of the condition.

If no condition has been met, then the default block of code is executed.

It has the following basic syntax.

20 | P a g e
<?php
switch(condition){
case value:
//block of code to be executed
break;
case value2:
//block of code to be executed
break;
default:
//default block code
break;
}
?>

Example:
<?php
$favcolor = "red";

switch ($favcolor) {
case "red":
echo "Your favorite color is red!";
break;
case "blue":
echo "Your favorite color is blue!";
break;
case "green":
echo "Your favorite color is green!";
break;
default:
echo "Your favorite color is neither red, blue, nor green!";
}
?>

Exercise:

1. Enter first number, second number and choice arithmetic operator, make calculation.
2.Iterative statements

Loops in PHP are used to execute the same block of code a specified number of times. PHP
supports following four loop types.

 for − loops through a block of code a specified number of times.

21 | P a g e
 while − loops through a block of code if and as long as a specified condition is true.

 do...while − loops through a block of code once, and then repeats the loop as long as a
special condition is true.

 foreach − loops through a block of code for each element in an array.

i.For

The for loop is used when you know in advance how many times the script should run.

Syntax

for (initialization; condition; increment)


{
code to be executed;
}

Parameters of for loop:


Initialization: is used to set a counter.
Condition : if condition is true loop will continue, if the condition is false loop ends.
Increment : used to increment the counter.

Example: Write a PHP program for printing the first five natural numbers
<?php

for ($i=1; $i<=5; $i++)

echo "The Number is: ".$i."<br/>";

?>

Exercises:

1.Write a php program to print your name 10 times


2. Find the sum of 1 to 100.
3. Find all even numbers between 1 to 100

ii.while

The while loop executes a block of code while a condition is true.

22 | P a g e
Syntax

while (condition)

code to be executed;

Example: Write a PHP program for printing the first five natural numbers
<?php
$i=1;
while($i<=5)
{
echo "The number is ". $i . "<br>";
$i++;
}
?>
Exercises:

1.Find the sum of 1 to 100 using While Loop

iii.Do while
The do…while Loop executes the statement once and then check the condition.

Syntax
do
{
code to be executed;
}
while (condition);

Example: Write a PHP program for printing the first five natural numbers
<?php
$i=1;
do

23 | P a g e
{
echo "The number is " . $i . "<br>";
$i++;
}
while ($i<=5);
?>

Exercise:
1.Write a program to display table of given number.

iv). Foreach

The foreach loop is used to display the value of array.

You can define two parameters inside foreach separated through “as” keyword.
First parameter must be existing array name which elements or key you want to display.

At the Position of 2nd parameter, could define two variables: One for key(index)
and another for value.

If you define only one variable at the position of 2nd parameter, it contains arrays value (By default
display array value).

Syntax

foreach ($array as $value)

code to be executed;

For every loop iteration, the value of the current array element is assigned to $value (and the
array pointer is moved by one) – so on the next loop iteration, you’ll be looking at the next array
value.

The following example demonstrates a loop that will print the values of the given array.

Example 1:
<?php
$person=array("alex", "simon","ravi");
foreach ($person as $val)
{

24 | P a g e
echo $val."<br/>";
}
?>
Example 2:
<?php

$marks = array(

"Paul" => array(

"Maths" => 95,


"Physics" => 85,
"Biology" => 74,
),

"Anitha" => array(

"Maths" => 89,


"Physics" => 67,
"Biology" => 80,
),

"Antony" => array(

"Maths" => 56,


"Physics" => 89,
"Biology" => 90,
),
);

foreach($marks as $mark) {
echo $mark['Maths']. " ".$mark['Physics']." ".$mark['Biology']."<br>";
}

?>

LO 2.2: Use PHP Functions

2.2.1 Application of PHP functions


1. Built-in functions
They help to better organize the application as well as eliminate the need to copy/paste repetitive
pieces of code. PHP has a lot of built in functions and while you are not expected to learn all of
them at once there are some useful functions that can help in everyday programming.

25 | P a g e
Examples:

string functions, date (), mysqli_close(),array(),imagecreate(),imagecreatetruecolor(),day(),etc.

2.User-defined functions

A user-defined function declaration starts with the word function.


Information can be passed to functions through arguments. An argument is just like a variable.
Arguments are specified after the function name, inside the parentheses. You can add as many
arguments as you want, just separate them with a comma.1

Syntax
function functionName() {
code to be executed;
}

A function name must start with a letter or an underscore. Function names are not case-sensitive.
Thus, the concept of "void" functions does not apply to PHP. You can specify the return value of
your function by using the return keyword.

Examples:

1. <?php
function add($a,$b){
$total = $a + $b;
return $total; //Function return, No output is shown
}

echo add(55,20); //Outputs 75


?>

2.<?php
function hello(){
return "Hello World"; // No output is shown
}
$txt = hello(); // Assigns the return value "Hello World" to $txt
echo hello(); // Direct Displays "Hello World"

1
https://www.w3schools.com/php/php_functions.asp 12/03/2020

26 | P a g e
?>

3. String manipulation functions

Some of the most useful PHP functions are string manipulation functions. As the name suggests
they manipulate strings.

strlen

The strlen() function returns the length of a string.

The syntax: strlen(string)

Example:
<?php
$name = "Matthew";
echo strlen($name); // 7
?>

substr
The substr() function is used to return a substring or part of a string. This function has 3
parameters which you can pass along.

The syntax: substr(string,start,length)


If $start is non-negative, the returned string will start at the start'th position in string, counting
from zero. For instance, in the string 'abcdef', the character at position 0 is 'a', the character at
position 2 is 'c', and so forth.

If $start is negative, the returned string will start at the start'th character from the end of string.
If $string is less than $start characters long, FALSE will be returned.

Note: If you don’t provide a $length parameter, this function will just return the remainder of the
string starting from the $start parameter.
Example:

<?php
$name = "Matthew";
echo substr($name, 0, 5); // Matth

27 | P a g e
echo substr($name, 2); // tthew
echo substr($name, 7,2);//No output because of 7 is grater than 6
echo substr($name,-7,2);//Ma
?>
Explanation

M a t t h e w
0 1 2 3 4 5 6
-7 -6 -5 -4 -3 -2 -1

Converting strings to UPPER or lower case


The two useful string functions that are simple to use are strtoupper() and strtolower(), these
functions can convert your strings to all UPPERCASE or all lowercase.
They are very useful for case sensitive operations where you may require all characters to be
lowercase for example.

<?php
$name = "Matthew ";
echo strtoupper($name); // MATTHEW
echo strtolower($name); // matthew
?>

Strrev

The strrev() function reverses a string.

Syntax

strrev ( string )

Example:
<?php
echo strrev("Hello world!"); // outputs "!dlrow olleH"
?>

strpos
strpos in PHP is a built-in function. Its use is to find the first occurrence of a substring in a string
or a string inside another string. The function returns an integer value which is the index of the

28 | P a g e
first occurrence of the string. The upper-case and lower-case characters are treated differently as
the function is case-sensitive.
Syntax: strpos(string,find,start)
Example1:
<?php
$name = "Matthew ";
echo strpos($name, "M"); // 0
echo strpos($name, "hew"); // 4
echo strpos($name, "m"); // false
?>
Example2:
<?php
Echo strops("strops in php","php");//10
?>

htmlentities()
The htmlentities() function converts characters to HTML entities.
Example:
<?php
$str = '<a href="https://www.w3schools.com">Go to w3schools.com</a><br>';
echo htmlentities($str);
?>
Trim

The trim() function removes whitespace and other predefined characters from both sides of a
string.

Related functions:

 ltrim() - Removes whitespace or other predefined characters from the left side of a string
 rtrim() - Removes whitespace or other predefined characters from the right side of a
string

Example1:

Remove characters from both sides of a string ("He" in "Hello" and "d!" in "World"):

29 | P a g e
<?php
$str = "Hello World!";
echo $str . "<br>";
echo trim($str,"Hed!");
?>
printf

The printf() function outputs a formatted string.

The arg1, arg2, ++ parameters will be inserted at percent (%) signs in the main string. This
function works "step-by-step". At the first % sign, arg1 is inserted, at the second % sign, arg2 is
inserted, etc.

Note: If there are more % signs than arguments, you must use placeholders. A placeholder is
inserted after the % sign, and consists of the argument- number and "\$".

The syntax: printf(format,arg1,arg2,arg++)

The possible formats:

%% - Returns a percent sign, %b - Binary number, %c - The character according to the ASCII
value, %d - Signed decimal number (negative, zero or positive), %e - Scientific notation using a
lowercase (e.g. 1.2e+2), %E - Scientific notation using a uppercase (e.g. 1.2E+2), %u - Unsigned
decimal number (equal to or greater than zero), %f - Floating-point number (local settings
aware), %o - Octal number, %s – String, %x - Hexadecimal number (lowercase letters),%X -
Hexadecimal number (uppercase letters).

These are placed between the % and the letter (example %.2f).

Example1:

<?php
$number = 9;
$str = "Beijing";
printf("There are %u million bicycles in %s.",$number,$str);
?>

Example2:

<?php
$number = 123;
printf("%f",$number);
?>

Example3:

30 | P a g e
<?php
$number = 123;
printf("With 2 decimals: %1\$.2f
<br>With no decimals: %1\$u",$number);
?>

str_word_count()
The str_word_count() function counts the number of words in a string.
Example 1:
<?php
// Count the number of words found in the string "Hello World!"
echo str_word_count("Hello world!");//2
?>
Example 2:
<?php
// Return an array with the words from the string
print_r(str_word_count("Hello world!",1));// Array ( [0] => Hello [1] => world )
?>
Example 3:
<?php
// Return an array where the key is the position of the word in the string, and value is the actual
word
print_r(str_word_count("Hello world!",2));// Array ( [0] => Hello [6] => world )
?>

Exercises

1.Give the output of this program

<?php
$name ="Matthew";
echo strlen($name);
echo"<br>";
echo substr($name,3,4);
echo"<br>";
echo substr($name,4,1);
echo"<br>";
echo substr($name,-2,3);
echo"<br>";

31 | P a g e
echo substr($name,-3,2);
echo"<br>";
echo substr($name,-5,4);
echo"<br>";
echo substr($name,8,4);
?>

2.What is the output of this PHP program?

<?php
$schoolName="GLORY ACADEMY";
echo strtoupper($schoolName);
echo "<br>";
echo strtolower($schoolName);
?>

3.What is the output of this program?

<?php
$name2="Level 5";
echo strrev($name2);
echo"<br>";
$name="Matthew";
echo strpos($name,"tt");
echo"<br>";
echo strpos($name,"at",1);
echo"<br>";
echo strpos($name,"hew",3);
echo"<br>";
echo strpos($name,"hew",4);
echo"<br>";
echo strpos($name,"hew");
echo"<br>";
echo strpos($name,"T");
?>

32 | P a g e
LO2.3: Implement PHP File processing

2.3.1 File formats supported by PHP

1.Image formats

PHP is not limited to creating just HTML output. It can also be used to create and manipulate
image files in a variety of different image formats, including GIF, PNG, JPEG, WBMP (wireless
Bitmap), and XPM(X PixMap). Even more conveniently, PHP can output image streams directly
to a browser. You will need to compile PHP with the GD (Graphics draw) library of image
functions for this to work. GD and PHP may also require other libraries, depending on which
image formats you want to work with.

You can use the image functions in PHP to get the size of JPEG, GIF, PNG, SWF(Shockwave
Fash), TIFF and JPEG2000 images.

2. File functions in PHP

A.is_file

The is_file() function checks whether the specified filename is a regular file.
Syntax:

is_file(file)

Program 1:

<?php
$myfile = "gfg.txt"; // checking whether the file is a regular file or not
if (is_file($myfile)) {
echo ("$myfile: regular file!");
} else {
echo ("$myfile: not a regular file!");
}
?>
Output:
gfg.txt: regular file!

B. file_exists

The file_exists() function checks whether a file or directory exists.


Syntax:
file_exists(path)

33 | P a g e
Examples:

<?php
$file = 'C:/xampp/htdocs/L52022/welcome.docx';
if (file_exists($file)) {
echo "The file $file exists";
}else {
echo "The file $file does not exists";
}
?>
C.fopen

The fopen() function opens a file or URL.

If fopen() fails, it returns FALSE and an error on failure. You can hide the error output by adding
an '@' in front of the function name.

Syntax
fopen(filename,mode,include_path,context)

Parameter Description
filename Required. Specifies the file or URL to open
mode
Required. Specifies the type of access you require to the file/stream.

Possible values:

 "r" (Read only. Starts at the beginning of the file)


 "r+" (Read/Write. Starts at the beginning of the file)
 "w" (Write only. Opens and clears the contents of file; or creates a new
file if it doesn't exist)
 "w+" (Read/Write. Opens and clears the contents of file; or creates a
new file if it doesn't exist)
 "a" (Write only. Opens and writes to the end of the file or creates a new
file if it doesn't exist)
 "a+" (Read/Write. Preserves file content by writing to the end of the
file)
 "x" (Write only. Creates a new file. Returns FALSE and an error if file
already exists)

"x+" (Read/Write. Creates a new file. Returns FALSE and an error if file
already exists)
include_path Optional. Set this parameter to '1' if you want to search for the file in the
include_path (in php.ini) as well

34 | P a g e
context Optional. Specifies the context of the file handle. Context is a set of options
that can modify the behavior of a stream

Example 1:
<?php
$myfile = fopen("level5.txt", "r") or die("Unable to open file!");
echo fread($myfile,filesize("level5.txt"));
fclose($myfile);
?>

Example 2:
<?php
$file = fopen("welcome.txt", "r");

//Output lines until EOF is reached


while(! feof($file)) {
$line = fgets($file);
echo $line. "<br>";
}

fclose($file);
?>

D.fwrite

The fwrite() writes to an open file.

The function will stop at the end of the file (EOF) or when it reaches the specified length,
whichever comes first.

Syntax

fwrite(file, string, length)

Example

<?php
$file = fopen("welcome.txt","w+");
echo fwrite($file,"Level 5 Software Development");//28(in bytes=number of characters+spaces)
fclose($file);
?>

35 | P a g e
E.fclose

The fclose() function closes an open file.

This function returns TRUE on success or FALSE on failure.

Syntax: fclose(file)
Example 1:
<?php
$file = fopen("level5.txt","r");
//some code to be executed
fclose($file);
?>
F.fgets

The fgets() function returns a line from an open file.

The fgets() function stops returning on a new line, at the specified length, or at end of file(EOF),
whichever comes first.

This function returns FALSE on failure.

Syntax: fgets(file,length)

Example 1:
<?php
//Read one line from the open file
$file = fopen("level5.txt","r");
echo fgets($file);
fclose($file);
?>
Example 2:

Read file line by line:

<?php
$file = fopen("level5.txt","r");

while(! feof($file))
{
echo fgets($file). "<br />";
}

36 | P a g e
fclose($file);
?>
G.fgetss

The fgetss() function returns a line, with HTML and PHP tags removed, from an open file.

The fgetss() function stops returning on a new line, at the specified length, or at EOF, whichever
comes first.

This function returns FALSE on failure.

Syntax

fgetss(file,length,tags)

Parameter Description
file Required. Specifies the file to check
length
Optional. Specifies the number of bytes to
read. Default is 1024 bytes.

Note: This parameter is required in versions


prior to PHP 5
tags Optional. Specifies tags that will not be
removed

Note: The fgetss() function is deprecated from PHP 7.3.


Example 1:
Test.html file has <h1>Level 5 SOD</h1>
<?php
$file = fopen("test.html","r");
echo fgetss($file,1024,"<h1>");
fclose($file);
?>

H.copy

The copy() function copies a file.

This function returns TRUE on success and FALSE on failure.

37 | P a g e
Syntax: copy(from_file,to_file)

Note: If the destination file already exists, it will be overwritten.

Example

<?php
echo copy("source.txt","target.txt");
?>

I.Unlink

The unlink() function deletes a file.

This function returns TRUE on success, or FALSE on failure.

Syntax: unlink(filename,context)
Example
<?php
$file = "test.txt";
if (!unlink($file))
{
echo ("Error deleting $file");
}
else
{
echo ("Deleted $file");
}
?>

J.file_get_contents

The file_get_contents() reads a file into a string.

This function is the preferred way to read the contents of a file into a string. Because it will use
memory mapping techniques, if this is supported by the server, to enhance performance.

Syntax
file_get_contents(path, include_path,context,start,max_length)
Parameter Description
path Required. Specifies the file to read

38 | P a g e
include_path Optional. Set this parameter to '1' if you want
to search for the file in the include_path (in
php.ini) as well
context Optional. Specifies the context of the file
handle. Context is a set of options that can
modify the behavior of a stream. Can be
skipped by using NULL.
start Optional. Specifies where in the file to start
reading. This parameter was added in PHP 5.1
max_length Optional. Specifies how many bytes to read.
This parameter was added in PHP 5.1

Tip: This function is binary-safe (meaning that both binary data, like images, and character data
can be written with this function).

Example 1:
<?php
echo file_get_contents("level5.txt");
?>
Example 2:
<?php
// Reading 100 bytes starting from
// the 0th character from welcome2.txt
$text = file_get_contents('welcome2.txt', false, NULL, 0, 100);
echo $text;

?>
Exercises
1.Write a PHP program that checks if bumba.txt is regular file.
2.Give the syntax of the following functions:
a) file_exists()
b) copy()
3.Write a PHP that opens and displays the contents of file called welcome.txt.
4.Write a PHP program that opens and displays the first line of content in file called imihigo.txt

39 | P a g e
5.Write a PHP program that uses gets function to display the output of this HTML file called
test.html.
test.html
<!doctype html>
<html>
<head><title>Getss example</title>
</head>
<body>
<h1>List of items</h1>
<ol>
<li>Laptop</li>
<li>Desktop</li>
</ol>
<p><strong>Good Luck!!</strong></p>
</body>
</html>

6.Write a PHP program that deletes a file called Amanota.docx

40 | P a g e
LO2.4: Handle Errors and Exceptions
2.4.1 Description of program error types
1.Syntax errors

Syntax Error (Parse Error) occurs if there is a syntax mistake in the script; the output is
Parse error. A parse error stops the execution of the script. There are many reasons for the
occurrence of parse errors in PHP. The common reasons for parse errors are as follows:
1. Unclosed quotes
2. Missing or Extra parentheses
3. Unclosed braces
4. Missing semicolon

Example:

<?php
echo "Cat";
echo "Dog"
echo "Lion";
?>

2.Logical errors

The logical or semantic error is a fault in program design like the order of instruction. They may
cause a problem to respond incorrectly to the user or crash completely.

If there is any logical error in code, the PHP script will compile and run successfully and the
computer will not generate any error message. But does not do the right thing.

PHP code does not print last message. An infinite loop was entered.

Example:

<?php
for($i=1;;$i++)
{
echo $i;
}
?>

41 | P a g e
3.Run time errors

Runtime error refers to the error that occurs during execution of the code, which are not usually
programming error, but caused by factors outside PHP script itself, such as database calls or disk
or network operation.

Example:

The mysqli_connect () function falls, because the username specified was accidently deleted by
the MySQL administrator.

2.4.2 Introduction to error functions

1.die function

die( ) function is used to display a message and exit the script. It may be used to print alternate
message. Instead of showing error it will show the user-friendly message.

The syntax is:


die(message)

Example:

<?php
$con= mysqli_connect("localhost","root","") or die('connection not found');
?>
In the above example if the connection with database is not established due to some error the die
function shows the message “connection not found”.

2. Custom error functions

Creating a custom error handler in PHP is quite simple. Create a function that can be called when
an error has been occurred in PHP.
Syntax:

error_function( $error_level, $error_message, $error_file, $error_line, $error_context)

42 | P a g e
Parameter Description
error_level Required. Specifies the error report level for
the user-defined error. Must be a value
number. Example: 1(E_ERROR): A fatal run-
time error. Execution of the script is
stopped,2(E_WARNING): A non-fatal run-
time error. Execution of the script is not
stopped, 8(E_NOTICE): A run-time notice.
The script found something that might be an
error, but could also happen when running a
script normally,…
error_message Required. Specifies the error message for the
user-defined error
error_file Optional. Specifies the filename in which the
error occurred
error_line Optional. Specifies the line number in which
the error occurred
error_context Optional. Specifies an array containing every
variable, and their values, in use when the
error occurred

Example:

<?php
// Creates my error function which prints message to user
function myerror($error_no, $error_msg,$error_file,$error_line,$error_context)
{
echo "[$error_no] <br> $error_msg <br>$error_file ";
echo "<br> $error_line";
echo "<br> $error_context";

// When error occured script has to be stoped


die();
}

// Setting set_error_handler
set_error_handler("myerror");

$a = 10;
$b = 0;

43 | P a g e
// This will generate error
echo($a / $b);
?>
Output:

[2]
Division by zero
C:\xampp\htdocs\sfd50119\customerror.php
20
Notice: Array to string conversion in C:\xampp\htdocs\sfd50119\customerror.php on line 7

Array

2.4.3 Application of exception block

1.Try and catch keywords

PHP try and catch are the blocks with the feature of exception handling, which contain the code
to handle exceptions. There is one more important keyword used with the try-catch block
is throw. The throw is a keyword that is used to throw an exception.

// code before the try-catch block

try {
// code

// if something is not as expected


// throw exception using the "throw" keyword

// code, it won't be executed if the above exception is thrown


} catch (Exception $e) {
// exception is raised and it'll be handled here
// $e->getMessage() contains the error message
}

// code after the try-catch block, will always be executed

The try block is the one to use where you suspect that your code may generate an exception. You
should always wrap such code using try and catch.

44 | P a g e
Example:

Let's assume that you've built an application which loads the application connection to mysql
server from the connection.php file. Now, it's essential that the connection.php file is present
when your application is connected to mysql server. Thus, your application can't run if
the connection.php file is not present. So this is the perfect use case to throw an exception and
let the user know they need to fix the issue.

<?php
try {

$file = "connection.php";
if (!file_exists($file))
{
throw new Exception("Connection file not found.");
}

} catch (Exception $a) {


echo $a->getMessage();
die();
}
?>

Complete program

<!DOCTYPE html>
<head><title>Data presentation in HTML table</title>
</head>
<body>
<?php
try {
$file = "connection.php";
if (!file_exists($file))
{
throw new Exception("Connection file not found.");
}
include('connection.php');

45 | P a g e
$select='select * from Modules';
$query=mysqli_query($con,$select);

echo"<center><table border='1'>
<caption><h2><u>LIST OF MODULES</u></h2></caption>
<tr><th>MID</th><th>MODULE CODE</th><th>MODULE NAME</th></tr>";

while($record=mysqli_fetch_array($query))
{
echo"<tr>";
echo"<td>".$record['MId']."</td>";
echo"<td>".$record['ModuleCode']."</td>";
echo"<td>".$record['ModuleName']."</td>";
echo"<tr>";
}
echo"</table></center>";

} catch (Exception $a)


{
echo $a->getMessage();
die();

}
?>
<body>
</html>

46 | P a g e
LU 3 PERFORM PHP MYSQL DATABASE INTERACTIONS

LO 3.1 Connect and access MySQL Database

3.1.1 Application of connection object and method

There are three ways of making the connection to a database.

1.Connection object

<?php
$servername = "localhost";
$username = "username";
$password = "password";

// Create connection
$conn = new mysqli($servername, $username, $password);

// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
?>

2.mysqli_connect

<?php
$servername = "localhost";
$username = "username";
$password = "password";

// Create connection
$conn = mysqli_connect($servername, $username, $password);

// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully";
?>

3.PDO
The PHP Data Objects (PDO) defines a lightweight interface for accessing databases in PHP.

47 | P a g e
<?php
$servername = "localhost";
$username = "username";
$password = "password";

try {
$conn = new PDO("mysql:host=$servername;dbname=myDB", $username, $password);
echo "Connected successfully";
}

catch(PDOException $e)
{
echo "Connection failed: " . $e->getMessage();
}
?>

Note: In the PDO example above we have also specified a database (myDB). PDO require a
valid database to connect to. If no database is specified, an exception is thrown.

A great benefit of PDO is that it has an exception class to handle any problems that may occur in
our database queries. If an exception is thrown within the try{ } block, the script stops executing
and flows directly to the first catch(){ } block.

Example 1:
<?php
$dbHost="localhost";
$dbName="isoko";
$dbUser="root";
$dbPassword="";
try{
$dbConn= new PDO("mysql:host=$dbHost;dbname=$dbName",$dbUser,$dbPassword);
Echo "Successfully connected with $dbName database";
} catch(Exception $e){
Echo "Connection failed" . $e->getMessage();
}
$dbConn=null;
?>

Example 2:

<?php

48 | P a g e
$dbHost="localhost";
$dbName="isoko";
$dbUser="root";
$dbPassword="";
try{
$dbConn= new PDO("mysql:host=$dbHost;dbname=$dbName",$dbUser,$dbPassword);
$stmt = $dbConn->prepare("SELECT * FROM products");
$stmt->execute();
$users = $stmt->fetchAll();
if($users)
{
echo"<h3></u>LIST OF CUSTMERS</u></h3>";
echo"<table border=1 cellspacing=0>
<tr><th>ID</th><th>Name</th><th> Category ID</th></tr>";

foreach($users as $user)
{
echo"<tr>";
echo"<td>";
echo $user['id'];
echo"</td>";
echo"<td>";
echo $user['name'];
echo"</td>";
echo"<td>";
echo $user['category_id'];
echo"</td>";
echo"</tr><br>";
}
echo"</table>";
}
else
{
echo "No Records found";
}

}
catch(Exception $e){
Echo "Connection failed" . $e->getMessage();
}
$dbConn=null;
?>
3.2.2 Application database access methods

1.mysqli_select_db

49 | P a g e
The mysqli_select_db() function is used to change the default database for the connection.

Syntax: mysqli_select_db(connection,dbname);

Example:

<?php
$con=mysqli_connect("localhost","my_user","my_password","my_db");
mysqli_select_db($con,"test");

// ...some PHP code for database "test"...


?>
2.mysqli_query

The mysqli_query() function accepts a string value representing a query as one of the
parameters and, executes the given query on the database.
Syntax: mysqli_query(connection,query,resultmode);

Parameter Description
connection Required. Specifies the MySQL connection to
use
query Required. Specifies the query string
resultmode Optional. A constant. Either:

 MYSQLI_USE_RESULT (Use this if


we have to retrieve large amount of
data)
 MYSQLI_STORE_RESULT (This is
default)

Example:

<?php
$con=mysqli_connect("localhost","root","");
mysqli_select_db($con,'gsbms');
mysqli_query($con,"INSERT INTO
users(userFirstname,userLastname,Username,userPassword)
VALUES('Alice','UWAYO', 'Ace1', 'Alice1231')");
?>
3.mysqli_num_rows

50 | P a g e
The mysqli_num_rows() function returns the number of rows in a result set.

Syntax:
mysqli_num_rows(result);
Parameter Description
result Required. Specifies a result set identifier
returned by mysqli_query().

Example:

Return the number of rows in a result set:

<?php
$con=mysqli_connect("localhost","root","");
mysqli_select_db($con,'gsbms');
$sql="select * from users";
$result=mysqli_query($con,$sql);
// Return the number of rows in result set
$rowcount=mysqli_num_rows($result);
printf("Result set has %d rows.<br>",$rowcount);
?>

4.mysqli_fetch_array

The mysqli_fetch_array() function fetches a result row as an associative array, a numeric array,
or both.

Note: Fieldnames returned from this function are case-sensitive.

Syntax: mysqli_fetch_array(result,resulttype);

Parameter Description
result Required. Specifies a result set identifier
returned by mysqli_query()
resulttype
Optional. Specifies what type of array that
should be produced. Can be one of the
following values:

 MYSQLI_ASSOC
 MYSQLI_NUM

51 | P a g e
 MYSQLI_BOTH

Example:

<?php
$con=mysqli_connect("localhost","root","");
mysqli_select_db($con,'gsbms');
$sql="SELECT * FROM modules where moduleId=1";
$result=mysqli_query($con,$sql);

while($row=mysqli_fetch_array($result,MYSQLI_ASSOC))
{
echo $row['moduleId']." ".$row['moduleCode']." ".$row['moduleName']."<br>";
}
?>

5.mysqli_close

The mysqli_close() function closes a previously opened database connection.

Syntax

mysqli_close(connection);
Parameter Description
connection Required. Specifies the MySQL connection to
close

Example

Close a previously opened database connection:

<?php
$con=mysqli_connect("localhost","my_user","my_password","my_db");

// ....some PHP code...

mysqli_close($con);
?>

52 | P a g e
LO 3.2 Implement database CRUD Operations
3.2.1 Manipulation of database table records

1. Insert record

To insert record in database you need to use INSERT INTO statement. It is possible to write the
INSERT INTO statement in two ways. The first way specifies both the column names and the
values to be inserted:

INSERT INTO table_name (column1, column2, column3, ...) VALUES (value1, value2, value3,
...);

If you are adding values for all the columns of the table, you do not need to specify the column
names in the SQL query. However, make sure the order of the values is in the same order as the
columns in the table. The INSERT INTO syntax would be as follows:

INSERT INTO table_name VALUES (value1, value2, value3, ...);


Example:

<?php
$con=mysqli_connect("localhost","root","");
mysqli_select_db($con,'gsbms');
$sql="INSERT INTO users(userFirstname,userLastname,Username,userPassword)
VALUES('Pierre','KAMANA', 'Pierre', 'Pierre23')";
$insertquery=mysqli_query($con,$sql);
if($insertquery==true)
{
echo"Record is inserted successfully!";
}
else
{
echo"Record is not inserted!";
}
mysqli_close($con);
?>

2.Retrieve records

The SELECT statement is used to retrieve data from a database.

The data returned is stored in a result table, called the result-set.

SELECT Syntax
SELECT column1, column2, ... FROM table_name;

53 | P a g e
Here, column1, column2, ... are the field names of the table you want to select data from. If you
want to select all the fields available in the table, use the following syntax:

SELECT * FROM table_name;


Example:
<?php
$con=mysqli_connect("localhost","root","");
mysqli_select_db($con,'gsbms');
$sql="SELECT * FROM modules";
$result=mysqli_query($con,$sql);
while($row=mysqli_fetch_array($result,MYSQLI_ASSOC))
{
echo $row['moduleId']." ".$row['moduleCode']." ".$row['moduleName']."<br>";
}
mysqli_close($con);
?>

3. Retrieve one record

To retrieve one record from the database you need to use a primary field value as the condition
with the SELECT statement.

Example:

<?php
$con=mysqli_connect("localhost","root","");
mysqli_select_db($con,'gsbms');
$sql="SELECT * FROM modules where moduleId=4";
$result=mysqli_query($con,$sql);
while($row=mysqli_fetch_array($result,MYSQLI_ASSOC))
{
echo $row['moduleId']." ".$row['moduleCode']." ".$row['moduleName']."<br>";
}
mysqli_close($con);
?>

4.Update record

The UPDATE statement is used to modify the existing records in a table.

Syntax:
UPDATE table_name
SET column1 = value1, column2 = value2, ...
WHERE condition;

54 | P a g e
Note: Be careful when updating records in a table! Notice the WHERE clause in the UPDATE
statement. The WHERE clause specifies which record(s) that should be updated. If you omit the
WHERE clause, all records in the table will be updated!

Example:

<?php
$con=mysqli_connect("localhost","root","");
mysqli_select_db($con,'gsbms');
$sql="update users set userFirstname='John' where userid=1 ";
$updatequery=mysqli_query($con,$sql);
if($updatequery==true)
{
echo"Record is updated successfully!";
}
else
{
echo"Record is not updated!";
}
mysqli_close($con);
?>

5.Delete record

The DELETE statement is used to delete existing records in a table.

Syntax
DELETE FROM table_name WHERE condition;
Note: Be careful when deleting in a table! Notice the WHERE clause in the DELETE statement.
The WHERE clause specifies which record(s) should be deleted. If you omit the WHERE clause,
all records in the table will be deleted.
Example:
<?php
$con=mysqli_connect("localhost","root","");
mysqli_select_db($con,'gsbms');
$sql="delete from users where userid=7";
$deletequery=mysqli_query($con,$sql);
if($deletequery==true)
{
echo"Record is deleted successfully!";
}
else
{

55 | P a g e
echo"Record is not deleted!";
}
mysqli_close($con);
?>

6.Export and import records


You can export record in a comma-separated values(CSV) file. It is a delimited text file that uses
a comma to separate values. Each line of the file is a data record.
 Exporting MySQL data to excel, it takes two steps:
Step 1. Make a HTML file and define markup
We make a HTML file and save it with a name export.html
<html>
<head></head>
<body>
<form method="post" action="export_data.php">
<input type="submit" name="export" value="EXPORT TO EXCEL">
</form></body></html>
Step 2. Make a PHP file to export data into MySQL database
We make a PHP file and save it with a name export_data.php

<?php
if(isset($_POST['export']))
{
$host="localhost";
$username="root";
$password="";
$databasename="gsbms";
$data="";
$connect=mysqli_connect($host,$username,$password);
$db=mysqli_select_db($connect,$databasename);

56 | P a g e
$select = mysqli_query($connect,"SELECT * FROM users");
while($row=mysqli_fetch_array($select))
{
$data.=$row['userid'].",";
$data.=$row['userFirstname'].",";
$data.=$row['userLastname'].",";
$data.=$row['Username'].",";
$data.=$row['userPassword']."\n";
}
echo $data;
header("Content-Disposition: attachment; filename=mysql_to_excel.csv");
exit();
}
?>

 Importing Excel file into MySQL it takes two steps:


Step 1. Make a HTML file and define markup
We make a HTML file and save it with a name import.html
<html>
<body>
<form method="post" action="import_file.php" enctype="multipart/form-data">
<input type="file" name="file"/>
<input type="submit" name="submit_file" value="Submit"/>
</form></body></html>
In this step we create a form to send csv file to 'import_file.php' page after manually converting
from excel file.
Step 2. Make a PHP file to import data into MySQL database
We make a PHP file and save it with a name import_file.php

57 | P a g e
<?php
$con=mysqli_connect("localhost","root","");
mysqli_select_db($con,'gsbms');
if(isset($_POST["submit_file"]))
{
$file = $_FILES["file"]["tmp_name"];
$file_open = fopen($file,"r");
while(($csv = fgetcsv($file_open, 1000, ",")) !== false)
{
$name = $csv[0];
$age = $csv[1];
$country = $csv[2];
mysqli_query($con,"INSERT INTO employees VALUES ('$name','$age','$country')");
}
}
?>
LO 3.3 Manage sessions and cookies

3.3.1 Introduction and use of cookies

1.Importance of cookies

An HTTP cookie (also called web cookie, Internet cookie, browser cookie, or simply cookie)
is a small piece of information which is stored at client browser. It is used to recognize the user.

Cookies were designed to be a reliable mechanism for websites to remember stateful information
or to record the user's browsing activity (including clicking particular buttons, logging in, or
recording which pages were visited in the past). They can also be used to remember arbitrary
pieces of information that the user previously entered into form fields such as names, addresses,
passwords, and credit card numbers. A cookie is often used to identify a user.

Once a cookie has been set, all page’s requests that follow return the cookie name and value.

58 | P a g e
Types of Cookies: Session based cookie which expires at the end of session and Persistent
cookies which are written on hard disk.

2. Cookies life time

Cookies can have an expiry time, if it is not set, then the cookie expires when the browser is closed.

3.Create cookies

Let’s now look at the basic syntax used to create a cookie.

<?php

setcookie(cookie_name, cookie_value, [expiry_time], [cookie_path], [domain], [secure],


[httponly]);

?>

HERE,

 setcookie is the PHP function used to create the cookie.


 cookie_name is the name of the cookie that the server will use when retrieving its value
from the $_COOKIE array variable. It’s mandatory.
 cookie_value is the value of the cookie and it’s mandatory.

 expiry_time is optional; it can be used to set the expiry time for the cookie such as 1 hour.
The time is set using the PHP time() functions plus or minus a number of seconds greater
than 0 i.e. time() + 3600 for 1 hour.

 cookie_path is optional; it can be used to set the cookie path on the server. The forward
slash “/” means that the cookie will be made available on the entire domain. Sub directories
limit the cookie access to the subdomain.

 domain is optional, it can be used to define the cookie access hierarchy


i.e. www.cookiedomain.com means entire domain
while www.sub.cookiedomain.com limits the cookie access
to www.sub.cookiedomain.com and its sub domains. Note it’s possible to have a
subdomain of a subdomain as long as the total characters do not exceed 253 characters.

 secure is optional, the default is false. It is used to determine whether the cookie is sent via
https if it is set to true or http if it is set to false.
 Httponly is optional. If it is set to true, then only client side scripting languages
i.e.JavaScript cannot access them.

59 | P a g e
Note: the php setcookie function must be executed before the HTML opening tag.

Let’s now look at an example that uses cookies.

We will create a basic program that allows us to store the user name in a cookie that expires after
60 seconds.

The code below shows the implementation of the above example “cookies.php”.

<?php
setcookie("user_name", "minageni", time()+ 60,'/'); // expires after 60 seconds
echo 'The cookie has been set for 60 seconds';
?>

Output:

The cookie has been set for 60 seconds

4.Retrieve cookies value

Create another file named “cookies_read.php” with the following code.

<?php
print_r($_COOKIE); //output the contents of the cookie array variable
?>

Output:

Array ([user_name] => minageni)

Note: $_COOKIE is a PHP built in super global variable.

5.Delete cookies

If you want to destroy a cookie before its expiry time, then you set the expiry time to a time that
has already passed.

Create a new filed named cookie_destroy.php with the following code

<?php

setcookie("user_name", "minageni", time() - 3600,'/');

60 | P a g e
?>
3.3.2 Introduction and use of sessions

1.Importance of sessions

A session creates a file in a temporary directory on the server where registered session variables
and their values are stored. This data will be available to all pages on the site during that visit.

The location of the temporary file is determined by a setting in the php.ini file
called session.save_path. Before using any session variable make sure you have setup this path.

2.Session life time

A session ends when the user loses the browser or after leaving the site, the server will terminate
the session after a predetermined period of time, commonly 30 minutes duration.

3.Create sessions

A PHP session is easily started by making a call to the session_start()function. This function first
checks if a session is already started and if none is started then it starts one. It is recommended to
put the call to session_start() at the beginning of the page.

Session variables are stored in associative array called $_SESSION[ ]. These variables can be
accessed during lifetime of a session.

Example

<?php

// Start the session

session_start();

?>

<!DOCTYPE html>

<html>

<body>

<?php

// Set session variables

61 | P a g e
$_SESSION["schoolname"] = "GLORY ACADEMY";

$_SESSION["level"] = "five";

echo "Session variables are set.";

?> </body>

</html>

4.Destroy session variables

A PHP session can be destroyed by session_destroy() function. This function does not need any
argument and a single call can destroy all the session variables. If you want to destroy a single
session variable then you can use unset() function to unset a session variable.

Here is the example to unset a single variable:

<?php
unset($_SESSION['counter']);
?>
Here is the call which will destroy all the session variables:

<?php
session_destroy();
?>

LO 3.4 Manage dynamic Forms

3.5.1 Application of HTML form processing methods

1.Embedded PHP scripts

When you embed PHP code in an HTML file, you need to use the .php file extension for that file,

so that your web server knows to send the file to PHP for processing.

The PHP language statements are enclosed in PHP tags with the following form:<?php ?>

Example

<!doctype html>

62 | P a g e
<html>

<head><title>Hello L5 software development</title></head>

<body>

<?php

echo"Hello Level 5 software development";


?>
</body>
</html>
Save this file on embeddphp.php

2.POST method

It appends form-data to the body of the HTTP request in such a way that data is not shown in
the URL. This method does not have any restrictions on data size to be sent. Submissions by form
with POST cannot be bookmarked. This method can be used to send ASCII(American Standard
Code for Information Interchange) as well as binary data like image and word documents. Data
sent by the POST method goes through HTTP header so security depends on the HTTP protocol.
You have to know that your information is secure by using secure HTTP. This method is a little
safer than GET because the parameters are not stored in browser history or in web server logs. It
also provides $_POST associative array to access all the sent information using the POST method.

It has the following syntax in php

<?php
$_POST['variable_name'];
?>

3. GET method

It appends form-data to the URL in name/ value pairs. The length of the URL is limited by 2048
characters. This method must not be used if you have a password or some sensitive information to
be sent to the server. It is used for submitting the form where the user can bookmark the result. It
is better for data that is not secure. It cannot be used for sending binary data like images or word
documents. It also provides $_GET associative array to access all the sent information using the
GET method.

63 | P a g e
It has the following syntax in php

<?php
$_GET['variable_name'];
?>

4.PHP form validation

Form validation is a necessary process before the data entered in the form is submitted to the
database. This is done to avoid unnecessary errors. In PHP Form validation, the script checks for
data in respective fields based on the rules set by the developer, and returns an error if it does not
meet the requirements.

You need to validate a few things:

1. Empty string

The code below checks that the field is not empty. If the user leaves the required field empty, it
will show an error message. Put these lines of code to validate the required field.

if (empty ($_POST["name"])) {
$errMsg = "Error! You didn't enter the Name.";
echo $errMsg;
} else {
$name = $_POST["name"];
}
2. Validate string

The code below checks that the field will contain only alphabets and whitespace, for example:
name. If the name field does not receive valid input from the user, then it will show an error
message.

$name = $_POST ["Name"];

if (!preg_match ("/^[a-zA-z]*$/", $name) ) {

64 | P a g e
$ErrMsg = "Only alphabets and whitespace are allowed.";

echo $ErrMsg;

} else {

echo $name;

3. Validate numbers

The below code validates that the field will only contain a numeric value. For example: Mobile
number. If the Mobile number field does not receive numeric data from the user, the code will
display an error message.

$mobileno = $_POST ["Mobile_no"];


if (!preg_match ("/^[0-9]*$/", $mobileno) ){
$ErrMsg = "Only numeric value is allowed.";
echo $ErrMsg;
} else {
echo $mobileno;
}
4. Input length

The input length validation restricts the user to provide the value between the specified range, for
Example - Mobile Number. A valid mobile number must have 10 digits.

The given code will help you to apply the length validation on user input.

$mobileno = strlen ($_POST ["Mobile"]);


$length = strlen ($mobileno);

if ( $length < 10 && $length > 10) {

65 | P a g e
$ErrMsg = "Mobile must have 10 digits.";
echo $ErrMsg;
} else {
echo "Your Mobile number is: " .$mobileno;
}

Example:

<!DOCTYPE html>
<html>
<head>
<style>
.error {color: #FF0001;}
</style>
</head>
<body>

<?php
// define variables to empty values
$nameErr = $mobilenoErr = $genderErr = $agreeErr= "";
$name = $mobileno = $gender = $agree="";

//Input fields validation


if ($_SERVER["REQUEST_METHOD"] == "POST") {

//String Validation
if (empty($_POST["name"])) {
$nameErr = "Name is required";
} else {
$name = input_data($_POST["name"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$nameErr = "Only alphabets and white space are allowed";
}
}

//Number Validation
if (empty($_POST["mobileno"])) {
$mobilenoErr = "Mobile no is required";
} else {
$mobileno = input_data($_POST["mobileno"]);
// check if mobile no is well-formed

66 | P a g e
if (!preg_match ("/^[0-9]*$/", $mobileno) ) {
$mobilenoErr = "Only numeric value is allowed.";
}
//check mobile no length should not be less and greator than 10
if (strlen ($mobileno) != 10) {
$mobilenoErr = "Mobile no must contain 10 digits.";
}
}

//Empty Field Validation


if (empty ($_POST["gender"])) {
$genderErr = "Gender is required";
} else {
$gender = input_data($_POST["gender"]);
}

//Checkbox Validation
if (!isset($_POST['agree'])){
$agreeErr = "Accept terms of services before submit.";
} else {
$agree = input_data($_POST["agree"]);
}
}
function input_data($data) {
$data = trim($data);
$data = stripslashes($data);
return $data;
}
?>

<h2>Registration Form</h2>
<span class = "error">* required field </span>
<br><br>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" >
Name:
<input type="text" name="name">
<span class="error">* <?php echo $nameErr; ?> </span>
<br><br>
Mobile No:
<input type="text" name="mobileno">
<span class="error">* <?php echo $mobilenoErr; ?> </span>
<br><br>
Gender:
<input type="radio" name="gender" value="male"> Male
<input type="radio" name="gender" value="female"> Female
<span class="error">* <?php echo $genderErr; ?> </span>

67 | P a g e
<br><br>
Agree to Terms of Service:
<input type="checkbox" name="agree">
<span class="error">* <?php echo $agreeErr; ?> </span>
<br><br>
<input type="submit" name="submit" value="Submit">
<br><br>
</form>

<?php
if(isset($_POST['submit'])) {
if($nameErr == "" && $mobilenoErr == "" && $genderErr == ""&& $agreeErr == "") {
echo "<h3 color = #FF0001> <b>You have sucessfully registered.</b> </h3>";
echo "<h2>Your Input:</h2>";
echo "Name: " .$name;
echo "<br>";
echo "Mobile No: " .$mobileno;
echo "<br>";
echo "Gender: " .$gender;
echo "<br>";
echo "Agree: " .$agree;
} else {
echo "<h3> <b>You didn't filled up the form correctly. </b> </h3>";
}
}
?>

</body>
</html>

The $_SERVER["PHP_SELF"] is a super global variable that returns the filename of the
currently executing script.

The htmlspecialchars() function converts special characters to HTML entities. This means that it
will replace HTML characters like < and > with &lt; and &gt;.

LU 4 USE OF PHP FRAMEWORKS

LO 4.1 Introduce Frameworks

4.1.1 Description of PHP frameworks

A framework is a platform that provides a foundation for developing software.

68 | P a g e
A PHP framework is a platform to create PHP web applications. PHP frameworks provide code
libraries for commonly used functions, cutting down on the amount of original code you need to
write. These frameworks save lots of time, stop rewriting the repeated code and provide rapid
application development (RAD). PHP frameworks help the developers to rapid development of
application by providing the structure.

There are many PHP frameworks but here we will discuss on the framework listed below:

1.CakePHP

CakePHP is an open-source web, rapid development framework that makes building web
applications simpler, faster and require less code.

It is a web development framework that uses the MVC model.

 Model is a class that deals with a database. For example, if we have users in an application
then we will have users model that deals with a database to query the table of users if we
have users model, then we will also have users table. We conclude from the example that
the model is going to have a table for that specific model.

 View is a class that deals with an HTML. Everything that we can see on the application in
the browser is the view or the representation.

 Controller is the middle-man that deals with both model and view. A controller is the class
that retrieves the data from the model and sends the data to the view class.

69 | P a g e
Advantages of using CakePHP in building web applications

 CakePHP allows a faster and easier web application building.


 It does not require much coding.
 The MVC architecture of the CakePHP framework organizes your work perfectly.
 Its in-built tools help you in input validation.
 CakePHP has extra features like caching, database access, and authentication.
 It has security features like CSRF (Cross-site request forgery) protection, XSS
injection protection, and Form tampering protection.
Disadvantages of attempting CakePHP as a beginner

 It takes much time to learn.


 Migrating from one version to another is an extremely difficult task.

2.Laravel
Laravel is a free and open-source PHP web framework, created by Taylor Otwell and intended for
the development of web applications following the model view controller (MVC) architectural
pattern and based on Symfony.
Laravel uses Artisan as a CLI that helps web developers to: migrate data, manage databases and
generate controllers, models and more

3. Symfony

70 | P a g e
Symfony is a free and open-source PHP web application framework and a set of reusable PHP
component libraries. It is for highly professional developer to build websites with PHP components
such as Drupal, PHPBB, laravel, and etc.

4.Zend
Zend framework is now Laminas project. It is modern framework for performing high end web
applications. This works based on Cryptographic and secure coding tools. It’s also the most used
PHP framework by enterprises.

5.Phalcon

Phalcon consist of object oriented classes to implement MVC architecture. MVC is a framework
which is used to develop web frameworks and desktop applications. Unlike other frameworks,
Phalcon optimizes performance due to its efficient memory utilization.

4.1.1.1 Comparisons of some frameworks

1.Difference Between Laravel and CakePHP

1. Laravel works on the object-oriented model while CakePHP works on the document-

oriented database model.

2. Laravel is based on Model View Controller (MVC) architecture while CakePHP is

implemented on Hierarchical Model View Controller (HMVC) architecture.

3. Laravel is not suitable for smaller projects while CakePHP is much more suitable to build

small-scale projects.

4. From the security level view, CakePHP plays a more crucial role than that of Laravel.

5. CakePHP is a more convenient choice than Laravel in terms of routing perspective

71 | P a g e
6. Laravel framework is a much better choice than CakePHP in case of rapid web

development and enhancement perspective.

7. Laravel framework is a much better choice than CakePHP in case of data backup and

handling perspective.

8. In the case of Laravel, there is a compiler functionality exists while there is no such feature

is present for CakePHP.

2.Difference Between Laravel and Symfony

i)Popularity

Laravel is the most popular PHP framework, but Symfony still ends up high on the list at number
two.

ii)Modularity and scaling

Symfony contains reusable components, which provide more modularity. It organizes the code in
a cleaner way, making it a great fit for larger and more complex projects. This is why many
experienced PHP developers prefer Symfony over Laravel.

iii)Templating engine

Symfony provides Twig as the default templating engine. Laravel’s default templating engine
Blade has lots for everyone, Blade provides advantages over Twig, as it allows for code reusability
that doesn’t exist in Twig.

iv)Database support

Both Laravel and Symfony provide object-relational mapping (ORM) for data access. With
Symfony, Doctrine handles ORM, while Eloquent provides ORM for Laravel. With ORM, data
manipulation becomes much simpler in either PHP framework.

72 | P a g e
v)Database migrations

With Symfony, database migrations are automatic. They just need simple definitions for the fields
in the model.When considering Laravel, database migrations are manual, but they don’t require
defining the fields.

LO 4.2 Implement the CakePHP framework

4.2.1 Installation of CakePHP 3.x

Before starting you should make sure your php version is up to date: php –v through CLI. You
should have 5.5.9 or higher. The cakephp is installed through Composer or you can download it
from github through https://github.com/cakephp/cakephp/releases.After downloading it from
GitHub, extract all the files in a folder called CakePHP in XAMPP.

After extracting it, let’s check whether it has been installed correctly or not by visiting the
following URL in browser − http://localhost/CakePHP/.

If you get this error message

Solution is to go in src/Template/Pages/home.ctp and comments these three lines

/*if (!Configure::read('debug')) :
throw new NotFoundException(
'Please replace src/Template/Pages/home.ctp with your own version or re-enable debug
mode.'
);
endif;*/

73 | P a g e
CakePHP uses Composer is a dependency management tool, as the officially supported method
for installation. To install composer on windows, download the executable file and run it.

4.2.2 CakePHP API (Application Programming Interface)

i)Class component

Base class for an individual component. Components provide reusable bits of controller logic that
can be composed into a controller. Components also provide request life-cycle callbacks for
injecting logic at specific points.

Components can provide several callbacks that are fired at various stages of the request cycle.
The available callbacks are:initialize(),startup(),beforeRender(),shutdown() and
beforeRedirect().

ii)Controller

Application controller class for organization of business logic. Provides basic functionality, such
as rendering views inside layouts, automatic model availability, redirection, callbacks, and more.

iii)Component Collection

Component collection is used as a registry for loaded components and handles loading and
constructing component class objects.

iv)EventManager

The event manager is responsible for keeping track of event listeners, passing the correct data to
them, and firing them in the correct order, when associated events are activated. You can create
multiple instances of the object to manage local events or keep a single instance and pass it around
to manage all events in your app.

v)EventListener

An event listener is a procedure or function in a computer program that waits for an event to occur.
The listener is programmed to react to an input or signal by calling the event's handler.

4.2.3 Develop a web application using CakePHP framework

1.CakePHP MVC Architecture

74 | P a g e
Note: Dispatcher converts requests into controller actions.
The CakePHP MVC architecture has three components: Model, View and Controller, and each
has its different role.

 Model
The Model layer is one that represents the logical part of your application. It retrieves the data and
convert it into meaningful concepts.
 View
The View layer shows the output to the end user. It processes the inputs provided by the Model
layer and generates specific output for the end user.
 Controller
The Controller layer is responsible for handling all requests coming from the users. It collects the
inputs from users and coordinate for the Model and View codes.
2.Naming conventions

CakePHP have its own naming convention standards to be used during PHP application
development. Whenever you have to create application using CakePHP you will need to create
following files first.

 One file to define your model.


 One file to define your controller.
 One or more files to represent the OUTPUT called view files.

So, while creating above files you will have to follow CakePHP naming convention standards and
it’s very important to the PHP developer to follow these standards.
A) Database table and field naming convention
 Table name must be in lowercase & plural. If there are more than one word in the table
name then words should be separated by underscore.

75 | P a g e
o Example: users, consultant_services, etc.
 Field name should also be in lowercase and if more than one word then separated by
underscore
o Example: id, consultant_service_name
 Foreign key name should be the (singular) name of the related table followed by _id.
o Example: user_id or consultant_service_id
B) Model naming convention
 Model file names are upper camel case, more than one word should be separated by
underscore.
o Example: User.php or Consultant_service.php
 Model class names are singular, usually this should be the database table name but in
singular format.
o Example: User or ConsultantService
Note: Model Files are located at app/models folder
C)Table naming convention
Table class names are plural, PascalCased and end in Table. UsersTable,
ArticleCategoriesTable, and UserFavoritePagesTable are all examples of table class names
matching the users, article_categories and user_favorite_pages tables respectively.

Entity class names are singular PascalCased and have no suffix. User, ArticleCategory, and
UserFavoritePage are all examples of entity names matching the users, article_categories
and user_favorite_pages tables respectively.

D) Controller naming Convention


 Controller file names are plural and upper camel case and filenames also end with
‘Controller.php’.
o Example: UsersController.php or ConsultantservicesController.php
Note: Controller Files are located at app/Controller folder
E) View naming Convention
View files are located at /app/views and into that a folder is created with its respective controller
name, if more than one word then separated by underscore.
• View file names are function_name.ctp (The function name is the name of the function you have
defined in your appropriate Controller file.)
Summary:

76 | P a g e
 Database table: “articles”
 Table class: ArticlesTable, found at src/Model/Table/ArticlesTable.php
 Entity class: Article, found at src/Model/Entity/Article.php
 Controller class: ArticlesController, found at src/Controller/ArticlesController.php
 View template, found at src/Template/Articles/index.ctp

Application

config/routes.php
$routes->connect('/users/add'.['controller'=>'Users','action'=>'add']);
$routes->connect('/users',['controller'=>'Users','action'=>'index']);
$routes->connect('/users/edit',['controller'=>'Users','action'=>'edit']);
$routes->connect('/users/delete',['controller'=>'Users','action'=>'delete']);

src/controller/UsersController.php
<?php
namespace App\Controller;
use App\Controller\AppController;
use Cake\ORM\TableRegistry;
use Cake\Datasource\ConnectionManager;
use Cake\Auth\DefaultPasswordHasher;
class UsersController extends AppController{
/*Function for inserting a new record */
public function add(){
if($this->request->is('post'))
{
$username=$this->request->data('username');
$hashPswdobj=new DefaultPasswordHasher;
$password=$hashPswdobj->hash($this->request->data('password'));
$users_table=TableRegistry::get('users');

77 | P a g e
$users=$users_table->newEntity();
$users->username=$username;
$users->password=$password;
if($users_table->save($users))

echo"User is added.";
}
}
/*Function for displaying records */
public function index()
{
$users=TableRegistry::get('users');
$query=$users->find();
$this->set('results',$query);
}
/*Function for editing a record */
public function edit($id){
if($this->request->is('post'))
{
$username=$this->request->data('username');
$password=$this->request->data('password');
$users_table=TableRegistry::get('users');
$users=$users_table->get($id);
$users->username=$username;
$users->password=$password;
if($users_table->save($users))
echo"User is updated";
$this->setAction('index');
}
else{
$users_table=TableRegistry::get('users')->find();
$user=$users_table->where(['id'=>$id])->first();
$this->set('username',$users->username);
$this->set('password',$users->password);
$this->set('id',$id);
}
}
/*Function for deleting a record */
public function delete($id){
$users_table=TableRegistry::get('users');
$users=$users_table->get($id);
$users_table->delete($users);
echo"User deleted successfully.";
$this->setAction('index');

78 | P a g e
}

}
?>

src/Template/Users/add.ctp
<?php
echo $this->Form->create("users",array('url'=>'/users/add'));
echo $this->Form->input('username');
echo $this->Form->input('password');
echo $this->Form->button('Submit');
echo $this->Form->end();
?>

src/Template/Users/index.ctp
<?= $this->Html->link("Add User",["action" =>"add"]) ?>
<table>
<tr>
<td>ID</td>
<td>Username</td>
<td>Password</td>
<td>Edit</td>
<td>Delete</td>
</tr>
<?php
foreach($results as $row):
echo"<tr><td>".$row->id."</td>";
echo"<td>".$row->username."</td>";
echo"<td>".$row->password."</td>";
echo"<td><a href='".$this->url->build(["controller"=>"Users","action"=>"edit",$row-
>id])."'>Edit</a></td>";
echo"<td><a href='".$this->url->build(["controller"=>"Users","action"=>"delete",$row-
>id])."'>Delete</a></td></tr>";
endforeach;
?>
</table>

src/Template/Users/edit.ctp
<?php
echo $this->Form->create("Users",array('url'=>'/users/edit/'.$id));
echo $this->Form->input('username',['value'=>$username]);

79 | P a g e
echo $this->Form->input('password',['value'=>$password]);
echo $this->Form->button('Submit');
echo $this->Form->end();
?>

4.3 Implement the Laravel framework


4.3.1 Installation of Laravel framework
For managing dependencies, Laravel uses composer. Make sure you have a composer installed on
your system before you install Laravel.
Step1: Visit the following URL and download composer to install it on your system.
https://getcomposer.org/download/
Step2: After the Composer is installed, check the installation by typing the Composer command
in the command prompt as shown in the screenshot.

80 | P a g e
To install Laravel, first of all, you have to go C:/xampp/htdocs directory, to navigate it type
following command in your command prompt: cd c:/xampp/htdocs

Step3: Create a new directory in htdocs for your new Laravel project. Type the following
command there to install Laravel.

composer create-project laravel/laravel laravelproject

After running this command, it should start downloading dependencies that are required to create
the Laravel project.

Step4: The above command will install Laravel in the current directory. Start the Laravel service
by executing the following command.

81 | P a g e
php artisan serve

Step5: After executing the above command, you will get the URL(http://127.0.0.1:8000/)
Step6: Copy that URL and paste it in the browser. If you see the following screen, it implies
Laravel has been installed successfully.

4.3.2 Laravel APIs


1.RESTful APIs
REST stands for REpresentational State Transfer and is an architectural style for network
communication between applications, which relies on a stateless protocol (usually HTTP) for
interaction.
In RESTful APIs, we use the HTTP verbs as actions, and the endpoints are the resources acted
upon. We’ll be using the HTTP verbs for their semantic meaning:
 GET: retrieve resources
 POST: create resources
 PUT: update resources
 DELETE: delete resources

82 | P a g e
4.3.3 Development of web application using Laravel
1.Root directory
Directory Description

app The app directory holds the base code for your Laravel application.

bootstrap The bootstrap directory contains all the bootstrapping scripts used for
your application.

config The config directory holds all your project configuration files (.config).

database The database directory holds your database files.

public The public directory helps to start your Laravel project and maintains
other necessary files such as JavaScript, CSS, and images of your
project.

resources The resources directory holds all the Sass files, language (localization)
files, templates (if any).

routes The routes directory contains all your definition files for routing, such
as console.php, api.php, channels.php, etc.

storage The storage directory holds your session files, cache, compiled
templates as well as miscellaneous files generated by the framework.

test The test directory holds all your test cases.

83 | P a g e
vendor The vendor directory holds all composer dependency files.

2.Application directory
It is the application folder and includes the entire source code of the project. It contains console
(it has Kernal.php calls the commands), exceptions (This folder contains all the methods needed
to handle exceptions. It also contains the file handle.php that handles all the exceptions.), Http
(controller and middleware), models and providers (This folder includes all the service providers
required to register events for core servers and to configure a Laravel application.).
3.Namespacing
Namespaces can be defined as a class of elements in which each element has a unique name to
that associated class. It may be shared with elements in other classes.
The use keyword allows the developers to shorten the namespace.
use <namespace-name>;
The default namespace used in Laravel is App, however a user can change the namespace to match
with web application. Creating user defined namespace with artisan command is mentioned as
follows:
php artisan app:name SocialNet
4.Service providers
Service providers are the central place of all Laravel application helping. Your own application,
as well as all of Laravel's core services, are helped via service providers.
If you open the config/app.php file included with Laravel, you will see a providers’ array. These
are all of the service provider classes that will be loaded for your application. By default, a set of
Laravel core service providers are listed in this array. These providers bootstrap the core Laravel
components, such as the mailer, queue, cache, and others. Many of these providers are "deferred"
providers, meaning they will not be loaded on every request, but only when the services they
provide are actually needed.
All service providers extend the Illuminate\Support\ServiceProvider class. Most service providers
contain a register and a boot method. Within the register method, you should only bind things
into the service container. You should never attempt to register any event listeners, routes, or any
other piece of functionality within the register method.
The Artisan CLI can generate a new provider via the make:provider command:
php artisan make:provider RiakServiceProvider
5.Service containers

84 | P a g e
The Laravel service container is a powerful tool for managing class dependencies and performing
dependency injection. Dependency injection is a fancy phrase that essentially means this: class
dependencies are "injected" into the class via the constructor method.
Let's look at a simple example:
<?php

namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use App\Repositories\UserRepository;
use App\Models\User;

class UserController extends Controller


{
protected $users;
public function __construct(UserRepository $users)
{
$this->users = $users;
}
public function show($id)
{
$user = $this->users->find($id);

return view('user.profile', ['user' => $user]);


}
}
In this example, the UserController needs to retrieve users from a data source. So, we will inject a
service that is able to retrieve users. In this context, our UserRepository most likely uses Eloquent
to retrieve user information from the database.
6.Contracts
Laravel's "contracts" are a set of interfaces that define the core services provided by the framework.
For example, an Illuminate\Contracts\Queue\Queue contract defines the methods needed for
queueing jobs, while the Illuminate\Contracts\Mail\Mailer contract defines the methods needed
for sending e-mail.
7.Services
Resources directory contains the files which enhances your web application. The sub-folders
included in this directory and their purpose is explained below
 assets − The assets folder include files such as LESS and SCSS, that are required for
styling the web application.

85 | P a g e
 lang − This folder includes configuration for localization or internalization.
 views − Views are the HTML files or templates which interact with end users and play a
primary role in MVC architecture.

8.Database
The configuration for Laravel's database services is located in your
application's config/database.php configuration file. In this file, you may define all of your
database connections, as well as specify which connection should be used by default. Most of the
configuration options within this file are driven by the values of your application's environment
variables. Examples for most of Laravel's supported database systems are provided in this file.
As the name suggests, this directory includes various parameters for database functionalities. It
includes three sub-directories:
 Seeds contains the classes used for unit testing database.
 Migrations this folder helps in queries for migrating the database used in the web
application.
 Factories, this folder is used to generate large number of data records.

9.Building a list of links

Step 1: Download Laravel and Other Project Files


Before we begin, let's first ensure that we have a system that can support Laravel. According to
the documentation, Laravel requires the following:
• PHP 5.3.x - Laravel makes use of a lot of PHP 5.3-specific features, like closures, late-static
binding and namespaces.
• The FileInfo library - this is enabled by default in PHP 5.3, but on Windows systems, you
might need to add the extension in your PHP.ini configuration file.
• Mcrypt library - this is used by Laravel for encryption and hash generation, and typically comes
preinstalled with PHP.
Once we're done setting up the environment, let's download Laravel and all the libraries we'll be
using for Instapics. Download the following files and place them within a web-accessible folder:

86 | P a g e
• Laravel - http://laravel.com (Currently v3.2.1)
• Twitter Bootstrap - http://twitter.github.com/bootstrap/ (Currently v2.0.4)
• jQuery - http://jquery.com (Currently v1.7.2)
Inside Laravel's root folder, you'll find a public folder - this is where all publicly accessible files
should be stored. Laravel v3.2.1 has some premade folders inside the public folder for our assets,
css, img, and js folders. Place the Twitter Bootstrap and jQuery files in their corresponding folders.
At this point, your folder structure should look similar to the following:

Twitter Bootstrap will have some files inside the css, img, and js folders, and jQuery will be inside
the js folder.
Step 2: Setup Laravel's Encryption Key, Pretty URLs and Virtual Host
If you are new to Laravel, then you should know that you have the provision to create configuration
files for Laravel application. After installing Laravel, you need to perform the permission writing
for your storage directory along with the bootstrap/cache.
Next, you have to do is, generating the application key for session securing and encrypted data
keys also. In case, the root directory doesn't have the .env file, in that case, you will have to rename
the file .env.example to .env and run the command mentioned below where you've installed the
Laravel:
php artisan key: generate
You can see in the .env file the newly generated key. Moreover, it is also possible to configure
time zone as well as a locale in the config/app.php file of your project.
Laravel allows us for running application for a diverse environment like testing, production, etc.
For configuring your application's environment, you will need the .env file which is in the root
directory of the project. When you install composer for Laravel, then this file gets generated or

87 | P a g e
created automatically by the composer itself, but if you don't install then have to rename the
specific file with the name .env.example to .env only.
You can configure the database for your application using the config/database.php file of your
project. Setting the configuration constraint utilized by various databases can also be done, and
moreover, Laravel also allowed us to use the default one as well.
Websites are regularly modified. As a developer for this, you have to put your site in maintenance
mode. In this advanced framework, it becomes easier to do that by using two artisan commands.
Let's see how to use the commands: For starting your project maintenance approach, the following
command is required:
php artisan down
After changing the required stuff, when it is time to re-run your project, the following command
is required:
php artisan up
Step 3: Setup Routing

Routing is one of the essential concepts in Laravel. Routing in Laravel allows you to route all your
application requests to its appropriate controller.

All Laravel routes are defined inside the route files located in the routes directory. When we create
a project, then a route directory is created inside the project. The route/web.php directory contains
the definition of route files for your web interface. The routes in web.php are assigned with the
web middleware group that provides the features like session state and CSRF protection. The
routes defined in routes/api.php are assigned with the API middleware group, and they are
stateless.

We will start by defining the routes in routes/web.api file.

The routes defined in the routes/web.php can be accessed by entering the defined URL to the
browser. Let's understand this through an example.

<?php
Route::get('/', function ()
{
return view ('welcome');
});

In the above case, Route is the class which defines the static method get(). The get() method
contains the parameters '/' and function() closure. The '/' defines the root directory and function()
defines the functionality of the get() method.

88 | P a g e
In the above route, the url is '/'; therefore, we entered the localhost/laravelproject/public URL in
the web browser.

As the method returns the view('welcome'), so the above output shows the welcome view of the
Laravel.

Let's see another example.

Now, we provide another url in this above example.

<?php
Route::get('/example', function ()
{
return "Hello Level 5 SOD";
});

In the above example, the route is defined in which URL is '/example', so we need to enter the
URL "localhost/laravelproject/public/example" in the web browser.

There are two types of parameters we can use:

o Required Parameters
o Optional Parameters

Required Parameters

The required parameters are the parameters that we pass in the URL. Sometimes you want to
capture some segments of the URI then this can be done by passing the parameters to the URL.
For example, you want to capture the user id from the URL.

Let's see the example without route parameters.

<?php
Route::get('/', function()
{
return "This is a home page";
}
);
Route::get('/about', function()
{
return "This is a about us page";
}
);
Route::get('/contact', function()
{

89 | P a g e
return "This is a contact us page";
}
);

Let's see the example with route parameters.

<?php
Route::get('/post/{id}', function($id)
{
return "id number is : ". $id;
}
);

The route parameters are enclosed within {} brackets, and parameters must contain alphabetic
characters. It should not contain '-' character, and instead of using this character, you can use '_'
character.

Route parameters are available in the route callbacks. Syntax of route parameters is given below:

Name of the callback/controller arguments

Where controller arguments are the route parameters.

Let's see the example with multiple route parameters.

<?php
//We can also pass the multiple parameters.

Route::get('/post/{id}/{name}', function($id,$name)
{
return "id number is : ". $id ." ".$name;
}
);

Optional Parameters

Suppose you want to specify the route parameter occasionally, in order to achieve this, you can
make the route parameter optional. To make the route parameter optional, you can place '?' operator
after the parameter name. If you want to provide the optional parameter, and then make sure that
you have also provided the default value to the variable.

Let's understand through some examples.

Example 1:

90 | P a g e
Route::get('user/{name?}', function ($name=null) {
return $name;
});

Navigating from one route to another using named routes

We can also navigate from one route to another route by using named routes.

Step 1: Define the route in the web.php file.

Route::get('/',function()
{
return view('student');
});

Route::get('student/details',function()
{
$url=route('student.details');
return $url;
})->name('student.details');

Step 2: Move to the resources folder and then click on the views folder.

Step 3: Create a new file and it is named as student.blade.php.

<a href="{{ route('student.details') }}">Student</a>

Step 3. Create your First Laravel Controller


Controllers are used to handle the request logic within the single class, and the controllers are
defined in the "app/http/Controllers" directory. Laravel framework follows the MVC (Model
View Controller) architecture in which controllers act as moving the traffic back and forth between
model and views.
The default file of controller is available in the app/http/Controllers directory.
<?php
namespace App\Http\Controllers;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Routing\Controller as BaseController;

91 | P a g e
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
class Controller extends BaseController
{
use AuthorizesRequests, DispatchesJobs, ValidatesRequests;
}

In the above code, the namespace is used as it allows you to use the same function names and
classes in the different parts of the same application. For example,

namespace App\Http\functions1;
namespace App\Http\functions2;

Suppose we have to run the function having the name, i.e., RunQuery(). They are available in
different directories functions1 and functions2, so we can say that namespace avoids the collision
between the same function names.

use is used to import the class to the current file.

Creating a Controller
Step 1: Type the command "php artisan make:Controller PostsController" in CMD Window
to create the Controller.
With this command provided above, we get the class without the functions such as create, update,
or delete.

This command php artisan make:controller --resource PostsController allows you to create
the controller which contains some default functions. With this command, laravel will create
controller with the following functions:

 create(): It is used to create a new resource.


 store(): It is used to store the specified resource.
 update(): It is used to update the specified resource in the storage.
 destroy(): It is used to remove the specified resources from the storage.

Step 2: Now move to your project and see whether the PostsController file has been created or
not. The path of the file is:

92 | P a g e
C:\xampp\htdocs\laravelproject\app\Http\Controllers

Routing controllers allow you to create the controller classes with methods used to handle the
requests.
1.Open the web.php file and write the following code:
use App\Http\Controllers\PostsController;
Route::get('/post',[PostsController::class,'index']);
In the above code, '/post' is the URL that we want to access, and PostsController is the name of
the controller. The 'index' is the name of the method available in the PostsController.php file,
and index indicates that the index() method should be hit when we access the '/post' url.
2.Add the code which is shown below as highlighted in PostsController.php file:

public function index()


{
return "Hello L5SOD5 ";
}
When declaring a resource route, you may specify a subset of actions the controller should handle
instead of the full set of default actions:
use App\Http\Controllers\PhotoController;

Route::resource('photos', PhotoController::class)->only([
'index', 'show'
]);

Route::resource('photos', PhotoController::class)->except([
'create', 'store', 'update', 'destroy'
]);
Controller Middleware

We can also assign the middleware to the controller's routes within your route files.

There are various ways of assigning the middleware to the controller:

Assigning the middleware to the controller in the web.php file.

We can assign the middleware to the controller in the web.php file. Following are the steps
required to assign the middleware:

93 | P a g e
Step 1: First, we create a controller. We already have created the controller named
as PostsController in the previous topic.

Step 2: Now, we create the middleware, which we want to assign to the PostsController. We use
the following command to create the middleware:

php artisan make:middleware Check

Step3: Open the Check.php file created in laravelproject/app/http/Middleware directory. And add
this line in function echo "Middleware in Laravel <br><br>";
Step 4: Now, we have to add the path of the middleware Check.php in kernel.php file.
protected $routeMiddleware = [
'auth' => \Illuminate\Auth\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
'can' => \Illuminate\Auth\Middleware\Authorize::class,
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
'age' => \App\Http\Middleware\CheckAge::class,
'check'=>\App\Http\Middleware\Check::class
];

In the above code, the highlighted statement adds the path of the middleware, i.e., Check.

Step 5: Add the following code in the web.php file to assign the middleware to
the PostsController.

Route::get('/post',[PostsController::class,'create'])->middleware('check');

Step 6: Enter the URL http://localhost/laravelproject/public/post to the web browser, then see the
output.

Views

Views contain the html code required by your application, and it is a method in Laravel that
separates the controller logic and domain logic from the presentation logic. Views are located in
the resources folder, and its path is resources/views.

94 | P a g e
Let's see the simple example of views.

Suppose we want to create the view of the contact.

Step 1: First, we create the view file named Contact.php in resources/views directory.

Contact.php

<html>
<body>
<h1>Name of the Contact is : <?php echo $name; ?></h1>
</body>
</html>
Step 2: Add the following code in web.php.

Route::get('/contact', function(){
return view('Contact',['name'=>'John']);
});

In the above code, view() method contains two arguments. The first argument is the name of the
file that contains the view, and the second argument is the array passed to the given file. In array,
we are passing the name variable to the Contact.php file.

Step 3: Enter the URL http://localhost/laravelproject/public/contact to the web browser for


getting the output.

Example 2:

In this example, we use the view() method in the Controller class.

Step 1: First, I need to create a controller. Suppose I have created the controller named
'PostsController', and then add the code given below in a PostsController.php file.

Step 2: Now, we create the about.blade.php file in which we add the html code.

<html>

<body>

<h1>About Us</h1>

</body>

</html>

95 | P a g e
Step 3: Last step is to add the route in web.php file.

Route::get('/pos',[PostsController::class,'display']);

Step 4: Enter the URL http://localhost/laravelproject/public/pos to the web browser.


Laravel Forms
Laravel handles the html forms by providing various in-built tags. Laravel generates the major
elements required for an HTML. In order to generate the html elements, we need to add the html
package in Laravel by using the composer.
composer require "laravelcollective/html":"^5.4.0"

We can open a form by using the code given below:

{Form::open(['url' => 'post/create'])}


//
{Form::close()}

In laravel forms, the default method is assumed to be 'post' method if not mentioned, but we are
free to specify any other method. Since forms support Post, Put, Delete, and Get methods, so these
methods can be added in a form by using the hidden method field.

If we want to use the put method in a form, then the code is given below:

Form::open(['url'=>'Post/create , 'method'=>'Put''])

We can also open forms that point to the named routes or controller actions.

Form.open(['route' => 'route.name'])


Form.open(['action' => 'Controller@method'])
Generating HTML Elements
o Label

Label is a normal text which appeared in the Html form. The syntax for writing a label element in
Laravel is given below:

Form::label('phone_no', 'Phone Number');

96 | P a g e
We can also specify the additional attributes in a label element.

Form::label('phone_no', 'Phone Number',['class'=>'phone_no']);

In this case, we have added the 'class' as an attribute in a Label element.

o Text

Text is an area where the user can input their data. The syntax for generating a text area in Laravel
is given below:

Form::text('email');

We can also specify the default value to the text box.

Form::text('email','akshita123@gmail.com');

o Password

Password is an html element in a form that captures the user input, and each character is
represented in the form of (*) instead of displaying the entered digits. The syntax for the password
field is given below:

Form::password('password',['class'=>'pass']);

o Checkboxes

We can create the checkbox as given below:

Form::checkbox('name','value');

By default, the checkbox is unchecked. We can also check the box by providing true value to the
checkbox element.

Form::checkbox('name','value',true);

o Radio buttons

We can create the radio button as given below:

Form::radio('name','value');

By default, the radio button is not selected. We can also select the radio button by providing true
value to the radio button element.

97 | P a g e
Form::radio(''name','value',true);

o Number

We can also add the number input field in a form. Syntax for the number input field is given below:

Form::number('name','value');

The file input field is an html element used in a form for file uploading. Syntax for file input field
is given below:

Form::file('image');

Where, image is the name of the file input field.

o Drop-down list

The drop-down element is used to display the list of all the pre-defined options. The syntax for
creating a drop-down menu is given below:

Form::select('digits', [1,2,3,4,5,6])

We can also set the drop-down list with a default value:

Form::select('digits',[1,2,3,4,5,6],'2')

The above code sets the value of the drop-down list with a second element of the array, i.e., 3 as
indexing starts with 0.

Generating Grouped list

We can generate the grouped list through the drop-down element. Let's see this through an
example:

Form::select('animal',[
'fruits' => ['Apple','Mango','Orange'],
'Vegetables' => ['Potato','Tomato','Cabbage'],
])
Generating drop-down list with a range.
Form::selectRange('number',1,30)
Generating drop-down list with a month names.
Form.selectMonth('month')

o Date

98 | P a g e
year, month, and day. The syntax for generating a date input field is given below:

Form::date('name',\Carbon\Carbon::now())

o Buttons

We can also create the button in a web form by using the button field in a form. Let's see its syntax:

Form::submit('Click me!!')

The above line creates the submit button with the name "Click me!!".

Restful Resource Controllers


Often while making an application we need to perform CRUD (Create, Read, Update, Delete)
operations. Laravel makes this job easy for us. Just create a controller and Laravel will
automatically provide all the methods for the CRUD operations. You can also register a single
route for all the methods in routes.php file.
Example
Step 1 − Create a controller called MyController by executing the following command.
php artisan make:controller MyController
Step 2 − Add the following code in app/Http/Controllers/MyController.php file.
app/Http/Controllers/MyController.php

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request; use
App\Http\Requests;
use App\Http\Controllers\Controller;
class MyController extends Controller {

99 | P a g e
public function index() { echo 'index';
}
public function create() { echo
'create';
}
public function store(Request $request) { echo 'store';
}
public function show($id) { echo
'show';
}
public function edit($id) { echo 'edit';
}
public function update(Request $request, $id) { echo 'update';
}
public function destroy($id) { echo
'destroy';
}}
Step 3 − Add the following line of code in app/Http/routes.php file.
app/Http/routes.php
Route::resource('my','MyController');
Step 4 − We are now registering all the methods of MyController by registering a controller with
resource. Below is the table of actions handled by resource controller.
Verb Path Action Route
Name
GET /my index my.index
GET /my/create create my.create
POST /my store my.store
GET /my{my} show my.show
GET /my{my}/edit edit my.edit
PUT/PATCH /my{my} update my.update
DELETE /my{my} destroy my.destroy

100 | P a g e
Step 5 − Try executing the URLs shown in the following table.
URL Description Output Image
http://localhost:8000/my Executes index method of index
http://localhost:8000/my/create MyController.php index create
Executes create method of
http://localhost:8000/my/l MyController.php create show
Executes show method of
http://localhost:8000/my/l/edit MyController.php show edit
Executes edit method of

Laravel Artisan Commands Cheat Sheet


Let’s have closer look at top 10 Laravel Artisan Commands for developers while building laravel
applications.
Command Description & Output
php artisan –version Check the current version of laravel
installation? Output: Laravel Framework
version 5.2.45
php artisan down Put Laravel application in “maintenance
mode” Output: Application is now in
maintenance mode.
php artisan env Display the environment laravel is running
Output: Current application environment: local
php artisan migrate Run Database migrations This executes all the
defined migrations and create database tables.
php artisan serve To start Laravel project. By, default this hosts
the application locally at localhost:8000 You
can server with different hostname and post
using “–host” and “–port” options
respectively.
php artisan up Bring UP the laravel application out of
maintenance mode
php artisan auth:clearresets Flush the expired password tokens
php artisan cache:clear Flush the application cache
php artisan cache:table Create a migration for the cache database table
php artisan config:cache Create a cache file for faster configuration
loading
php artisan config:clear Remove the configuration cache file
php artisan make:auth Scaffold basic login and registration views and
routes
php artisan make:controller TechCluesBlog Create a new controller class using artisan
command

101 | P a g e
php artisan make:migration my_blog_post Create a new migration file. Output: Created
Migration:
2019_01_27_094045_my_blog_post The new
migration file
2019_01_27_094045_my_blog_post.php will
be created under ../database/migrations./
php artisan make:model MyBlogPost Create a new Eloquent model class. Output:
Model created successfully. The new Model
file “MyBlogPost.php” will be created in
app/Models or ../app/..
php artisan route:list List all registered routes
php artisan route:clear Remove the route cache file
php artisan route:cache Create a route cache file for faster route
registration
php artisan vendor:publish Publish any publishable assets from vendor
packages
php artisan view:clea Clear all compiled view files

Step 4. Create your first Laravel View with the Blade Templating Engine
In MVC framework, the letter “V” stands for Views. It separates the application logic and the
presentation logic. Views are stored in resources/views directory. Generally, the view contains
the HTML which will be served by the application.
Example
Observe the following example to understand more about Views –
Step 1 − Copy the following code and save it at resources/views/test.php
<html>
<body>
<h1>Hello, World</h1>
</body> </html>
Step 2 − Add the following line in app/Http/routes.php file to set the route for the above view.
app/Http/routes.php
Route::get('/test', function() { return
view('test'); });
Step 3 − Visit the following URL to see the output of the view. http://localhost:8000/test
Step 4 − The output will appear as shown in the following image.

102 | P a g e
Passing Data to Views
While building application it may be required to pass data to the views. Pass an array to view
helper function. After passing an array, we can use the key to get the value of that key in the HTML
file. Example
Observe the following example to understand more about passing data to views –
Step 1 − Copy the following code and save it at resources/views/test.php
<html>
<body>
<h1><?php echo $name; ?></h1>
</body>
</html>
Step 2 − Add the following line in app/Http/routes.php file to set the route for the above view.
app/Http/routes.php
Route::get('/test', function() {
return view('test',[‘name’=>’John MUHIRE’]); });
Step 3 − The value of the key name will be passed to test.php file and $name will be replaced by
that value.
Step 4 − Visit the following URL to see the output of the view. http://localhost:8000/test
Step 5 − The output will appear as shown in the following image.

Sharing Data with all Views


We have seen how we can pass data to views but at times, there is a need to pass data to all the
views. Laravel makes this simpler. There is a method called share() which can be used for this
purpose. The share() method will take two arguments, key and value. Typically share() method
can be called from boot method of service provider. We can use any service provider,
AppServiceProvider or our own service provider.
Example
Observe the following example to understand more about sharing data with all views –
Step 1 − Add the following line in app/Http/routes.php file. app/Http/routes.php
Route::get('/test', function() { return
view('test');

103 | P a g e
});
Route::get('/test2', function() { return
view('test2'); });
Step 2 − Create two view files — test.php and test2.php with the same code. These are the two
files which will share data. Copy the following code in both the files. resources/views/test.php &
resources/views/test2.php
<html>
<body>
<h1><?php echo $name; ?></h1>
</body>
</html>
Step 3 − Change the code of boot method in the file app/Providers/AppServiceProvider.php as
shown below. (Here, we have used share method and the data that we have passed will be shared
with all the views.) app/Providers/AppServiceProvider.php
<?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
class AppServiceProvider extends ServiceProvider {

/**
* Bootstrap any application services.
*
* @return void
*/
public function boot() {
view()->share('name', 'Virat Gandhi');
}
/**
* Register any application services.

104 | P a g e
*
* @return void
*/
public function register() {
//
}}
Step 4 − Visit the following URLs. http://localhost:8000/test http://localhost:8000/test2
Step 5 − The output will appear as shown in the following image.
Root directory
The Root Directory Structure of Laravel
The public directory helps in starting your Laravel project and also holds other scripts (JavaScript
and CSS) as well along with images required for your project. resources. This directory is one of
the most important directories inside which you will find some other subdirectories. These are:
routes storage
Directory Description
app The app directory holds the base code for your
Laravel application.
bootstrap The bootstrap directory holds all the
bootstrapping scripts used for your application.
config The config directory holds all your project
configuration files (.config).
database The database directory holds your database
files.
routes The routes directory hold all your definition
files for routing such as console.php, api.php,
routes channels.php etc.
storage The storage directory holds your session files,
cache, compiled templates as well as
miscellaneous files generated by the
framework.
test The test directory holds all your test cases.
vendor The vendor directory holds all composer
dependency files.

Application directory

105 | P a g e
This is another Laravel directory which holds other subdirectories for additional purposes. These
are:
Directory Description
Console The Console directory contains all your project
artisan commands.
Events The Events directory hold event files that your
laravel application may pop up. Events is
Events used for sending messages or signals to
other parts of the laravel project that any action
had taken place within the project
Exceptions The Exceptions directory holds your laravel
project's exception handling files which
Exceptions handles all the exceptions thrown
by your Laravel project.
Http The Http directory holds different filters,
requests, and controllers. The Jobs directory
holds all lineup jobs in this directory. But it
does not get created Jobs initially, rather, you
need to type and run this artisan command:
make:job
Listeners The Listeners directory holds all your project's
handler class for which are used for Listeners
receiving and handling events.
Mail The Main directory holds all the emails send
by through your Laravel project, and this Mail
directory needs to be created using the
command: make:mail
Notifications The Notifications directory contains all your
transactional notifications sent through your
Notifications Laravel project, and this
directory needs to be created using the
command: make:notification
Policies The policies directory holds different policies
for your laravel project.
Providers The Providers directory is used for containing
different service providers.
Rules The Rules directory hold all the different
objects related to custom validation rules, and
Rules this directory needs to be created using
the command: make:rule

Namespacing

106 | P a g e
Namespaces can be defined as a class of elements in which each element has a unique name to that
associated class. It may be shared with elements in other classes.
Declaration of namespace
The use keyword allows the developers to shorten the namespace.
use <namespace-name>;
The default namespace used in Laravel is App, however a user can change the namespace to match
with web application. Creating user defined namespace with artisan command is mentioned as
follows –
php artisan app:name SocialNet
The namespace once created can include various functionalities which can be used in controllers
and various classes.
Service providers
Service providers are the central element of the initialization process where all the relevant and
required code is loaded by PHP. This includes all the essentials from the framework itself, but also
any own and custom code you need to load.
Bootstrap Service Providers
During the initializing process, the code bootstraps itself. That means it gets ready to go by
registering service container bindings, event listeners, middleware, configuration, and routes.
Service providers are therefore a central place to set up your application.
In the config/app.php you will find an array of providers listing all the service provider classes
that are loaded during bootstrapping. Beware that many of the service provider classes may be so-
called deferred providers. It means they are only loaded upon request, and not always included by
default. Making a provider deferred works well for classes that only need to be loaded sometimes
because it reduces the performance overhead and loads time of your web application.
Custom Service Providers
The code below is an example of a custom service provider. It extends the
Illuminate\Support\ServiceProvider class which is an abstract that requires you to define at least
a method called register. The purpose of the register method is to bind values in the service
container.
Writing Service Providers
All service providers extend the Illuminate/Support/ServiceProvider class. Most service
providers contain a register and a boot method. Within the register method. You should only blind
things into the service container. You should never attempt to register any event listeners, routes,
or any other piece of functionality within the register method. The Artisan CLI can generate a new

107 | P a g e
provider through the make::provider command. php artisan make:provider
RiakServiceProvider
Copy
The Register Method Within the register method, you should only blind thing into the service
container. You should never attempt to register any event listeners, routes, or any other piece of
functionality within the register method. Otherwise, you may accidentally use a service that is
provided by a service provider which has not loaded yet. Let's look at this code sample
<?php
namespace App\Providers; use
Riak\Connection;
use Illuminate\Support\ServiceProvider;
class RiakServiceProvider extends ServiceProvider
{
public function register()
{
$this->app->singleton(Connection::class, function ($app)
{
return new Connection(config('riak')); });
}}
Copy
This service provider only defines a register method, and uses that method to define an
implementation of Riak//Connection in the service container.

The Boot Method

So, what if we need to register a view composer within our service provider? This should be done
within the boot method. This method called after all other service providers have been registered.
Let's look at a simple example.

<?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
class ComposerServiceProvider extends ServiceProvider
{
public function boot()
{
view()->composer('view', function () {
//
});
}
}

108 | P a g e
Service containers

The Service Container in Laravel is a Dependency Injection Container and a Registry for the
application. The advantages of using a Service Container over creating manually your objects are:
Capacity to manage class dependencies on object creation: You define how an object should be
created in one point of the application (the binding) and every time you need to create a new
instance, you just ask it to the service container, and it will create it for you, along with the required
dependencies For example, instead of creating objects manually with the new keyword:

//everytime we need YourClass we should pass the dependency manually

$instance = new YourClass($dependency);

Copy Instead, you can register a binding on the Service Container:


//add a binding for the class YourClass App::bind( YourClass::class, function()
{
//do some preliminary work: create the needed dependencies
$dependency = new DepClass( config('some.value') );
//create and return the object with his dependencies
return new YourClass( $dependency );
});
Copy and create an instance through the service container with:

//no need to create YourClass dependencies, the SC will do that for us! $instance = App::make(
YourClass::class );

Copy

With Laravel automatic dependency injection, when an interface is required in some part of the
app (i.e. in a controller's constructor), a concrete class is instantiated automatically by the Service
Container. Changing the concrete class on the binding, will change the concrete objects
instantiated through all your app:

//every time a UserRepositoryInterface is requested, create an EloquentUserRepository App::bind(


UserRepositoryInterface::class, EloquentUserRepository::class );

Copy

//from now on, create a TestUserRepository App::bind( UserRepositoryInterface::class,


TestUserRepository::class );

109 | P a g e
Copy

Using the Service Container as a Registry

You can create and store unique object instances on the container and get them back later: using
the App::instance method to make the binding, and thus using the container as a Registry.

// Create an instance.
$kevin = new User('Kevin');

// Bind it to the service container.


App::instance('the-user', $kevin);

// ...somewhere and/or in another class... //


Get back the instance
$kevin = App::make('the-user');

Copy

As a final note, essentially the Service Container -is- the Application object: it extends the
Container class, getting all the container's functionalities.

110 | P a g e

You might also like