0% found this document useful (0 votes)
6 views86 pages

A - Better Way To Learn PHP

This document is a comprehensive guide on PHP, covering installation, integration with HTML, CSS, and JavaScript, and various programming concepts such as variables, data types, decision making, and looping. It also includes sections on functions, arrays, MySQL integration, file handling, and Bootstrap. The eBook is designed for beginners and provides detailed explanations and examples to facilitate learning PHP for web development.

Uploaded by

haji5
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views86 pages

A - Better Way To Learn PHP

This document is a comprehensive guide on PHP, covering installation, integration with HTML, CSS, and JavaScript, and various programming concepts such as variables, data types, decision making, and looping. It also includes sections on functions, arrays, MySQL integration, file handling, and Bootstrap. The eBook is designed for beginners and provides detailed explanations and examples to facilitate learning PHP for web development.

Uploaded by

haji5
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 86

CONTENT

Preface

Overview of PHP
Chapter 1: PHP Installation

1.1 Introduction

1.2 Installation of PHP

1.3 PHP code execution


Chapter 2: PHP with HTML, CSS and JavaScript
Chapter 3: Variables and Data types in PHP

3.1 Variables

3.2 Data Types

3.3 String manipulation in PHP

3.4 Operators in PHP


Chapter 4: Decision Making in PHP

4.1 If else condition

4.2 Nested if condition

4.3 Switch case statements


Chapter 5: Looping in PHP

5.1 While loop

5.2 For loop

5.3 do while loop

5.4 Foreach loop


Chapter 6: Function in PHP

6.1 Call by value function

​6.1.1 Example 1
​6.1.2 Example 2
6.2 Inbuild functions in PHP

6.3 Date function in PHP

6.4 Scope, local and global variables in PHP


Chapter 7: Arrays in PHP

7.1 Associative Array

7.2 Multi-Dimensional Array


Chapter 8: MySQL with PHP

8.1 Database creation in phpMyadmin

8.2 Database connectivity

8.3 Create database using PHP script


Chapter 9: File handling in PHP

9.1 Text and HTML file handling

9.2 fopen(), fread() & fclose() in PHP

9.3 fgetc() and fgets() in PHP


Chapter 10: Bootstrap in PHP

10.1 Power of Bootstrap

10.2 Form using Bootstrap


PREFACE
PHP is a worldwide famous script language used to develop web pages.
It is an object-oriented language. Hence it uses interpreter to execute
the instructions.
The main applications of PHP are - web page development, client GUI
application, server - side scripting etc. It is also embedded with HTML,
CSS.
Almost 75% of websites are developed by using the instructions in PHP
language.
This eBook teaches you how to write PHP code, while going into several
topics of the language. If a learner is not aware of any other
programming language like Java, C, C++, then also he can easily learn
PHP.
This eBook gives you complete idea about web development and
writing PHP code. You will not be bored. I have explained PHP from
Basic level to the developer level with lots of examples. if you are not
familiar with any other computer language, this could be an excellent
book for you to get started in PHP.
OVERVIEW OF PHP
PHP is a most prominent language powering the web. It was created in
beginning of 1994 by Rasmus Lerdorf. At very first it was a simple set
of CGI (Common Gateway Interface) binaries written in the C
language. PHP stands for “Personal Home Page”. At initial stage PHP
was only used for tracking online resume. Later PHP tools was
rewritten by Rasmus for much larger and richer implementation. In
the month of June 1995, Rasmus released the source code for PHP
Tools to the public. In 1996, PHP/FI was introduced by Rasmus where
FI stands for “Forms interpreter”. It includes built in support for DBM
(Data base Management), MySQL, cookies, user defined function
support, and much more.
The new model of PHP is capable of database interaction and many
more. It provides a framework upon which user could develop simple
dynamic web applications. This also allows the user to fix bugs in code
and improve upon it.
Nowadays, PHP is growing popularity in still young world of web
development. The maturation of PHP/FI was doomed to limitation
while there were several minor contributors, it was still primarily
developed by an individual.
Following are the application of PHP:-
• E-Commerce Applications
• Web page Development
• Content Management Systems (CMS)
• Server -Side Scripting
• Social Media Websites
• Chatbots
• Data Collection and Processing
• Web Scraping
CHAPTER 1
PHP Installation

1.1 Introduction

PHP was basically designed to resemble C in structure, makes it easy


for developers familiar with C, Perl, and similar languages. It was
limited to UNIX and POSIX-compliant systems, the potential for a
Windows NT implementation was being explored. Nowadays we can
install PHP for windows but we need Visual Studio environment.
PHP is a very beautiful programming language. The latest version of
PHP is PHP 7. Now we are going to discuss about how to create an
environment to run the PHP coding.
1.2 Installation of PHP
First of all we got to install Visual Studio. Visual studio supports a
programmer in syntax highlighting and many more. So let us install
Visual studio.
Type Visual studio in Google, click on “code.visualstudio.com”,
download Visual studio as shown below

Once it is downloaded, click, and Run


Accept the agreement and select all task, click next, click install. The
Visual studio is successfully installed in your system.

Now we are going to install PHP.


To create a run time environment, a user must be aware that you have
to install PHP, Apache web server, MySQL for using database etc. We
can do all in one, download XAMPP software as shown below.
Go to Google, type XAMPP software, download it

Once it is downloaded, click, and Run, select all components, click on


next, give location and click on install. XAMPP software successfully
installed in your system.
During installation of XAMPP will prompt for Run, a user must make
sure that Apache and MySQL are installed successfully and running to
support. In MySQL if you click on admin then phpMyAdmin opens.
PHP Admin will help you to look at your database, which database you
have created. We can also convert excel file in to our database here.
1.3 PHP code execution

XAMPP is one of the easiest way to execute PHP code. As we have


installed XAMPP, now you can start Apache and MySQL, click on
admin to open phpMyAdmin. Let us see where is XAMPP in our
system, we find XAMPP in C drive. Now among all available folders we
got to search htdocs folder. Once we found double click to open. Figure
shows the htdocs folder.

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.

Now we are ready to do the coding, go to browser type localhost/ravi,


we can easily check here that index of /ravi is empty because we have
not yet given any code. So go to the previous screen, now we have to
make a PHP file, so go to new file and create filename.php (user can
give any filename) and start writing the code. Let us write some code.

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.

Now we will discuss how websites work? A user(client) sends URL


(www.google.com) from browser as request to server. On behalf of web
server PHP will execute the user request and responds by website of
HTML, CSS and JavaScript.

Let us discuss about role of all four languages in Web development.


1. Role of HTML
HTML is a standard markup language. It is basically a language for giving a
static skeleton to web application and websites. It has tags for making bold
text, where to start paragraph, where to put a division. In HTML tag you
have to wrap your content. There are basic syntax such as head, body, title.
In this HTML file CSS, JavaScript everything is sent as an embedded.

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

Variable is an entity to store data. In other words, we can say variables


are containers for storing information. Every variable in PHP is a case
sensitive. We use $(Doller) before variable in coding.
Let us write some code to display the given string using variable on web
page. Make a file and write the code shown below, type
<?php
$name = “John”;
$income = 2000000.00;
Echo “This guy is $name and his income is Rs. $income”;
Save the code and start Apache server than see the output on web page
Output
This guy is John and his income is Rs. 200000.00

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

1. String – Any word or sentence is called string. We can use single or


double quotes to write a string.
Example
$name = “John”
$friend = ‘Merry’
echo $name; // to display name
echo $friend; //to display friend

2. Integer – A non-decimal number is known as Integer. It can be both


negative or positive.
Example
$income = 4000;
$debts = -5000;
echo $income; // to display income
echo $debts; //to display debts

3. Float – A decimal point number is known as Float. It can be negative


or positive.
Example
$income = 465.5;
$debts = -45.5;

4. Boolean – It gives the output either true or false.


Example
$x = true;
$is_friend = false;
Echo var_dump($x); // to display true
Echo var_dump($is_friend); // to display false
Note: Here we have var_dump() function to display the Boolean
variable in proper format on web.

5. Object – It is an instance of classes. This data type is used in Object-


Oriented programming so it will be discussed later during OOPs
programming in PHP.

6. Array – We can store the multiple values in a single variable.


Example
$friends = array(“John”, “Merry”, “Ord”, “Larry”)
Echo var_dump($friends); // to display all friends
Echo $friends[0]; // to display John
Echo $friends[1]; // to display Merry

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.

3. str_word_count() – To count the number of words in given string.


Example
<?php
$sentence = “My name is John”;
echo str_word_count($sentence);
?>
Output - 4

4. strrev() – To reverse the given string.


Example
<?php
$name = “John”;
echo strrev($name);
?>
Output - nhoJ

5. strpos() – To get the position of given string.


Example
<?php
$sentence = “My name is John”;
echo strpos($sentence, “is”);
?>
Output - 8

6. str_replace() – To replace the given string.


Example
<?php
$name = “John”;
echo str_replace(“John”, “Merry”, $name);
?>
Output - Merry

7. str_repeat() – To repeat the given string.


Example
<?php
$name = “John”;
echo str_repeat($name, 5);
?>
Output
John John John John John
3.4 Operators in PHP
Following are operators used in PHP
1. Arithmetic Operators
2. Assignment Operators
3. Comparison Operators
4. Logical Operator
1. Arithmetic Operators – Addition(+), Subtraction(-),
Multiplication(*), Division(/), Modulus (%), Power (**).
Let us write a code in PHP to perform all arithmetic operation on Web
page, Start the Apache server and start writing the code shown below.
Save and get the result on web page.

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.

2. Assignment operators – It helps us to assign a value to another value


as shown below.
Example
Let $a =5
$x = $a; // assigns the value of a to x
$a += 6; // value of a incremented by 6 so the result is 11
$a -= 4; // value of a decremented by 4 so the result is 1
Similarly we can assign /= , *=, %= etc.

3. Comparison operators – It compares two values.


Comparison operators are - equal to(==), not equals to(<>), greater
than(>), less than(<), greater than equal to (>=), less than equal to(<=)
etc.
We will see in upcoming chapter how to use comparison operators in
coding.

4. Logical operators – These operators are used along with if else


statements in coding. We are going to discuss about if else construct in
upcoming chapter. Logical operators are –
and – &&
or - ||
not - !

Note: Logical operators and comparison operators are used to make


the decision.
CHAPTER 4
Decision making in PHP

In this section, we are going to discuss about how to make decisions


using the comparison operators and Logical operators.
4.1 If else condition
The “if else” statement helps us to write the logics. If the condition is
true than true action will be taken and if false than else action will be
taken. Let us make the decision using “if else” construct.
Start the Apache server and create a file, save the given code and get
the result on webpage.
We are going to write code for given number is greater than 70 or not
using “if else” construct. You must follow the syntax.
<?php
$a =55;
$b = 20;
If ($a > 70)
{
echo “a is greater than 70”;
}
else
{
echo “a is not greater than 70”;
}
?>
Output
a is not greater than 70
4.2 Nested if condition

Inside the if clause if we use another if statement known as Nested if


clause. In nested if clause both the if clause will be executed depends on
condition we give. Let us make the decision using elseif ladder. User
must follow the syntax of elseif ladder.
We are going to write a program in PHP to find the largest among three
given numbers.
<?php
$a = 3;
$b = 5;
$c = 2;
if ($a > $b && $a > $c)
{
echo “a is largest”;
}
elseif($b > $a && $b > $c)
{
echo “b is largest “;
}
else
{
echo “c is largest”
}
?>

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

Note: We are using break statement because as soon as the match


found, program will be terminated.
CHAPTER 5
Looping in PHP

In this section, we are going to discuss about different type of looping


used in PHP. Looping is always used with sequential numbers. It can be
defined as a segment of code executed again and again until the given
condition is true.
5.1 While loop
While the condition is true a segment of code will be executed known as
While loop. Let us write a program in PHP using while loop. User must
follow the syntax.
We are going to write a program in PHP to display 1 to 5 on web page
using while loop. Start the Apache server, create a file to write
program, type the code shown below.
<?php
$i = 0;
While($i < 5) //if we write 10 instead of 5 then loop will run up to 10
{
echo $i + 1;
echo “<br>”;
$i++; // here, i incremented by 1, we can also write i+=2 to increment by
2 if required
}
?>
Output
1
2
3
4
5
5.2 For loop
For loops is basically another way of writing loops. They are just
different in syntax and execution time is almost the same. Let us write
the program using for loop. User must follow the syntax.
We are going write a program in PHP to display number 1 to 10 using
for loop.

<?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

Note: We have used // for writing comment within code, if we want to


write multiline comment than use /*sentences*/.
5.3 do while loop
The loop says, do the segment of code while the given condition is true.
In do while loop segment of code will be executed at least once if
condition is false. Let us write a PHP program using do while loop.
We are going to write a program in PHP to display 1 to 5 on web page
using do while loop.

<?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

For example, there is a class in which individual student’s marks must


be calculated here also same task is repeated for every student, so let us
apply function, it is also known as call by value function. In this
function gets the value and passes parameter as result.

<?PHP
function processMarks($marksArr)
{
foreach ($marksArr as $value)
{
$sum += $value;
}
return $sum;
}
$ravi = [30, 80, 60, 75, 90];
$sumMarks = processMarks($ravi);

$john = [90, 95, 98, 86, 72]


$sumMarksJohn = processMarks($John);
echo “Total marks scored by Ravi out of 600 is $sumMarks <br>”;
echo “Total marks scored by John out of 600 is $sumMarksJohn”;
?>
Output
Total marks scored by Ravi out of 600 is 335
Total marks scored by John out of 600 is 441
6.1.2 Example 2
Now I am going to write the code using function to calculate the
average marks obtained by each student.

<?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);

$john = [90, 95, 98, 86, 71]


$sumMarksJohn = avgMarks($John);

echo “Average marks scored by Ravi out of 600 is $sumMarks <br>”;


echo “Average marks scored by John out of 600 is $sumMarksJohn”;

?>

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.

6.3 Date function in PHP

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

7.1 Associative Array


In this section we will discuss about Associative array. If the elements of
array is associated with the values known as associative array. Let
there are four persons John, Jackson, Albert, Phillips, each of them
having some favourite color. So, if we display the elements of array
(colors) then how people will recognise which color belongs to whom?
Let us write the code using associative array. User must follow the
syntax
<?php
$favCol = array(
​‘john’ => ‘red’,
​‘jackson’ => ‘green’,
​‘albert’ => ‘yellow’.
​‘phillips’ => ‘black’
)​ ; // we can also use integer instead of string, For
e.g. 8=> ‘blue’;

echo $favCol[‘john’];
echo “<br>”;
echo $favCol[‘albert’];

?>

Output
red
yellow

Let us use foreach loop to display the favourite color of person in


proper format using loop iteration.
<?php
$favCol = array(
​‘john’ => ‘red’,
​‘jackson’ => ‘green’,
​‘albert’ => ‘yellow’.
​‘phillips’ => ‘black’
​);

foreach ($favCol as $key => $value)


{
echo “<br> Favourite color of $key is $value”;
}

?>

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));

for ($i=0; $i < count($multiDim); i++)


{
for ($j=0; $i < count($multiDim[$i]); j++)
{
echo $multiDim[$i][$j];
echo “ “;
}
echo “<br>”;
}

?>
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

We are going to discuss about phpMyadmin. User must start the


Apache Server and MySQL and click on admin to open phpMyadmin.
A screen will appear as shown below. To create a database, go to the left
top click on new. Type the filename and click on create. A database is
successfully created. You can see the filename just below the new.

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

We have already created a database using phpMyadmin. We can also


create the database in phpMyadmin using PHP script. Database
connectivity will be same as we discussed previously, we got to insert
the code in middle to create database. Let us write the code
<?php
$servername = “localhost”;
$username = “root”;
$password = “”; // don’t give any password

// 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

9.1 Text and HTML file handling

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

Note: Instead of myfile.txt, if we write any image file(1.png) than image


will not be displayed on web. The text version of image will be
displayed.

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

10.1 Power of Bootstrap

In this section, we are going to discuss about power of Bootstrap and


how can we manipulate the coding. So far as we wrote our code in
single block in a file i.e. <?PHP …. ?>. We can use several numbers of
blocks in a file. Let us write the code using several blocks in a file and
execute.
<?PHP
echo “Welcome to PHP”;
?>
<?PHP
echo “Welcome to PHP”;
?>
<?PHP
echo “Welcome to PHP”;
?>

Output
Welcome to PHP
Welcome to PHP
Welcome to PHP

Note: A programmer can use several blocks according to requirement.

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

Bootstrap is one of the powerful tool which allows us to avoid HTML,


CSS, JavaScript to do many tasks on web page. It gives us ready to use
code which we can be simply copied and pasted in PHP file and
manipulate according to requirement and get the output on web. We
can also insert our code in PHP block. We are not saying to completely
avoid HTML, CSS or JavaScript but for some tasks which is available
in Bootstrap you can use it for your purpose and manipulate it
according to your requirement. I am going to explain everything using
images. A programmer or learner must practice it.
10.2 Form using Bootstrap
In, this section we are going to discuss about how to take support of
Bootsrap. A user can manipulate a form according to his requirement.
Let us retrieve the code of a form from bootstrap and paste it in PHP
programming gallery. If any user fills the form, corresponding data will
be directly stored in a table created by us. First of all download and
open Bootstrap, go to form as shown below.

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.

Let us do some manipulation in coding. Suppose we are going to change


the heading “Contact us for your concerns” and name of columns such
as name, email, description.
First, open database gallery phpMyAdmin as discussed in Chapter 8,
create a table so that when user enters data that will be stored in this
database table. We must write the name of column according to form.
Once we created the database according to form, go to the coding
section and include code for database connectivity to server as
discussed in chapter 8. We must manipulate the code, replace heading,
column name according to our requirement.

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

You might also like