Note
Note
Program Control
Just as with most other programming languages there are a number of conditional and iteration
constructs in PHP. There are if and switch, and while, do while, for, and foreach loops.
if . . . else
In this syntax the condition to test is contained within () brackets with the body contained in {}
blocks. Optional else if statements can follow, with an else ending the branch. The below code
use a condition to set a greeting variable, depending on the hour of the day.
if ( $hourOfDay > 6 && $hourOfDay < 12 )
{
$greeting = "Good Morning";
}
else if ($hourOfDay == 12)
{
$greeting = "Good Noon Time";
}
else
{
$greeting = "Good Afternoon or Evening";
}
switch . . . case
The switch statement is similar to a series of if . . . else statements.
switch ($artType)
{
case "PT":
$output = "Painting";
break;
case "SC":
$output = "Sculpture";
break;
default:
$output = "Other";
}
For loop
The for loop in PHP has the same syntax as the for loop in JavaScript. The for loop contains the
same loop initialization, condition, and post-loop operations as in JavaScript.
for ($count=0; $count < 10; $count++)
{
echo $count.’<br />’;
}
The foreach loop is used for iterating through arrays or list of elements.
Array keys in most programming languages are limited to integers, start at 0, and go up by 1. In PHP,
keys can be either integers or strings.
Array values are not restricted to integers and strings. They can be any object, type, or primitive
supported in PHP.
Arrays are dynamically sized - elements are added to or deleted from the array during run-time.
Elements within an array are accessed using the familiar square bracket notation.
Arrayvariable[index];
The code below echoes the value of our $days array for the key=1, which results in
output of Tue.
echo "Value at index 1 is ". $days[1]; // index starts at zero
In PHP, keys can be explicitly defined along with the values. This allows us to use keys other than the
classic 0, 1, 2, . . . , n to define the indexes of an array. The array
$days = array(“Mon”,”Tue”,”Wed”,”Thu”,”Fri”); can be defined more explicitly by specifying the
keys and values as
$days = array(0 => "Mon", 1 => "Tue", 2 => "Wed", 3 => "Thu", 4=> "Fri");
Where 0,1,2,… are the keys and “Mon”,”Tue”,… are the values.
These types of arrays in PHP are generally referred to as associative arrays. Keys must be either
integer or string values, but the values can be any type of PHP data type, including other arrays.
In the above example, the keys are strings (for the weekdays) and the values are weather forecasts for
the specified day in integer degrees. To access an element in an associative array,
simply use the key value rather than an index:
echo $forecast["Wed"]; // this will output 52
Multidimensional Arrays
PHP also supports multidimensional arrays, an array within another array. It can be defined as -
$month = array
(
array("Mon","Tue","Wed","Thu","Fri"),
array("Mon","Tue","Wed","Thu","Fri"),
array("Mon","Tue","Wed","Thu","Fri"),
array("Mon","Tue","Wed","Thu","Fri")
);
echo $month[0][3]; // outputs Thu
OR
$cart = array();
$cart[] = array("id" => 37, "title" => "Burial at Ornans", "quantity" => 1);
$cart[] = array("id" => 345, "title" => "The Death of Marat", "quantity" => 1);
$cart[] = array("id" => 63, "title" => "Starry Night", "quantity" => 1);
echo $cart[2]["title"]; // outputs Starry Night
In PHP, arrays are dynamic. The arrays can grow or shrink in size. An element can be added to an
array simply by using a key/index that hasn’t been used.
$days[5] = "Sat";
Since there is no current value for key 5, the array grows by one, with the new key/value pair added to
the end of our array. If the key had a value already, the new value replaces the value at that key.
As an alternative to specifying the index, a new element can be added to the end of any existing array
by -
$days[ ] = "Sun";
The advantage to this approach is that you don’t have to remember the last index key used.
$days = array("Mon","Tue","Wed","Thu","Fri");
Prof. Ashish. D. Revankar PHP & MYSQL 5|Page
$days[7] = "Sat";
print_r($days);
The print_r() - will display the non-NULL elements of the array, as shown below -
Array ([0] => Mon [1] => Tue [2] => Wed [3] => Thu [4] => Fri [7] => Sat)
The NULL value are not displayed.
Elements can be deleted from the array explicitly by using the unset() function –
$days = array("Mon","Tue","Wed","Thu","Fri");
unset($days[2]);
unset($days[3]);
print_r($days); // outputs: Array ( [0] => Mon [1] => Tue [4] => Fri )
The Null values in arrays can be removed and array is reindexed by using the array_values()
function.
$b = array_values($days);
print_r($b); // outputs: Array ( [0] => Mon [1] => Tue [2] => Fri )
// Array is reindexed.
print_r($days) // outputs: Array ( [0] => Mon [1] => Tue [4] => Fri )
It is possible to check if an array index contains a value or NULL by using the isset() function. The
returns true if a value has been set, and false otherwise.
$days = array (1 => "Tue", 3 => "Wed", 5 => "Thurs");
if (isset($days[0]))
{
// The code below will never be reached since $days[0] is not set!
echo "Monday";
}
if (isset($days[1]))
{
echo "Tuesday";
}
There are many built-in sort functions, which sort by key or by value in PHP.
sort(arrayname); - sort the array in ascending order by its values. The array itself is sorted.
$days = array("Mon","Tue","Wed","Thu","Fri");
sort($days);
print_r($days); // outputs: Array ([0] => Fri [1] => Mon [2] => Thu [3] => Tue [4] => Wed)
sort() function loses the association between the values and the keys.
asort(arrayname) – sort the array in ascending order by its values, association is maintained.
Eg –
Prof. Ashish. D. Revankar PHP & MYSQL 6|Page
asort($days);
print_r($days); // outputs: Array ([4] => Fri [0] => Mon [3] => Thu [1] => Tue [2] => Wed)
array_values($Arrayname): This method returns an indexed array with the values being the values
of $ Arrayname.
Eg: print_r(array_values($days))
Outputs - Array ( [0] => Mon [1] => Tue [2] => Wed [3] => Thu [4] => Fri )
array_rand($Arrayname, $num=1): This function returns an array of, as many random keys as are
requested. If you only want one, the key itself is returned;
otherwise, an array of keys is returned.
For example, print_r(array_rand($days,2))
might output: Array (3, 0)
in_array($value, $arrayname): This method search the array $ arrayname for a value ($value). It
returns true if value is found, and false otherwise.
if(in_array(“Wed”,$days))
echo “Element found”;
else
echo “Element not found”;
shuffle($arrayname): This method shuffles $arrayname in random order and makes it an indexed
array.
shuffle($days);
print_r($days); // Array ( [0] => Thu [1] => Fri [2] => Wed [3] => Mon [4] => Tue)
shuffle($days);
print_r($days); // Array ( [0] => Tue [1] => Mon [2] => Thu [3] => Wed [4] => Fri )
Include Files
PHP have facility to include or insert content from one file into another. Include files provide a
Prof. Ashish. D. Revankar PHP & MYSQL 8|Page
mechanism for reusing both markup and PHP code.
PHP provides four different statements for including files, as shown below.
include "somefile.php";
include_once "somefile.php";
require "somefile.php";
require_once "somefile.php";
The difference between include and require lies in what happens when the specified file cannot
be included. With include, a warning is displayed and then execution continues. With require, an
error is displayed and execution stops. The include_once and require_once statements work just
like include and require but if the requested file has already been included once, then it will not
be included again.
UNIT – III
Functions
Prof. Ashish. D. Revankar PHP & MYSQL 9|Page
A function in PHP contains a small bit of code that accomplishes a task. These functions can be
made to behave differently based on the values of their parameters. It exist all on its own, and is
called from anywhere that needs to make use of them.
In PHP there are two types of function: user-defined functions and built-in functions.
A user-defined function is one that the programmer define. A built-in function is one of the
functions that come with the PHP environment. One of the real strengths of PHP is its rich
library of built-in functions.
Function Syntax
The PHP function uses ‘function’ keyword followed by the function’s name, round ( )
brackets for parameters, and then the body of the function inside curly { } brackets. Functions can
return values to the caller, or not return a value.
Syntax:
function functionname(parameter list)
{
}
Eg:
function getSum()
{
$x=5;$y=6;
$z= $x+$y;
echo $z;
}
A function called getNiceTime(), which will return a formatted string containing the current
server time
function getNiceTime()
{
return date("H:i:s");
}
Calling a Function
To call a function you must use its name with the () brackets. Since getNiceTime() returns a
Prof. Ashish. D. Revankar PHP & MYSQL 10 | P a g e
string, you can assign that return value to a variable, or echo that return value directly, as shown
below.
$output = getNiceTime();
OR
echo getNiceTime();
If the function doesn’t return a value, you can just call the function:
getSum();
<?php
function getSum($x,$y)
{
$z= $x+$y;
return $z; // return $x+$y;
}
$ sum =getSum(5,6);
Echo $sum;
?>
Parameters
Parameters are the mechanism by which values are passed into functions, and there are some
complexities that allow us to have multiple parameters, default values, and to pass objects by
reference instead of value. Parameters, being a type of variable, must be prefaced with a $
symbol like any other PHP variable
<?php
function getSum($x,$y)
{
$z= $x+$y;
echo $z;
}
getSum(5,6);
?>
In PHP, parameter default values can be set for any parameter in a function. However, once
you start having default values, all subsequent parameters must also have defaults.
<?php
function getSum($x,$y=10)
{
Output:
sum of 5 and6 is 11
sum of 15 and 10 is 25
sum of 12 and 14 is 26
sum of 25 and 10 is 35
Even if 2nd parameter value is not passed to the function, the default value 10 is taken. If the
value is passed, the default will be overridden by whatever that value was.
By default, arguments passed to functions are passed by value in PHP. This means that PHP
passes a copy of the variable so if the parameter is modified within the function, it does not
change the original.
In the below example, notice that even though the function modifies the parameter value, the
contents of the variable passed to the function remain unchanged after the function has been
called.
function changeParameter($arg)
{
$arg += 300;
echo "arg=" . $arg;
}
$initial = 15;
PHP allows arguments to functions to be passed by reference, which will allow a function to
change the contents of a passed variable. A parameter passed by reference points the local
variable to the same place as the original, so if the function changes it, the original variable is
changed as well. The mechanism in PHP to specify that a parameter is passed by reference is to
add an ampersand (&) symbol next to the parameter name in the function definition.
Eg:
function changeParameter(&$arg)
{
$arg += 300;
echo "arg=" . $arg;
}
$initial = 15;
echo "<br/>initial=" . $initial;
changeParameter($initial);
echo "<br/>initial=" . $initial; // value changed
Output:
initial=15
arg =315
initial=315
All variables defined within a function have function scope, ie. they are only accessible within
the function.
Unlike in other language, in PHP any variables created outside of the function in the main script
are unavailable within a function. For instance, in the following example, the output of the echo
within the function is 0 and not 56 since the reference to $count within the function is assumed to
be a new
variable named $count with function scope.
$count= 56;
function testScope() {
echo $count; // outputs 0 or generates run-time warning/error
}
testScope();
echo $count; // outputs 56
The program results in run – time error
Prof. Ashish. D. Revankar PHP & MYSQL 13 | P a g e
PHP allow variables with global scope to be accessed within a function using the global
keyword.
<?php
$count= 56;
function testScope() {
global $count;
echo $count;
}
testScope();
echo $count;
?>
Output:
56
56
Strings in PHP
PHP string is a sequence of characters i.e., used to store and manipulate text.
Prof. Ashish. D. Revankar PHP & MYSQL 14 | P a g e
1.single quoted : We can create a string in PHP by enclosing the text in a single-quote. It is the
easiest way to specify string in PHP.
Eg: $str='Hello text within single quote';
2. double quoted : In PHP, we can specify string through enclosing text within double quote also.
But escape sequences and variables will be interpreted using double quote PHP strings.
eg: $num1=10;
echo "Number is: $num1";
Object:
A class defines an individual instance of the data structure. We define a class once and then make
many objects that belong to it. Objects are also known as an instance.
Syntax:
<?php
class MyClass
{
// Class properties and methods go here
}
$obj = new MyClass;
var_dump($obj);
?>
Object Properties:
Once you have instances of an object, you can access and modify the properties of each one
separately using the variable name and an arrow (->).
Example of class and object:
<?php
class demo
{
private $a= "hello javatpoint";
public function display()
{
echo $this->a;
Inheritance:
It is a concept of accessing the features of one class from another class. If we inherit the class
features into another class, we can access both class properties. We can extends the features of a
class by using 'extends' keyword.
Inheritance has three types, single, multiple and multilevel Inheritance.
PHP supports only single inheritance, where only one class can be derived from single parent
class.
We can simulate multiple inheritance by using interfaces.
Example
<?php
class a
{
function fun1()
{
echo "javatpoint";
}
}
class b extends a
{
?>
Constructors:
PHP 5 allows developers to declare constructor methods for classes.
Constructor is suitable for any initialization that the object may need before it is used.
We can design constructor using "__construct" or same name as class name.
Parent constructors are not called implicitly if the child class defines a constructor. In order to run
a parent constructor, a call to parent::__construct().
Example
<?php
class Example
{
public function __construct()
{
echo "Hello kle bca dwd";
}
}
$obj = new Example();
Prof. Ashish. D. Revankar PHP & MYSQL 19 | P a g e
$obj = new Example();
?>
Destructors:
P 5 introduces a destructor concept similar to that of other object-oriented languages, such as C++.
The destructor method will be called as soon as all references to a particular object are removed
or when the object is explicitly destroyed in any order in shutdown sequence.
We create destructor by using "__destruct" function.
Example
<?php
class Example
{
public function __construct()
{
echo "Hello kle bca dwd";
}
pubfunction __destruct()
{
echo "destroy.....";
}
}
$obj = new Example();
$obj = new Example();
?>
Superglobal Arrays
PHP uses special predefined associative arrays called superglobal variables. It allows the programmer
to easily access HTTP headers, query string parameters, and other commonly needed information.
They are called superglobal because these arrays are always accessible, from a function , class or file,
without using the global keyword.
UNIT – IV
MySQL is a relational database management system based on the Structured Query Language,
which is the popular language for accessing and managing the records in the database. MySQL is
open-source and free software under the GNU license. It is supported by Oracle Company.
Database :A database is an application that stores the organized collection of records. It can be
accessed and manage by the user very easily. It allows us to organize data into tables, rows,
columns, and indexes to to find the relevant information very quickly.
MySQL is currently the most popular database management system software used for managing
the relational database. It is open-source database software,e relevant information very quickly.
MySQL Works
MySQL follows the working of Client-Server Architecture. This model is designed for the end-
users called clients to access the resources from a central computer known as a server using
network services.
Here, the clients make requests through a graphical user interface (GUI), and the server will give
the desired output as soon as the instructions are matched. The process of MySQL environment is
the same as the client-server model.
MySQL Commands
1. MySQL Create Database
create database db1;
<?php
<?php
$host = 'localhost:3306';
$user = ‘root';
$pass = ‘ ';
$conn = mysql_connect($host, $user, $pass);
if(! $conn )
{
mysqli_close($conn);
?>
<?php
$host = 'localhost:3306';
Prof. Ashish. D. Revankar PHP & MYSQL 26 | P a g e
$user = '';
$pass = '';
$dbname = 'test';
$conn = mysqli_connect($host, $user, $pass,$dbname);
if(!$conn){
die('Could not connect: '.mysqli_connect_error());
}
echo 'Connected successfully<br/>';
<?php
$host = 'localhost:3306';
$user = '';
$pass = '';
$dbname = 'test';
$id=2;
$name="Rahul";
$salary=80000;
$sql = "update emp4 set name=\"$name\", salary=$salary where id=$id";
if(mysqli_query($conn, $sql)){
echo "Record updated successfully";
}else{
echo "Could not update record: ". mysqli_error($conn);
}
mysqli_close($conn);
?>