PHP Concept
PHP Concept
15 PHP(server-side scripting)
Introduction:-
PHP is the most popular server-side scripting language for creating dynamic web pages.
[Note:Here ‘Dynamic page’ means different content with different users' accounts and time.
1
PHP
Terms:-
Compiled program:-
A compiled program is not human readable, but instead is in an architecture-specific machine language. Creating a
compiled program requires several steps.
Interpreted language:-
An interpreted language is a programming language whose implementations execute instructions directly and
freely, without previously compiling a program into machine-language instructions. For example, php,python js etc
In an interpreted language, the code is not compiled at first hand. Instead, a copy is transferred to another
engine which then converts (into machine) and processes the code.
Different browser uses different engines.
Like v8 engine by chrome, spidermonkey by firefox, webkit by safari etc.
2
PHP
PHP was originally created by Rasmus Lerdorf in 1994. It was initially known as’ Personal Home Page’.
PHP scripts are executed on the server and the result is sent to the web browser as plain HTML.
PHP can be integrated with the number of popular databases, including MySQL, PostgreSQL, Oracle, Microsoft SQL
Server, Sybase, and so on.
3
PHP(server-side scripting)
Working mechanism
4
PHP
Advantages of PHP over Other Languages
Following are some major advantages of PHP.
• Easy to learn: PHP is easy to learn and use. For beginner programmers who just started out in web
development, PHP is often considered as the preferable choice of language to learn.
• Open source: PHP is an open-source project. It is developed and maintained by a worldwide community of
developers who make its source code freely available to download and use.
• Portability: PHP runs on various platforms such as Microsoft Windows, Linux, Mac OS, etc. and it is compatible
with almost all servers used today such Apache, IIS, etc.
• Fast Performance: Scripts written in PHP usually execute or runs faster than those written in other scripting
languages like ASP, Ruby, Python, Java, etc.
• Vast Community: Since PHP is supported by the worldwide community, finding help or documentation related
to PHP online is extremely easy.
5
PHP
Disadvantages :-
1.It is not that secure due to its open-source, because the ASCII text file are often easily available.
2.It is not suitable for giant content-based web applications.
3.It has a weak type, which can cause incorrect data and knowledge to the user.
4.PHP frameworks have to use PHP built-in functionalities to avoid writing additional code.
5.Using more features of PHP framework and tools cause poor performance of online applications.
6.PHP doesn't allow change or modification in core behavior of online applications.
7.The PHP frameworks aren’t equivalent in behavior so does their performance and features.
6
3.13 Hardware and software requirements
3.13 Hardware and Software requirements:-
Hardware requirements:-
7
3.13 Hardware and software requirements
Software requirements:-
The system requirements for using our PHP platform are as follows.
Operating Systems
• Windows XP SP3
• Windows Server 2003
• Windows Vista SP1
• Windows Server 2008
• Windows 7
• Windows Server 2008 R2
• Windows 8, 8.1 etc
8
3.13 Hardware and software requirements
For development environment:-
• PHP 5.3.3+ version. Unzip the downloaded file and move the unzipped folder to the desired drive.
• Apache
• MySQL (optional. Necessary for DataBase related functionalities)
For these all, we have to install one WEB server.
Some popular web servers are:
9
3.13 Hardware and software requirements
XAMPP:-
XAMPP is a free and open-source cross-platform web server solution stack package developed by Apache Friends,
consisting mainly of the Apache HTTP Server, MariaDB database, and interpreters for scripts written in the PHP
and Perl programming languages.
“XAMPP provides an ideal local development environment”
Installation and starting of APACHE:-
Follow the steps to download and install XAMPP
1.open https://www.apachefriends.org/download.html
2. Click the download button for 64 bits.
3.after downloading, install it.
4.Having installed it, open my computer and look for the xampp folder.
10
3.13 Hardware and software requirements
5. Open the xampp folder then get inside the htdocs folder.
[You may delete all the files inside htdocs. We have to save our php pages inside this folder.]
6. We have to store all php files over there to run all php pages in the browser.
11
3.13 Hardware and software requirements
How to start apache and mysql:
1.Open xampp folder
2.Open xampp control icon
12
3.14 Object Oriented Programming
Definition:-
Object-Oriented Programming (OOP) is a programming model that is based on the concept of classes and
objects.
As opposed to procedural programming where the focus is on writing procedures or functions that perform
operations on the data, in object-oriented programming the focus is on the creations of objects which
contain both data and functions together.
Object-oriented programming has several advantages over conventional or procedural style of programming.
13
3.14 Object Oriented Programming
OOP is faster and easier to execute.
OOP provides a clear structure for the programs.
OOP helps to keep the PHP code DRY "Don't Repeat Yourself", and makes the code easier to
maintain, modify and debug.
OOP makes it possible to create full reusable applications with less code and shorter development
time.
14
3.14 Object Oriented Programming
Lets understand some features in brief:-
Class:-
Object:-
15
3.14 Object Oriented Programming
Encapsulation:-
Hiding the implementation details and only exposing the methods. The main purpose of
encapsulation is to:
Reduce software development complexity – by hiding the implementation details and only exposing the
operations, using a class becomes easy.
Protect the internal state of an object – access to the class variables is via methods such as get and set,
this makes the class flexible and easy to maintain.
The internal implementation of the class can be changed without worrying about breaking the code that
uses the class.
16
3.14 Object Oriented Programming
Inheritance –
This is concerned with the relationship between classes. The relationship takes the form of a parent
and child. The child uses the methods defined in the parent class. The main purpose of inheritance is;
->Re-usability– a number of children, can inherit from the same parent. This is very useful when we
have to provide common functionality such as adding, updating and deleting data from the
database.
Polymorphism – This is concerned with having a single form but many different implementation ways. The
main purpose of polymorphism is;
•Simplify maintaining applications and making them more extendable.
17
3.14 Object Oriented Programming
How to OOP in PHP:-
PHP is an object oriented scripting language; it supports all of the above principles. The above
principles are achieved via;
18
3.15 Basic syntax of PHP
PHP fundamental concept:- To write PHP program, we have to understand basic concept of major components such as
2. comments
3. Variables
4. Constants
5. operators
6. Data types
19
3.15 Basic syntax of PHP
General format/structure of PHP code:-
<?php
?>
Note:
->The default file extension for PHP files is ".php" i.e save the file with extension .php.
->A PHP file normally contains HTML tags, and some PHP scripting code.
->All scripts/codes must be terminated with a semicolon.
->PHP codes (commands)are not case sensitive. But the variables are case sensitive.
20
3.15 Basic syntax of PHP
Below, we have an example of a simple PHP file, with a PHP script that uses a built-in PHP
function "echo" to output the text "Hello World!" on a web page:
Example 1:-
<?php
echo”hello world”;
?>
Save it with hello.php inside the htdocs folder and view its output from the browser.
To see the output, type path of of php file with localhost.
[Reminder:
we may use only single quotes with echo. It works. We may also use ‘print’/printf instead echo.
All keywords, classes, and functions are NOT case sensitive.
Variables names are case sensitive.
]
21
3.15 Basic syntax of PHP
PHP Variables:-
A name , also called an identifier, is used to hold data in memory. Variables in PHP are represented by a dollar
sign followed by the name of the variable. The variable name is case-sensitive.
•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 ($age and $AGE are two different variables)
22
3.15 Basic syntax of PHP
PHP Variables’ types:- Variables are of following types.
1.Numeric variable:- It stores numbers.
1.1 integer variable
1.2floating variable
$a=45; or $a=45.65;
2. String variable:- It stores string/character. $a=‘Kathmandu’
3.Boolean variable:- It stores true or false value. E.g. $a=true;
4.Array type of variable: It is a collection of data of similar types.
5.Object type of variable:-It contains data with functions.
6.Null type of variable:-It stores null value. E.g. $a=null;
7. Resource type of variable:-It is used for database connection.
Variables scope: It means the visibility of a variable. We can also say, the part or place where a variable can be
used. We can use in three ways.
1.local:- All the variables used inside the function are local variables. They are accessible to that function only.
2.Global: All the variables used outside the function are called global. Variables can be accessed from anywhere.
3. static: To retain the value of a variable after calling a function, we use that variable as ‘static’
23
3.15 Basic syntax of PHP
PHP constant:-
A constant is simply a name that holds a single value. As its name implies, the value of a constant cannot be
changed during the execution of the PHP script.
We can use php constant value in different ways.
1. define() constant:
To define a constant, you use the define() function. The define() function takes the constant’s name as the first
argument and the constant value as the second argument.
Example 1:
<?php
define('name',"College");
echo name;
?>
24
3.15 Basic syntax of PHP
CONST keyword for constant:-
PHP provides you with another way to define a constant via the const keyword. Here’s the syntax:
const name=value;
Example 2:-
<?php
const $name="computer science";
echo $name;
?>
25
3.15 Basic syntax of PHP
PHP comments:-
Comments are important parts of the code. Comments provide useful information that will help you and other developers understand the
meaning of the code more quickly later.
PHP supports two types of comments:
1.One-line comments
The one-line comment is placed at the end of the line or at the current block.
. A one-line comment starts with the pound (#) or double forward-slash (//). The rest of the text after the (//) is ignored by the PHP
interpreter.
2. Multi-line comments:- <?php
const name="computer science";#assigning constant
A Multi-line comment start with /* and end with */.
value
Example :
echo name; /* printing the value */
$myname="Ram Kumar Shrestha";
echo '.<br>'.$myname; //printing the value of
myname variable
?>
26
3.15 Basic syntax of PHP
Input in PHP:- To input data in php, we apply following techniques.
1. using HTML form: It is a very popular technique to input data using HTML form and process them using php code.
Format:-
print_r(variable);
27
3.15 Basic syntax of PHP
Using echo:-
Example1:-
<?php
echo ("Hello, world!!!!"),("welcome");
?>
Example 2:
<?php
$name="learning js";
echo $name;
echo ("string is ".$name);//comma does not work. Use . to concatenate
echo "<br>string is",$name;//it works.
?>
[echo supports all most all expressions.]
Using print:-
Example:-
<?php
$name="learning js";
print $name;
print ("<br>string is ".$name);//comma does not work. Use . to concatenate
print "<br>string is".$name;//comma does not work.
?>
28
3.15 Basic syntax of PHP
Using print_r():-
<?php
$name="learning js";
print_r ($name);//must put bracket. without it ,it does not work.
print_r ("<br>string is ".$name);//comma does not work. Use . to concatenate
?>
[Note:
From hereafter we will be using ‘echo’ construct to display our output.
It is not a function.
]
29
3.16 PHP data types
Variables can store data of different types, and different data types can do different things.
Array
Object
30
3.16 PHP data types
1.scalar data type: Scalar variables contain only one value at a time. Following are its types
1.1 String:-
A string is a sequence of characters surrounded by single quotes (‘) or double quotes (“). For
Example:
Example 1:-
<?php
$name=”Rajan”;//variable starts with $ sign
echo $name;
?>
31
3.16 PHP data types
1.scalar data type: Scalar variables contain only one value at a time. Following are its types
1.1.2 Integer:-
Integers are whole numbers defined in the set {…-3,-2-,-1,0,1,2,3…}. The size of the integer depends on
the platform where PHP runs. PHP uses the int keyword to denote the integer type.
Example 2:-
<?php
$count = 0;
$max = 1000;
$page_size = 10;
echo”count=”,$count;
?>
32
3.16 PHP data types
1. scalar data type:
1.1.3 Float (floating point numbers - also called double):-
Floats are floating-point numbers, which are also known as floats, doubles, or real numbers. It uses
the ‘float’ keyword to represent floating numbers.
Example 3:-
<?php
$price = 10.25;
$tax = 0.08;
echo $price;
?>
33
3.16 PHP data types
1. scalar data type:
1.1.4 Boolean:-
Boolean represents a truth value that can be either true or false. PHP uses the bool keyword to represent
the Boolean type.
Example 4:-
<?php
$loggen_in=true;
echo $loggen_in;
?>
34
3.16 PHP data types
2. Compound type:
Compound data includes the values that contain more than one value. PHP has two compound types including
array and object. Its types are:
2.1 Array:- An array in PHP is actually an ordered map. A map is a type that
associates values to keys. It helps us to store many values. It is of three types: indexed, associative array and
multidimensional.
Example 5:- Here we have taken indexed array without key. It takes key from 0.
<?php
$country = ["Nepal","USA","China"]; #storing value in array country.we can also use array() function
echo $country[0]."<br>“;#. is for concatenation; 0 is for location. We can also use print_r() /var_dump()
echo $country[1]."<br>";
echo $country[2];
?>
35
3.16 PHP data types
2. Compound type:
2.2 object:- IN OOP, An object is an instance of a class. IT can have some property and value.
?>
36
3.16 PHP data types
3. special type: PHP has two special types:
->null and
->resource
3.1 NULL type:- The null is a special type in PHP. The null type has only one value which is also null. In
fact, null indicates the absence of a value for a variable.
Example 7:-
<?php
$email = null;
$first_name = Null;
$last_name = NULL;
echo $email;
echo $first_name;
echo $last_name;
?>
It will display nothing.
37
3.16 PHP data types
3.2 Resource:-
The resource type holds a reference to an external resource, e.g. a file handle or a database connection.
Example 8:-
<?PHP
$conn = mysqli_connect(localhost,"root","admin","animals");
?>
In this code, the database information is specified for the mysqli_connect() and it returns
MySQL connection object as a resource identifier.
38
3.17 PHP Basic programming
Program 1:-
To find sum of two numbers
<?php
$number1=90;#initialization
$number2=120;
$sum=$number1+$number2;/*formula*/
echo"sum of two numbers is=",$sum;//printing value
?>
39
3.17 PHP Basic programming
Program 2:-
To find square root of a number(constant).
<?php
$number1=90;
$number2=120;
$squareroot=sqrt($number1+$number2);//sqrt () is used to find square root.
echo"square root of sum of two numbers is",'<br>',$squareroot;
?>
40
3.17 PHP Basic programming
Program 3:-
program to print/display name and address of a person.
<?php
$address=” Kathmandu”;
41
3.17 PHP Basic programming
Program 4:-
To input name ,address and print them.
<form method="post">
<label>name is</label><input type="text" name="naam">
<label>address is</label><input type="text" name="address">
<input type="submit" name="submit" value="click to print">
</form>
<?php
if(isset($_POST['submit']))
/*isset() is used to check if the variable is set with the value or not
ISSET comes in or probably, if you want an action to be performed when the user click on SUBMIT.If it is set, it returns true,if not it returns false.
$_POST is a variable used to grab data sent through a web form.
*/
{
$name=$_POST['naam'];//grabs data for input box 'naam' and stores in $name
$address=$_POST['address'];//" "
echo"name is ",$name," address is ",$address;//prints values
}
?>
42
3.17 PHP Basic programming
Program 5:-
To input two numbers and print them.
<form method="post">
<label>number one is</label><input type="text" name="number1">
<label>number two is</label><input type="text" name="number2">
<input type="submit" name="submit" value="click to print">
</form>
<?php
if(isset($_POST['submit']))
{
$n1=$_POST['number1'];
$n2=$_POST['number2'];
echo"first number is ",$n1," second number2 is ",$n2;
}
?>
43
3.17 PHP Basic programming
Program 6:-
To find length of string.
<?php $name="learning js";
echo"length is=",strlen($name);
?>
[note:- some other string functions are: strcmp(), strrev() etc
44
3.18 PHP operators
Definition:-
Operators are the symbols used to carry out some operation.
Arithmetic operators
Assignment operators
Comparison/relational operators
Increment/Decrement operators
Logical operators
String operators
Array operators
Conditional assignment operators
45
3.18 PHP operators
Definition:-
1.Arithmetic operator:-
The PHP arithmetic operators are used with numeric values to perform common arithmetical operations, such as
addition, subtraction, multiplication etc.
Operator Name Example Result
+ Addition $x + $y Sum of $x and $y
- Subtraction $x - $y Difference of $x and $y
* Multiplication $x * $y Product of $x and $y
/ Division $x / $y Quotient of $x and $y
% Modulus $x % $y Remainder of $x divided by $y
** Exponentiation $x ** $y Result of raising $x to the $y'th power
46
3.18 PHP operators
Example:-Arithmetic operator
<?php
Output is:
$n1=12; ------------------------------
$n2=15;
sum is=27
echo"sum is=",$n1+$n2,"<br>";
difference is=-3
echo"difference is=",$n1-$n2,"<br>";
product is=180
echo"product is=",$n1*$n2,"<br>"; division is=0.8
echo"division is=",$n1/$n2,"<br>"; difference is=-3
remainder is=12
//br breaks the line. We may use it with . or inside string.
exponentiarion is=144
echo"difference is=",$n1-$n2,"<br>";
echo"remainder is=",$n1%$n2,"<br>";
echo"exponentiarion is=",$n1**2,"<br>";
?>
47
3.18 PHP operators
2.Assignment operator:-The PHP assignment operators are used with numeric values to write a
value to a variable.
x += y x=x+y Addition
x -= y x=x-y Subtraction
x *= y x=x*y Multiplication
x /= y x=x/y Division
x %= y x=x%y Modulus
48
3.18 PHP operators
Example:-Assignment operator
<?php
$n1=12; Output is:
$n2=15; ------------------------------
$n1=$n2;
echo"n1 is=",$n1,"<br>";
$n1+=$n2;
n1 is=15
echo"n1 is=",$n1,"<br>"; n1 is=30
$n1-=$n2; n1 is=15
echo"n1 is=",$n1,"<br>"; n1 is=225
$n1*=$n2; n1 is=15
echo"n1 is=",$n1,"<br>"; n1 is=0
$n1/=$n2;
echo"n1 is=",$n1,"<br>";
$n1%=$n2;
echo"n1 is=",$n1,"<br>";
?>
49
3.18 PHP operators
3.comparison/relational operators:- The PHP comparison operators are used to compare two values
(number or string):
<= Less than or equal to $x <= $y Returns true if $x is less than or equal to $y
50
3.18 PHP operators
Example:-relational operator Output is:
<?php ------------------------------
$n1=12;
$n2=15; 1.12==15 is=bool(false)
echo"1.$n1==$n2 is=",var_dump($n1==$n2),"<br>";
2.12===15 is=bool(false)
echo"2.$n1===$n2 is=",var_dump($n1===$n2),"<br>";
echo"3.$n1!=$n2 is=",var_dump($n1!=$n2),"<br>";
3.12!=15 is=bool(true)
echo"4.$n1<>$n2 is=",var_dump($n1<>$n2),"<br>"; 4.12<>15 is=bool(true)
echo"5.$n1!==$n2 is=",var_dump($n1!==$n2),"<br>"; 5.12!==15 is=bool(true)
echo"6.$n1>$n2 is=",var_dump($n1>$n2),"<br>"; 6.12>15 is=bool(false)
echo"7.$n1>=$n2 is=",var_dump($n1>=$n2),"<br>"; 7.12>=15 is=bool(false)
echo"8.$n1<$n2 is=",var_dump($n1<$n2),"<br>"; 8.12<15 is=bool(true)
echo"9.$n1<=$n2 is=",var_dump($n1<=$n2),"<br>"; 9.12<=15 is=bool(true)
echo"10.$n1<=>$n2 is=",var_dump($n1<=>$n2),"<br>";
10.12<=>15 is=int(-1)
?>
Note:- The var_dump() function is a built-in function of PHP that dumps the information about the variables.
This information includes the data type and value of the variable.
51
3.18 PHP operators
4.Increment and decrement operator:-
The PHP increment operators are used to increment a variable's value.
The PHP decrement operators are used to decrement a variable's value.
Operator Name Description
52
3.18 PHP operators
Example:-increment/decrement operator Output is:
<?php ------------------------------
$x = 10;
echo"++x=",++$x."<br>"; // Prints: 11 ++x=11
$x = 10;
x++10
echo"x++",$x++,"<br>"; // Prints: 10
$x=10;
--x=9
echo"--x=",--$x,"<br>"; // Prints: 9 x--10
$x = 10;
echo"x--",$x--; // Prints: 10
?>
53
3.18 PHP operators
5.Logical operator:-
The PHP logical operators are used to combine conditional statements.
Operator Name Example Result
54
3.18 PHP operators
Example:-logical operator Output is:
<?php ------------------------------
$number1=3;
$number2=4; bool(false)
$number3=5;
bool(false)
var_dump($number1>$number2 and $number1>$number3 );
//and can be used with &&
bool(true)
echo'<br>';
var_dump($number1>$number2 or $number1>$number3);
//or can be used with ||
echo '<br>';
var_dump(!($number1>$number2));
?>
55
3.18 PHP operators
6. string operator:-
PHP has two operators that are specially designed for strings.
56
3.18 PHP operators
Example:-string operator Output is:
<?php ------------------------------
$name1="Ram kumar";
$name2="Sam Kumar"; merged name=Ram kumarSam Kumar
$merged_name=$name1.$name2;//merges data
merged name=Sam KumarRam kumar)
echo'merged name=',$merged_name,'<br>';
$name2.=$name1;//merging then assigning
echo'merged name=',$name2,'<br>';
?>
57
3.18 PHP operators
7.Conditinal assignment /ternary operator or conditional operator:-The PHP conditional assignment
operators are used to set a value depending on conditions:
58
3.18 PHP operators
7.Conditinal assignment /ternary operator example:- Output is:
------------------------------
<!DOCTYPE html>
<body>
<?php
$txt = "PHP";
$txt1="php";
echo $result;
?>
</body>
</html>
59
3.18 PHP operators
Order of precedence:-
The precedence of an operator specifies how "tightly" it binds two expressions together. For example, in the expression 1 +
5 * 3, the answer is 16 and not 18 because the multiplication ("*") operator has a higher precedence than the addition
("+") operator. Parentheses may be used to force precedence, if necessary.
For instance: (1 + 5) * 3 evaluates to 18.
When operators have equal precedence their associativity decides how the operators are grouped. For example "-" is left-
associative, so 1 - 2 - 3 is grouped as (1 - 2) - 3 and evaluates to -4. "=" on the other hand is right-associative, so $a = $b =
$c is grouped as $a = ($b = $c).
60
3.18 PHP operators
Order of precedence table:-
61
3.19 Variable manipulations
Variable manipulation is a method of specifying or editing variables in a computer program. We may use different functions to
manipulate variables in PHP.
We can understand manipulation with the help of following programs.
Example 1: Simple Mathematics with PHP Variables
<?php
$a=5;
$b=4;
$add = $a + $b;
echo "addition=",$add."<br>";//prints 9
$diff = $a - $b;;
echo "difference=";$diff."<br>";//prints 1
$div = $a * $b;
echo "multiplication=",$div."<br>";//prints20
$answer = 1/3;
echo "quotient=",$answer."<br>";//prints 0.333
$answer = ((5 + 4)*2) % 7; //prints 4
echo "result=",$answer;
?>
62
3.19 Variable manipulations
Example 2: Mathematics with PHP Variables
<?php
$a = 10; Output is:-
$b = 11; -------------------------
results are
$c = 12;
10,11,12
$add = $a + $b + $c;
$sub = $c - $a;
$mult = $a * $b;
$div = $c / 3;
echo"results are","<br>";
echo"$a,$b,$c";
?>
63
3.19 Variable manipulations
64
3.19 Variable manipulations
Example 4:program using ceil() and floor() mathematical function
<?php Output is:-
// Round fractions up -------------------------
echo"using ceil() function","<br>"; using ceil() function
echo ceil(4.3),"<br>"; // 0utputs: 5 5
echo ceil(9.99),"<br>"; // 0utputs: 10 10
echo ceil(-5.76),"<br>"; // 0utputs: -5 -5
// Round fractions down using floor() function
echo"using floor() function","<br>"; 4
echo floor(4.8),"<br>"; // 0utputs: 4 9
echo floor(9.95),"<br>"; // 0utputs: 9 -6
echo floor(-5.12); // 0utputs: -6
?>
65
3.19 Variable manipulations
Example 5:-To find square of (a+b). Here, the numbers are entered by user.
<html>
<head>
<title>
square root
</title>
</head>
<body>
<form method="post" action="">
enter first number<input type="text" name="fnumber"><br>
enter second number<input type="text" name="snumber"><br>
<input type="submit" value="find the result" name="submit">
</form>
<?php
@$fnumber=$_POST["fnumber"];
/*
$_POST is a global variable used to grab data sent through a web form.Here it is for 'fname'.*/
@$snumber=$_POST['snumber'];
66
/*@ is used to When an expression is prepended with the @ sign, error messages that might be
3.19 Variable manipulations
Example 5:-To find square of (a+b). Here numbers are entered by user. (continue)
<?php
@$fnumber=$_POST["fnumber"];
/*
$_POST is a global variable used to grab data sent through a web form.Here it is for 'fname'.*/
@$snumber=$_POST['snumber'];
/*@ is used to When an expression is prepended with the @ sign, error messages that might be
generated by that expression will be ignored.
otherwise, it will print
'undefined array key'!.
better to use isset() function.
*/
$p=2;
$result=($fnumber+$snumber)**$p;
echo"result is",$result;
?>
</body>
</html>
67
3.19 Variable manipulations
Example 6:-string lowercase conversion.
Output is:
<!DOCTYPE html> ------------------------------
<html>
<body>
<?php string in lower case is=i am learning php.
$txt = "I am learning php.";
echo "string in lower case is=",strtolower($txt);
?>
</body>
</html>
68
3.19 Variable manipulations
Output is:
Example 7:- ------------------------------
string first letter in uppercase conversion. string with first letter in upper case is=I Am Learning Php.
<!DOCTYPE html>
<html>
<body>
<?php
$txt = "I am learning php.";
echo "string with first letter in upper case is=",ucwords($txt);
?>
</body>
</html>
69
3.19 Variable manipulations
Example 8:-
70
3.20 PHP database connection with MYSQL
In order to store or access the data inside a MySQL database, you first need to connect to the MySQL database server. PHP
offers two different ways to connect to MySQL server:
MySQLi (Improved MySQL)
and PDO (PHP Data Objects) extensions.
While the PDO extension is more portable and supports more than twelve different databases,
MySQLi extension as the name suggests supports MySQL database only.
MySQLi extension however provides an easier way to connect to, and execute queries on, a MySQL database server.
Both PDO and MySQLi offer an object-oriented API, but MySQLi also offers a procedural API which is relatively easy for
beginners to understand.
71
3.21 Connecting to MYSQL database server
In PHP you can easily do this using the mysqli_connect() function. All communication between PHP and the MySQL
database server takes place through this connection. Here're the basic syntaxes for connecting to MySQL using MySQLi and
PDO extensions:
We are going to talk about MYSQLi procedural way for connection. We will use mysqli_connect() function to connect with
database.
Syntax:-
variable=mysqli_connect("hostname", "username", "password", "database");
e.g.
72
3.21 Connecting to MYSQL database server
Close the Connection
The connection will be closed automatically when the script ends. To close the connection before, we have to use the
following function:
mysqli_close($conn);
Syntax:
mysqli_close(connection name);
mysqli_connect_error():-
PHP mysqli_connect_error() function returns a string value representing the description of the error from the last
connection call, in case of a failure. If we donot use it, it will not display description.
Synatx:-
mysqli_connect_error();
73
3.21 Connecting to MYSQL database server
Example 1:
<?php
$connection=mysqli_connect("localhost","root","","book");
/*using function mysqli_connect(),database is connected and stored
as a variable in $connection. try with different database*/
if($connection)
{
echo"congrats! database connected";
}
else
{
die("database connection failed!").mysqli_connect_error();
}
mysqli_close($connection);
//closes the connection
/*The die() is an inbuilt function in PHP. It is used to print message and exit from the current php
script.*/
?>
74
3.21 Connecting to MYSQL database server
Example 2:
<?php
$connection=mysqli_connect("localhost","root","","book")
/*using function mysqli_connect(),database is connected and stored
as a variable in $connection. try with different database*/
or
mysqli_close($connection);
//closes the connection
/*The die() is an inbuilt function in PHP. It is used to print message and exit from the current php
script.*/
echo"database connected";
//better to use 'if'
?>
75
3.22 SQL queries
SQL:-
SQL is used to communicate with a database. According to ANSI (American National Standards Institute), it is
the standard language for relational database management systems. SQL statements are used to perform tasks
such as update data on a database, or retrieve data from a database.
SQL is Structured Query Language, which is a computer language for storing, manipulating and retrieving data stored in a
relational database.
SQL is the standard language for Relational Database System. All the Relational Database Management Systems (RDMS)
like MySQL, MS Access, Oracle, Sybase, Informix, Postgres and SQL Server use SQL as their standard database language.
Following are some features of SQL:
1. Uses DML,DDL,DQL, DCL etc commands to process data.
2. Client-server execution with remote database access
3. Security and authentication
4. High performance
5. Robust transactional support etc
76
3.22 SQL queries
SQL’s DDL commands with examples:-
This is the means by which the content & format data to be stored is described &
structure of database is defined, including relationship between records & indexing strategies. This definition of database is
known as schema.
It contains statements that are used to define the database structure or schema. Some statements are:
•CREATE - to create objects in the database
•ALTER - alters the structure of the database
•DROP - delete objects from the database
•TRUNCATE - remove all records from a table, including all spaces allocated for the records are removed
•COMMENT - add comments to the data dictionary
•RENAME - rename an object etc
77
3.22 SQL queries
SQL’s DDL commands with examples:-
1. Create: A command which is used to create an object/table or database.
Syntax:
1.Create table(field1 data type,field2 data type,…);
[Note:-Here we have assumed that database has been created and we are inside the database.
Or
We can use following commands to create database.
To create database we use,
create database name; Create table student
To get inside the database, (
Use database name; st_id int primary key auto increment,
Or St_name varchar(100),
We can use GUI interface. St_section varchar(100)
] );
It creates a table named student with fields. This uses DDL
commands.
Example of table:-
78
3.22 SQL queries
SQL’s DDL commands with examples:-
2. Alter: It is used to add, delete, or modify columns in an existing table.
Syntax:
2.alter table table _name
Add column_name data type
;
79
3.22 SQL queries
SQL’s DML commands with examples:-
These are the statements are used for managing data(insertion, deletion,
updation etc) within schema objects. Some commands:
Syntax:-
Insert into table(field1,field2,…)
Values(value1,value2,…)
;
[For string, we use single or double quote]
Example 1: Assuming that we have created table student with some fields(previous slide), if we want to insert some data
Insert into student (St_name, St_section)
Values(“Rajan”,”B”),(“sujan”,”B”)
;
Insertion of data
It inserts two records into table student. This uses DML
commands.to insert multiple values, we have to separate values
using comma.
80
3.22 SQL queries
SQL’s DML commands with examples:-
2.Fetching data/records:-
SELECT – It retrieves data from a database.
Syntax:-
Select column1,column2,…
From table
;
[we can also put condition while fetching data, as shown below.
Assuming that we have table student with some fields(previous slide) and records.
Example 1:
To fetch records with condition:
To fetch records with some fields
to fetch all records ----------------------------------
----------------------------------
-------------------------------------- Select *
Select st_id,st_name
Select * From student
From student
From student Where st_id=1
;
; ;
------------------------------------
------------------------------------------------- ------------------------------------
It prints all records with two
It displays all records with all fields. It prints all records with fields
fields st_id and st_name. 81
and under condition.
3.22 SQL queries
SQL’s DML commands with examples:-
3.Updating data/records:-
update:-It is used to update record.
Syntax:
Update table_name
Set column_name=value
Where condition;
Assuming that we have table student with some fields(previous slide) and records.
82
3.22 SQL queries
SQL’s DML commands with examples:-
4. Deleting data/records:-
delete:-It is used to delete record.
Syntax:
Delete from table_name
Where condition;
Assuming that we have table student with some fields(previous slide) and records.
Example 1:
to delete a record
--------------------------------------
Delete from student
Where st_id=1
; Note:
------------------------------------------------- some more SQL commands are:max(),min(),limit,
It deletes the record with st_id 1 . groupby,avg(),orderby etc.
83
3.23 Fetching datasets;getting data about data
1.Inserting data into table using PHP and MYSQL:- We use following code to insert data.
<?php $dis="insert into book(bookname,bookprice)
$connection=mysqli_connect("localhost","root","","book"); values('physics',600),('chemistry',900)";
//database connection with function and user name and pw //inserting record into table
//it is stored in variable $connection $result=mysqli_query($connection,$dis);
if(!$connection)//if it could not be connected
//mysqli_query() performs query for given
{
echo"database connection
//connection and database and stores in $dis
failed".mysqli_connect_error(); if($result)//if it executes or returns true
} {
else echo("data inserted successfully");
{ }
echo"database connected !!<br>"; else
} {
echo"data insertion
failed".mysqli_error();
}
mysqli_close($connection);
?>
84
3.23 Fetching datasets data about data
2. Deleting record in our database using PHP:-:- For this we use following code.
<?php
$connection=mysqli_connect("localhost","root","","book");
//database connection and stroing in a variable
if(!$connection)//testing the connection
{
echo"data base connection failed".mysqli_connect_error();
//connection failure with message
}
$dis="delete from book where bookname='physics' ";
//sql delete command execution and storing in variable $dis
$result=mysqli_query($connection,$dis);
//query execution and storing in $result variable
if($result)//if the query executed i.e true
{
echo"data deleted successfully";
}
else
{
echo"data deletion failed".mysqli_connect_error();
}
mysqli_close($connection);
?>
85
3.23 Fetching datasets data about data
3. updating record in our database using PHP:-:- For this we use following code.
<?php
$connection=mysqli_connect("localhost","root","","book");
//database connection and stroing in a variable
if(!$connection)//testing the connection
{
echo"data base connection failed".mysqli_connect_error();
//connection failure with message
}
$dis="update book set bookname='computer science' where bookid=1 ";
//sql update command execution and storing in variable $dis
$result=mysqli_query($connection,$dis);
//query execution and storing in $result variable
if($result)//if the query executed i.e true
{
echo"data updated successfully";
}
else
{
echo"data updation failed".mysqli_connect_error();
}
mysqli_close($connection);
?>
86
3.24 Creating SQL database using PHP
1.creating SQL database using PHP:-:- For this we use following code.
<?php
$conn = mysqli_connect("localhost", "root","");
//database connection
if(! $conn ) //testing the connection
{
die('Could not connect: ' . mysqli_connect_error());
}
echo 'Connected successfully';
$sql = 'CREATE Database test_database';
$ret=mysqli_query($conn,$sql);
//query execution and storing in $ret
if(! $ret)
{
die('<br>Could not create database: ' . mysqli_connect_error());
}
echo "<br>Database test_db created successfully\n";
mysqli_close($conn);
?>
87
3.24 Creating SQL database using PHP
2.selecting SQL database using PHP:-:- For this we use following code.
<?php
$conn = mysqli_connect("localhost", "root","");
if(! $conn )
{
die('Could not connect: ' . mysqli_connect_error());
}
echo 'Connected successfully<br>';
mysqli_select_db($conn,'test_database');
//select the databasae for given connection
echo'database selected !!';
mysqli_close($conn);
?>
88
3.24 Creating SQL database using PHP
3. creating table using PHP in MYSQL:- For this we use following code.
<?php $q=mysqli_query($con,$sql);
//we are assuming that 'test_database' exists if($q)//it it is true
$con = mysqli_connect("localhost", "root", "", "test_database"); {
echo "Table created successfully.";
// Checks the connection }
if(!$con) else
{ {
die("ERROR: Could not connect. " . mysqli_connect_error()); echo "ERROR: Could not able to execute $sql. " . mysqli_error($con);
} }
89
3.25 Fetching and displaying data in tables
Fetching data from our database and displaying them in the table:- For this we use following code.
<?php //creates table heading
echo"</tr>";//closing of row
$connection=mysqli_connect("localhost","root","","book");
//database connection while ($row = mysqli_fetch_array($result))
if(!$connection)//testing whether connected or not //mysqli_fetch_array() fetches row
{ from database, in array form, and
echo"data base connection
failed".mysqli_connect_error();
//stores in $row variable .As the
//printing error with message row ends, it returns null.
} {
else echo "<tr>"."<td>".
{
echo"database connected !!<br>"; $row['bookid']."</td>", "<td>".$row['bookname']."</td>","<td>".
} $row['bookprice'] ."</td>"."</tr>" .'<br>';
$dis="select * from book"; //printing of data in different row
$result=mysqli_query($connection,$dis);
//performing query with the help of mysqli_query()
}
//for given connection and database echo"</table>";
//and storing in $dis variable mysqli_close($connection);
echo'<table>';//creates a table
echo'<tr>';//creates a row
echo'<th>'.'bood id'.'</th>','<th>'.' book name '.'</th>','<th>'.'book ?>
price'.'</th>'.'<br>';
90