PHP and Mysql Unit-1

Download as pdf or txt
Download as pdf or txt
You are on page 1of 15

Web Applications Development using PHP& MYSQL B.Sc./ B.

Tech /BCA

UNIT-I
The Building blocks of PHP
Introduction:

PHP stands for Hypertext Preprocessor. PHP is a powerful and widely-


used open source server-side scripting language to write dynamically generated web pages.
PHP scripts are executed on the server and the result is sent to the browser as plain HTML.
PHP can be integrated with the number of popular databases, including MySQL,
PostgreSQL, Oracle, Sybase, Informix, and Microsoft SQL Server. PHP can be embedded
within a normal HTML web pages.

PHP files can contain text, HTML, CSS, JavaScript, and PHP code , PHP code
are executed on the server, and the result is returned to the browser as plain HTML , PHP
files have extension ".php".

Advantages of PHP :

Open source: It is developed and maintained by a large group of PHP developers, this will
helps in creating a support community, abundant extension library.

Speed: It is relative fast since it uses much system resource.

Easy to use: It uses C like syntax, so for those who are familiar with C, it's very easy for them
to pick up and it is very easy to create website scripts.

Stable: Since it is maintained by many developers, so when bugs are found, it can be quickly
fixed.

Powerful library support: we can easily find functional modules you need such as PDF,
Graph etc.

Built-in database connection modules: You can connect to database easily using PHP, since
many websites are data/content driven, so we will use database frequently, this will largely
reduce the development time of web apps.

Can be run on many platforms, including Windows, Linux and Mac, it's easy for users to find
hosting service providers.

Building Blocks or Structure of PHP Program :

WWW.GVRJOBS4U.COM Page 1 of 15
Web Applications Development using PHP& MYSQL B.Sc./ B.Tech /BCA

PHP is a server side scripting language that is embedded in HTML. It is integrated with a
number of popular databases, including MySQL, PostgreSQL, Oracle, Sybase, Informix, and
Microsoft SQL Server.

Example PHP program:

<html>
<body>
<?php
// Use echo to print on console
echo “Hello World!”;
?>
</body>
</html>

Variables in PHP
A variable is a special container that we can define, which then “holds” a value, such as a
number, string, object, array, or a Boolean. A variable can have a short name (like x and y) or
a more descriptive name (age, carname, total_volume).

Rules for PHP variables:

• A variable starts with the $ sign, followed by the name of the variable

• A variable name must start with a letter or the underscore character

• A variable name cannot start with a number

• A variable name can only contain alpha-numeric characters and underscores (A-z, 0-
9, and _ )

• Variable names are case-sensitive ($age and $AGE are two different variables)

Examples : <?php

$x = 5;

$y = 4;

echo $x + $y;

?>

PHP Variables Scope :

In PHP, variables can be declared anywhere in the script. The scope of a variable is the part
of the script where the variable can be referenced/used.

WWW.GVRJOBS4U.COM Page 2 of 15
Web Applications Development using PHP& MYSQL B.Sc./ B.Tech /BCA

PHP has three different variable scopes:

• local

• Global

• Static

Global Scope : A variable declared outside a function has a GLOBAL SCOPE and can only be
accessed outside a function:

Example <?php

$x = 5; // global scope

function myTest() {

echo "<p>Variable x inside function is: $x</p>"; }

myTest();

echo "<p>Variable x outside function is: $x</p>";

?>

Local Scope : A variable declared within a function has a LOCAL SCOPE and can only be
accessed within that function

Example

<?php

function myTest()

{ $x = 5; // local scope

echo "<p>Variable x inside function is: $x</p>";

} myTest();

// using x outside the function will generate an error

echo "<p>Variable x outside function is: $x</p>";

?>

Static :-

Normally, when a function is completed/executed, all of its variables are deleted. However,
sometimes we want a local variable NOT to be deleted. We need it for a further job.

WWW.GVRJOBS4U.COM Page 3 of 15
Web Applications Development using PHP& MYSQL B.Sc./ B.Tech /BCA

To do this, use the static keyword when you first declare the variable:

Example

<?php

function myTest() {

static $x = 0;

echo $x;

$x++;

} myTest(); myTest(); myTest(); ?>

Super Global Variables


In addition to global variables of your own creation, PHP has several predefined
variables called superglobals. These variables are always present, and their values are
available to all our scripts. Each of the following superglobals is actually an array of other
variables:

. $_GET contains any variables provided to a script through the GET method. .

$_POST contains any variables provided to a script through the POST method. .

$_COOKIE contains any variables provided to a script through a cookie.

$_FILES contains any variables provided to a script through file uploads. .

$_SERVER contains information such as headers, file paths, and script locations.

$_ENV contains any variables provided to a script as part of the server environment. .

$_REQUEST contains any variables provided to a script via GET, POST, or COOKIE input
mechanisms.

$_SESSION contains any variables that are currently registered in a session.

:Data Types:
The Properties of data is called datatype . PHP has a total of eight data types which we use
to construct our variables

Simple Types:

WWW.GVRJOBS4U.COM Page 4 of 15
Web Applications Development using PHP& MYSQL B.Sc./ B.Tech /BCA

• Integers − are whole numbers, without a decimal point, like 4195.


• Float or Double − are floating-point numbers, like 3.14159 or 49.1.

• Booleans − have only two possible values either true or false.


• NULL − is a special type that only has one value: NULL.
• Strings − are sequences of characters.

Compound Types:

• Arrays − are named and indexed collections of other values.


• Objects − are instances of programmer-defined classes, which can package up both
other kinds of values and functions that are specific to the class.

• Resources − are special variables that hold references to resources external to PHP
(such as database connections).
Integers:-

• An integer data type is a non-decimal number between -2,147,483,648 and


2,147,483,647. An integer must have at least one digit
• An integer must not have a decimal point
• An integer can be either positive or negative
• Integers can be specified in three formats: decimal (10-based), hexadecimal (16-
based - prefixed with 0x) or octal (8-based - prefixed with 0)
Syntax: <variable_name> = value;

Ex: $int_var=12345;

Float or Double:

A float (floating point number) is a number with a decimal point or a number in exponential
form.

Ex: $many=2.8855;

Boolean:

A Boolean represents two possible states: TRUE or FALSE.


$x = true;
$y = false;
String:

A string is a sequence of characters, like "Hello world!". A string can be any text inside
quotes. You can use single or double quotes.
WWW.GVRJOBS4U.COM Page 5 of 15
Web Applications Development using PHP& MYSQL B.Sc./ B.Tech /BCA

Example: $x = "Hello world!";


NULL:
Null is a special data type which can have only one value: NULL.A variable of data type NULL
is a variable that has no value assigned to it. If a variable is created without a value, it is
automatically assigned a value of NULL. Variables can also be emptied by setting the value
to NULL.

Example: $x = null;

Operators In PHP

Operators are symbols that tell the PHP processor to perform certain actions. For example,
the addition (+) symbol is an operator that tells PHP to add two variables or values, while
the greater-than (>) symbol is an operator that tells PHP to compare two values.
The following lists describe the different operators used in PHP.
Arithmetic Operators
The arithmetic operators are used to perform common arithmetical operations, such as
addition, subtraction, multiplication etc. Here's a complete list of PHP's arithmetic
operators:
Operator Description 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

Assignment Operators

The assignment operators are used to assign values to variables.


Operator Description Example Is The Same As
= Assign $x = $y $x = $y
+= Add and assign $x += $y $x = $x + $y
-= Subtract and assign $x -= $y $x = $x - $y
/= Divide and assign quotient $x /= $y $x = $x / $y
%= Divide and assign modulus $x %= $y $x = $x % $y

Comparison Operators:

The comparison operators are used to compare two values in a Boolean fashion.
Operator Name Example Result

WWW.GVRJOBS4U.COM Page 6 of 15
Web Applications Development using PHP& MYSQL B.Sc./ B.Tech /BCA

== Equal $x == $y True if $x is equal to $y


=== Identical $x === $y True if $x is equal to $y, and they are of the
same type
!= Not equal $x != $y True if $x is not equal to $y
< Less than $x < $y True if $x is less than $y
> Greater than $x > $y True if $x is greater than $y

Incrementing and Decrementing Operators:

The increment/decrement operators are used to increment/decrement a variable's value.


Operator Name Effect
++$x Pre-increment Increments $x by one, then returns $x
$x++ Post-increment Returns $x, then increments $x by one
--$x Pre-decrement Decrements $x by one, then returns $x
$x-- Post-decrement Returns $x, then decrements $x by one

Logical Operators:

The logical operators are typically used to combine conditional statements.


Operator Name Example Result
And And $x and $y True if both $x and $y are true
Or Or $x or $y True if either $x or $y is true
Xor Xor $x xor $y True if either $x or $y is true, but not both
&& And $x && $y True if both $x and $y are true
|| Or $x || $y True if either $$x or $y is true
! Not !$x True if $x is not true

String Operators:

There are two operators which are specifically designed for strings.
Operator Description Example Result
. Concatenation $str1 . $str2 Concatenation of $str1 and $str2
.= Concatenation assignment $str1 .= $str2 Appends the $str2 to the $str1

Array Operators:

The array operators are used to compare arrays:

WWW.GVRJOBS4U.COM Page 7 of 15
Web Applications Development using PHP& MYSQL B.Sc./ B.Tech /BCA

Operator Name Example Result


+ Union $x + $y Union of $x and $y
== Equality $x == $y True if $x and $y have the same key/value pairs
=== Identity $x === $y True if $x and $y have the same key/value pairs in the
same order and of the same types
!== Non- $x !== $y True if $x is not identical to $y
identity

Constant in PHP:
• A constant is a name or an identifier for a fixed value. Constant are like variables
except that once they are defined, they cannot be undefined or changed.
• Constants are very useful for storing data that doesn't change while the script is
running.
• Common examples of such data include configuration settings such as database
username and password, website's base URL, company name, etc.
• Constants are defined using PHP's define() function, which accepts two arguments:
the name of the constant, and its value.
• define(name, value, case-insensitive)
• name: Specifies the name of the constant
• value: Specifies the value of the constant
• case-insensitive: Specifies whether the constant name should be case-
insensitive. Default is false
• Once defined the constant value can be accessed at any time just by referring to its
name.
Example:
<?php
// Defining constant
define("SITE_URL", "https://www.freejobs4us.com/");
// Using constant
echo 'Thank you for visiting - ' . SITE_URL;
?>

PHP Conditional Statements / Flow of Control Statements

Like most programming languages, PHP also allows you to write code that perform different
actions based on the results of a logical or comparative test conditions at run time.

WWW.GVRJOBS4U.COM Page 8 of 15
Web Applications Development using PHP& MYSQL B.Sc./ B.Tech /BCA

There are several statements in PHP that you can use to make decisions:
• The if statement
• The if...else statement
• The if...elseif....else statement
• The switch...case statement

The if Statement:
The if statement is used to execute a block of code only if the specified condition evaluates
to true. This is the simplest PHP's conditional statements and can be written like:
if(condition){
// Code to be executed
}
Example:
<?php
$age = 18;
if($age>=18 ){
echo “You are Major – U R Eligible for Vote !";
} ?>

The if...else Statement:


In the decision making process by providing an alternative choice through adding
an else statement to the if statement. The if...else statement allows you to execute one
block of code if the specified condition is true and another block of code execute if it is
false.
if(condition)
{
// Code to be executed if condition is true
}
Else
{
// Code to be executed if condition is false
}
Example:
<?php
$age = 18;
if($age>=18 ){
echo “You are Major – U R Eligible for Vote !";
}
else
{
echo “You are Minor – U R NOT Eligible for Vote !";
?>

WWW.GVRJOBS4U.COM Page 9 of 15
Web Applications Development using PHP& MYSQL B.Sc./ B.Tech /BCA

The if...elseif...else Statement: The if...elseif...else a special statement that is used to


combine multiple if...else statements.
if(condition)
{
// Code to be executed if condition is true
} elseif(condition){
// Code to be executed if condition is true
} else{
// Code to be executed if condition is false
}
Example:
<?php
$age = 18;
if($age<=15){
echo “You are Eligible for SSC !";
}
elseif(age<=18)
{
echo “You are Eligible for DEGREE";
}
else
{
echo “You are Eligible for PG , PHD";
}

?>

Switch…Case:
The switch-case statement is an alternative to the if-elseif-else statement, which does
almost the same thing. The switch-case statement tests a variable against a series of values
until it finds a match, and then executes the block of code corresponding to that match.

switch(n)
{
case label1:
// Code to be executed if n=label1
break;
case label2:
// Code to be executed if n=label2
break;
...
default:
// Code to be executed if n is different from all labels
}

WWW.GVRJOBS4U.COM Page 10 of 15
Web Applications Development using PHP& MYSQL B.Sc./ B.Tech /BCA

Example:
<?php
$today = date("D");
switch($today){
case "Mon":
echo "Today is Monday. Clean your house.";
break;
case "Tue":
echo "Today is Tuesday. Buy some food.";
break;
case "Wed":
echo "Today is Wednesday. Visit a doctor.";
break;
case "Thu":
echo "Today is Thursday. Repair your car.";
break;
case "Fri":
echo "Today is Friday. Party tonight.";
break;
case "Sat":
echo "Today is Saturday. Its movie time.";
break;
case "Sun":
echo "Today is Sunday. Do some rest.";
break;
default:
echo "No information available for that day.";
break;
}
?>

PHP Loops
Different Types of Loops in PHP
Loops are used to execute the same block of code again and again, until a certain condition
is met. The basic idea behind a loop is to automate the repetitive tasks within a program to
save the time and effort. PHP supports four different types of loops.
• while — loops through a block of code until the condition is evaluate to true.
• do…while — the block of code executed once and then condition is evaluated. If the
condition is true the statement is repeated as long as the specified condition is true.
• for — loops through a block of code until the counter reaches a specified number.
WWW.GVRJOBS4U.COM Page 11 of 15
Web Applications Development using PHP& MYSQL B.Sc./ B.Tech /BCA

PHP while Loop:


The while statement will loops through a block of code until the condition in
the whilestatement evaluate to true.
while(condition)

{
// Code to be executed
}

Example:

<?php
$i = 1;
while($i <= 3){
$i++;
echo "The number is " . $i . "<br>";
}?>
PHP do…while Loop:
The do-while loop is a variant of while loop, which evaluates the condition at the end of
each loop iteration. With a do-while loop the block of code executed once, and then the
condition is evaluated, if the condition is true, the statement is repeated as long as the
specified condition evaluated to is true.
do{
// Code to be executed
}
while(condition);

Example:
<?php
$i = 1;
do{
$i++;
echo "The number is " . $i . "<br>";
}
while($i <= 3);
?>
Difference Between while and do…while Loop:
The while loop differs from the do-while loop in one important way — with a while loop, the
condition to be evaluated is tested at the beginning of each loop iteration, so if the
conditional expression evaluates to false, the loop will never be executed.
With a do-while loop, on the other hand, the loop will always be executed once, even if the
conditional expression is false, because the condition is evaluated at the end of the loop
iteration rather than the beginning.

WWW.GVRJOBS4U.COM Page 12 of 15
Web Applications Development using PHP& MYSQL B.Sc./ B.Tech /BCA

PHP for Loop:


The for loop repeats a block of code until a certain condition is met. It is typically used to
execute a block of code for certain number of times.
for(initialization; condition; increment){
// Code to be executed
}

The parameters of for loop have following meanings:


• initialization — it is used to initialize the counter variables, and evaluated once
unconditionally before the first execution of the body of the loop.
• condition — in the beginning of each iteration, condition is evaluated. If it evaluates to true,
the loop continues and the nested statements are executed. If it evaluates to false, the
execution of the loop ends.
• increment — it updates the loop counter with a new value. It is evaluate at the end of each
iteration.

Example:
<?php
for($i=1; $i<=10; $i=i+1){
echo "The number is " . $i . "<br>";
}
?>

PHP Functions
A function is a self-contained block of code that can be called by your scripts. When A
function is called, the function’s code is executed and performs a particular task. You can
pass values to a function, which then uses the values appropriately—storing them,
transforming them, displaying them, whatever the function is told to do. When finished, a
function can also pass a value back to the original code that called it into action.

PHP Built-in Functions


PHP has a huge collection of internal or built-in functions that you can call directly within
your PHP scripts to perform a specific task, like gettype(), print_r(), var_dump, etc.
PHP User-Defined Functions
PHP also allows you to define your own functions. It is a way to create reusable code
packages that perform specific tasks and can be kept and maintained separately form main
program. Here are some advantages of using functions:
• Functions reduces the repetition of code within a program
• Functions makes the code much easier to maintain
• Functions makes it easier to eliminate the errors

WWW.GVRJOBS4U.COM Page 13 of 15
Web Applications Development using PHP& MYSQL B.Sc./ B.Tech /BCA

• Functions can be reused in other application

Creating and Invoking Functions:

The declaration of a user-defined function start with the word function, followed by the
name of the function you want to create followed by parentheses i.e. () and finally place
your function's code between curly brackets {}.

Example:

<?php
function test()
{
echo "Welcome to My First Function ";
}
test();
?>

Functions with Parameters:


You can specify parameters when you define your function to accept input values at run
time. The parameters work like placeholder variables within a function; they're replaced at
run time by the values (known as argument) provided to the function at the time of
invocation.
Example:
<?php
function add($a, $b)
{
$c = $a + $b;
echo "Sum of the two numbers =”,$c;
}

add(2, 3);
?>

Returning Values from a Function:


A function can return a value back to the script that called the function using the return
statement. The value may be of any type, including arrays and objects.

Example:

<?php

WWW.GVRJOBS4U.COM Page 14 of 15
Web Applications Development using PHP& MYSQL B.Sc./ B.Tech /BCA

function add($a, $b)


{
$c = $a + $b;
return $c;
}
echo add(2, 3);
?>

WWW.GVRJOBS4U.COM Page 15 of 15

You might also like