A - Better Way To Learn PHP
A - Better Way To Learn PHP
Preface
Overview of PHP
Chapter 1: PHP Installation
1.1 Introduction
3.1 Variables
6.1.1 Example 1
6.1.2 Example 2
6.2 Inbuild functions in PHP
1.1 Introduction
All our PHP files will be stored in htdocs. So get in to the htdocs and
make a new folder to store your PHP code. You can give your name to
folder so that you can easily identify if required. Here we have created
a folder by name - ravi. Open the folder and right click on mouse then
click on open with code option. A screen shown below will appear.
A beginner can type the code shown below to display the given string
on browser. Follow the syntax.
<?php
echo “Welcome to PHP”;
?>
save it and go to the browser reload or refresh, you can see the output
of given code appearing in browse.
Welcome to PHP
Note: Keyword in PHP is not case sensitive. So here we can write echo,
ECHO or Echo
CHAPTER 2
PHP with HTML, CSS and JavaScript
In this section, we are going to discuss about how HTML, CSS, JavaScript,
and PHP work together to develop a webpage.
Whenever you want to build a website, you need HTML, CSS, and
JavaScript. Now you will say that, Do not you need PHP? So, answer to this
question is that you don’t need PHP but when your website will be
complex, you want to process on some server side, you want to pull data
from some other website on server side, then you people obviously want to
execute something on server, to execute that you will need PHP. That’s why
PHP is in back end to solve these problems.
Suppose you have a blog, in that you have 1000 blog posts, you have stored
those 1000 blog posts in the database. If you want to access the blog post
you got to write the script in PHP to pull the data from database than you
will send as a response HTML, CSS, and JavaScript combination and that
will be wrapped in html.
But finally the final output which will be sent as a response is a
combination of HTML, CSS and JavaScript.
HTML, CSS, and JavaScript, let us understand this with a friendly example
– Car. Now we are going to compare car with the website, A car contains
three things.
1. Body - HTML
2. Color, designs, decorations - CSS
3. Engine – JavaScript logic
We use the different language in the same way to develop a website.
HTML – It is responsible for what should be written on website such as text
display.
CSS – It is responsible for text color, background color, background image
etc.
JavaScript – It is responsible for logic such as buttons, alert box, events etc.
2. Role of CSS
CSS (Cascading Style Sheets) use to handle the presentation of the web
page containing HTML. We can make our websites beautiful and modern
looking using CSS. We can add different colors and animation to the web
page.
3. Role of JavaScript
JS is client-side scripting language to create completely dynamic web
applications and websites. It handles the logic of the websites. JS is
responsible for event creation and event handling such as Button, textbox,
checkbox, scrollbar and many more.
4. Role of PHP
PHP is a general-purpose scripting language. It is especially suited to web
development. You can also do other types of scripting with PHP. PHP
executes the task of pulling data from database at back-end. Hence it is
known as back-end programming language.
CHAPTER 3
Variables and Data types in PHP
3.1 Variables
Note: We can assign any value integer or float but when we are storing
words or string use double quotes or single quote.
While writing the code in PHP, you do not need to declare the variable
whether it is integer, real, Boolean or other data types. As in other
language JavaScript, Python, Java you must declare the variable.
3.2 Data types
In this section, I will tell you how to deal with different data variable
and what you will have to do.
Following are the primary data type in PHP:-
1. String
2. Integer
3. Float
4. Boolean
5. Object
6. Array
7. Null
7. NULL- If a variable does not have any value than we can use NULL.
Example
$name = NULL;
Echo var_dump($name); // to display instead of variable NULL
3.3 String manipulation in PHP
In this section, we are going to discuss about how to manipulate string
on web page using PHP string functions.
1. strlen() – To display the length of string.
Example
<?php
$name = “John”;
echo strlen($name);
?>
Output - 5
2 dot operator (.) – We can use dot operator to concatenate the string.
Example
echo “My name” . “is John”;
Output – My name is John.
Example
<?php
$a = 5;
$b = 2;
echo “For a + b, the result is “ . ($a + $b) . “<br>”;
echo “For a - b, the result is “ . ($a - $b) . “<br>”;
echo “For a * b, the result is “ . ($a * $b) . “<br>”;
echo “For a / b, the result is “ . ($a / $b) . “<br>”;
echo “For a % b, the result is “ . ($a % $b) . “<br>”;
echo “For a ** b, the result is “ . ($a ** $b) . “<br>”;
?>
Output on webpage
7
3
10
2.5
1
25
Note: We are using <br> for shifting the next data to new line on web
page.
Output on webpage
b is largest
4.3 Switch case statement
Switch case is like if else but syntax is different. Let us write a program
using switch case statement. User must follow the syntax.
We are writing a program in PHP to verify the given age.
<?php
$age = 62;
Switch($age)
{
case 12:
echo “you are 12 years old”;
break;
case 45:
echo “you are 45 years old”;
break;
case 50:
echo “you are 50 years old”;
break;
default:
echo “Your age is not valid”
}
?>
Output
Your age is not valid
<?php
for ($index=1; $index < 11; $index++) //using syntax - for(initialization;
condition; updation)
{
echo $index;
echo “<br>”;
}
?>
Output
1
2
3
4
5
6
7
8
9
10
<?php
$i=0;
do
{
echo $i+1;
echo “<br>”;
$i++;
}while(i<6);
?>
Output
1
2
3
4
5
5.4 Foreach loop
We have seen how for loop works, to minimize the coding in writing
segment of for loop we use foreach loop. We are going to compare the
for loop with foreach loop. Let us take an example of displaying the
elements of an array.
This program displays the elements of given array (fruits)
<?php
$arr = {“apple”, “banana”, “Orange”, “Mango”};
for ($i=1; count($arr); $i++) //count function counts the number of
element in array
{
echo $arr[i];
echo “<br>”;
}
?>
Output
apple
banana
Orange
Mango
Now we are going to do the same task in better way using foreach loop.
Here the variable value will store the element of array. Let us write the
code using foreach, follow the syntax
<?php
$arr = {“apple”, “banana”, “Orange”, “Mango”};
foreach ($arr as $value)
{
echo $value;
echo “<br>”;
}
?>
Output
apple
banana
Orange
Mango
CHAPTER 6
Function in PHP
In this section we are going to discuss about functions in PHP. Suppose
we are developing a big application on ecommerce, in which we got
place the order of item. We will have huge number of items so obviously
we got to repeat the same task for different items. Function is best
suitable for like this situation.
6.1 Call by value function
6.1.1 Example 1
<?PHP
function processMarks($marksArr)
{
foreach ($marksArr as $value)
{
$sum += $value;
}
return $sum;
}
$ravi = [30, 80, 60, 75, 90];
$sumMarks = processMarks($ravi);
<?PHP
function avgMarks($marksArr)
{
$sum = 0;
$i = 1;
foreach ($marksArr as $value)
{
$sum += $value;
$i++;
}
return $sum/$i;
}
$ravi = [30, 80, 60, 75, 90];
$sumMarks = avgMarks($ravi);
?>
Output
Average marks scored by Ravi out of 600 is 67
Average marks scored by John out of 600 is 88
6.2 Inbuild functions in PHP
The table shown below illustrates the inbuild functions used in PHP
with corresponding description.
Buit-in functions Description
count() Counts the number of elements in an array
strlen() Counts the length of a string.
explode() String will split into an array by a specified delimiter.
implode() It joins the array elements into a string with a specified
delimiter.
file_get_contents() It reads the contents of a file into a string.
substr() It returns a part of a string based on a start position and
length.
strtoupper() It converts a string to uppercase.
strtolower() It converts a string to lowercase.
If we want the current date than we can use date function of PHP. We
can also refer the website of PHP that is PHP.net for Date and other
functions. Let us display the current date on webpage using date
function. User must follow the syntax
<?PHP
$d = date(“dS F Y”); // User can refer the manual of php.net website for
more date format
echo “Today date is $d <br>”
?>
Output
Today date is 10th Sep 2024
We must go to the Php.net website, then see the manual for different
alphabetic representation of date function. A user can make the format
according to his requirement. You must practice using manual for
different types of dates as well as time format.
For example
date(“dS F Y, g:i A”) gives the output – 10th September 2024, 10:31AM
6.4 Scope, Local and global variables in PHP
Scope - It indicates from where you can access the variables in
program.
Local – A variable used within the function known as local variable. We
can access the variable within the function.
Global – We can access from outside of the function.
PHP gives us the facility to access the global variable within function.
All global variables can be declared within function using global
keyword.
For e.g.
global $a, $b;
Let us write some code using Local and global variable. This program
displays the values of local and global variable within the function
<?php
$b = 6; // global variable
$c = 5; // global variable
function displayValue()
{
$a =4; // local variable
global $b, $c;
echo $a;
echo $b;
echo $c;
}
?>
Output
4
5
6
CHAPTER 7
Arrays in PHP
echo $favCol[‘john’];
echo “<br>”;
echo $favCol[‘albert’];
?>
Output
red
yellow
?>
Output
Favourite color of john is red
Favourite color of jackson is green
Favourite color of albert is yellow
Favourite color of phillips is black
7.2 Multi-Dimensional array
As we have seen previously, we had to give only one key to access the
element such as 0,1,2 etc. If we insert an array within array known as
multidimensional array. Let us consider the matrices shown below and
write code to display the given matrices.
We are going to use nested for loop. Here when first for loop executed
once at the same time second one will execute all iteration and display
the given data.
<?PHP
$multiDim = array(array(2,5,7),
array(1,2,3),
array(4,5,6));
?>
Output
CHAPTER 8
MySQL with PHP
A database is a collection of information that is organised so that it can
be easily accessed, managed, and updated. The database management
system (DBMS) is the software that interacts with end users,
applications, and the database itself to capture and analyse the data. In
this section we will use MySQL with PHP to get this done. MySQL is an
open-source relational database management (RDBMS).
Fig shows the interaction between client, Server and database admin.
User or Client will request the server to access the database, the
database may be stored within server or if it belongs to big organisation
than it may stored outside and connected to the server. Suppose client is
requesting for google.com. Now server will access the database using
PHP script as well as MySQL commands and responds to client. Here
client is not aware of database admin, he just places the request
through URL or others. I hope this is helpful to learn upcoming coding.
Now we are going to use MySQL APIs to pull, push and update existing
data.
8.1 Database creation in phpMyadmin
To create a table, click on file, right hand side of screen enter table
name, click on go and type name of column, data type as well as
primary key. Here user must be aware of MySQL. Once a table is
successfully created, we can insert data one by one, click on insert and
store data. You can also delete the record as well as export the record.
phpMyadmin provides facility to run MySQL query, if you are aware
of MySQL than you can use it.
8.2 Database connectivity
Once the database is successfully created in phpMyadmin, next we got
to write a code segment to connect to the database. There are two ways
to connect to database
1. MySQLi extension- Using function
2. PDO (PHP data object)- Using object-oriented code
Let us write the code to connect to the database using MySQL
extension.
<?php
Echo “Welcome to the stage where we are ready to get connected to a
database”;
//Connecting to the database
$servername = “localhost”;
$username = “root”;
$password = “”; // don’t give any password
// Create a connection
$conn =mysqli_connect($servername, $username, $password);
Echo “Connection was successful”;
?>
Output
Connection was successful
8.3 Create database using PHP script
// Create a connection
$conn =mysqli_connect($servername, $username, $password);
//Create database
$sql = “CREATE DATABASE dbRavi”;
mysqli_query($conn, $sql);
if (!$conn)
{
die(“Sorry we failed to connect: “,mysqli_connect_error())
}
else
{
echo “Connection was successful”;
}
?>
Output
Connection was successful
Note: User must go to phpMyadmin and make sure dbRavi database
created.
CHAPTER 9
File handling in PHP
In this section, we are going to discuss about the file handling. What
does files mean? You must have heard about text files, you must have
heard about image files, and the code we are writing also stored in a
file. So, our source code is a text file, which has characters in it, PHP
gives us facility to display the content of the file on web page.
Let us create a file (myfile.txt) and store some text in that “Welcome to
world of PHP script”. Now, start the XAMPP Apache server and write
the code shown below.
<?PHP
$a = readfile(“myfile.txt”);
echo $a
?>
Output
Welcome to world of PHP script 30
Note: In output 30 is the total number of characters.
To avoid the total number of characters, we must write the code shown
below.
<?PHP
readfile(“myfile.txt”);
?>
Output
Welcome to world of PHP script
Now, let us try to display the html file on webpage, Create a html
file(file.html), write some html tag in that (<HTML> </HTML). Write
the code shown below
<?PHP
$a = readfile(“myfile.txt”)
readfile(“file.html”)
?>
Output
<HTML> </HTML>
Above shown examples indicate that we can only display text files,
source code file or html file as well as any text file using readfile()
method. These are the simplest way to display the file content to read
on webpage.
9.2 fopen(), fread() & fclose() in PHP
In this section, we are going to discuss about how can we use the
content of the file. Sometimes we want to write something in the file, if
I want to add something in the end or the middle of the file than we will
have to read the file and after reading we will add what we want to add
and write it. Let us see how do we do all these things. I am going to
explain it through coding in PHP.
Note: We are using the same text file (myfile.txt)
<?php
//To read the file we are using file pointer and fopen() function to read
the file
$fptr = fopen(“myfile.txt”, “r”); //here “r” is for read mode, “w’ is for
write mode
If (!fptr)
{
die(“Unable to enter the file please enter valid filename”); //warning
message
}
//now we are going to read the file
$content = fread($fptr, filesize(“myfile.txt”));
echo $content;
fclose($fptr)
?>
Output
Welcome to world of PHP script.
In above example fopen() will open the resource, fread() will read the
file and filesize() gives the no. of characters in a file to read. fclose() is
used to close the file.
There are three types of mode commonly used
1. r – read mode
2. w- write mode
3. r+- read and write mode.
Note: We can refer PHP.net site for different modes and many more
functions.
9.3 fgetc() & fgets() in PHP
In this section we are going to discuss about fgetc() and fgets() function.
Let us open the same file (myfile.txt) and include one sentence “Hi!
User,” above “Welcome to world of PHP script.”. Here fgets() will read
one sentence at a time. So to read both sentence we need two fgets().
Code to read both sentences of myfile.txt
<?php
$fptr = fopen(“myfile.txt”, “r”);
echo fgets($fptr);
echo fgets($ptr);
?>
Output
Hi! User,
Welcome to world of PHP script.
fgetc() function will read the file character by character. We can use
while loop in above code to read the specific number of sentence. Let
us write a program using while loop and fgetc() to read the content of a
file until (.) has been encountered.
<?php
$fptr = fopen(“myfile.txt”, “r”);
While($a = fgetc($fptr))
{
echo $a;
if($a == “.”) // Here we can also use any other character according to
requirement
{
break;
}
}
?>
Output
Hi! User,
Welcome to world of PHP script.
CHAPTER 10
Bootstrap in PHP
Output
Welcome to PHP
Welcome to PHP
Welcome to PHP
We can also insert the PHP block in HTML code. Let us insert the PHP
block which is displaying “Welcome to PHP” in HTML code.
<HTML>
<BODY>
<?PHP
Echo “Welcome to PHP”;
?>
</Body>
</HTML>
Output
Welcome to PHP
Get the corresponding code of form from starter template copy and
paste in PHP as shown below. If we want to change the name of column
or title, we can change according to our requirement. A user must
manipulate the code change the name of column, heading etc.
Execute the code, on webpage fill the form and click on submit button.
Data will automatically stored in a table created by us.
The end