PHP Conv
PHP Conv
Introduction to PHP:
Page | 1
PHP is a recursive acronym for "PHP: Hypertext Preprocessor". Rasmus Lerdorf
unleashed the first version of PHP way back in 1994. The PHP Hypertext
Preprocessor (PHP) is a programming language that allows web developers to create
dynamic content that interacts with databases. PHP is basically used for developing
web based software applications.
<html>
<body>
<?php
// Use echo to print on console
echo ―Hello World‖;
?>
</body>
</html>
Comments in PHP
// Single line comment (C++ and Java-style comment)
# Single line comment (Shell-style comments)
/* Multiple line comment (C-style comments) */
VARIABLES
The main way to store information in the middle of a PHP program is by using a
variable.
Here are the most important things to know about variables in PHP.
1. All variables in PHP are denoted with a leading dollar sign ($).
2. Variables are assigned with the = operator, with the variable on the left-hand
side and the expression to be evaluated on the right.
4. Variables in PHP do not have intrinsic types - a variable does not know in
advance whether it will be used to store a number or a string of characters.
5. Variables used before they are assigned have default values. Page | 2
Syntax:
$var_name = value;
Ex :
<html>
<body>
<?php
$a = 25; // Numerical variable
$b = ―Hello‖; // String variable
$c = 5.7; // Float variable
echo ―Number is : ―.$a.
―<br/>‖; echo ―String is : ―.
$b. ―<br/>‖; echo ―Float value
:‖ .$c;
?>
</body>
<html>
ECHO and PRINT statements in PHP
- It can output one or more strings
– It can only output one string, and returns always 1
u need to output data through a function, you can use PRINT() instead:
DATA TYPES
PHP has a total of eight data types which we use to construct our variables –
Simple Types:
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.
Compound Types:
Arrays − are named and indexed collections of other values.
Page | 4
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:-
Ex: $int_var=12345;
Float or Double:
Ex:
$many=2.8855;
Boolean:
$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.
Example:
<?php
$x = "Hello world!";
$y = 'Hello world!';
Unit I
echo $x;
echo "<br>";
echo $y;
?> Page | 5
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:
<?php
$x = "Hello world!";
$x = null;
var_dump($x);
?>
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
Example:
Unit I
<?php
$x = 10;
$y = 4;
Page | 6
echo($x + $y); // 0utputs: 14
echo($x - $y); // 0utputs: 6
echo($x * $y); // 0utputs: 40
echo($x / $y); // 0utputs: 2.5
echo($x % $y); // 0utputs: 2
?>
Assignment Operators
= Assign $x = $y $x = $y
+= Add and assign $x += $y $x = $x + $y
-= Subtract and assign $x -= $y $x = $x - $y
*= Multiply 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
Example:
<?php
$x = 10;
echo $x; // Outputs: 10
$x = 20;
$x += 30;
echo $x; // Outputs: 50
$x = 50;
$x -= 20;
echo $ ; // Outputs: 30
$x = 5;
$x *= 25;
echo $x; // Outputs: 125
$x = 50;
$x /= 10;
echo $x; // Outputs: 5
Unit I
$x = 100;
$x %= 15;
echo $x; // Outputs: 10
Page | 7
?>
Comparison Operators:
The comparison operators are used to compare two values in a Boolean fashion.
Operator Name Example Result
Example:
<?php
$x = 25;
$y = 35;
$z = "25";
var_dump($x == $z); // Outputs: boolean true
var_dump($x === $z); // Outputs: boolean false
var_dump($x != $y); // Outputs: boolean true
var_dump($x !== $z); // Outputs: boolean true
var_dump($x < $y); // Outputs: boolean true
var_dump($x > $y); // Outputs: boolean false
var_dump($x <= $y); // Outputs: boolean true
var_dump($x >= $y); // Outputs: boolean false
?>
Unit I
Example
<?php
$x = 10;
echo ++$x; // Outputs: 11
echo $x; // Outputs: 11
$x = 10;
echo $x++; // Outputs: 10
echo $x; // Outputs: 11
$x = 10;
echo --$x; // Outputs: 9
echo $x; // Outputs: 9
$x = 10;
echo $x--; // Outputs: 10
echo $x; // Outputs: 9
?>
Logical Operators:
String Operators:
There are two operators which are specifically designed for strings.
Operator Description Example Result
Example:
<?php
$x = "Hello";
$y = " World!";
echo $x . $y; // Outputs: Hello World!
$x .= $y;
echo $x; // Outputs: Hello World!
?>
Array Operators:
Example:
<?php
$x = array("a" => "Red", "b" => "Green", "c" => "Blue");
$y = array("u" => "Yellow", "v" => "Orange", "w" => "Pink");
$z = $x + $y; // Union of $x and $y
var_dump($z);
var_dump($x == $y); // Outputs: boolean false
var_dump($x === $y); // Outputs: boolean false
var_dump($x != $y); // Outputs: boolean true
var_dump($x <> $y); // Outputs: boolean true
var_dump($x !== $y); // Outputs: boolean true
?>
Concatenation Operator:
The concatenation operator is represented by a single period (.). Treating both
operands as strings, this operator appends the right-side operand to the left-side
operand. So
―hello‖.‖ world‖
Returns
“hello world”
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.
Unit I
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
Page | 11
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)
o name: Specifies the name of the constant
o value: Specifies the value of the constant
o 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.tutorialrepublic.com/"); // Using constant
echo 'Thank you for visiting - ' . SITE_URL;
?>
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:
Unit I
<?php
$d = date("D");
if($d == "Fri"){
echo "Have a nice weekend!"; Page | 12
}
?>
The if...else Statement:
You can enhance 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 evaluates to true and another
block of code if it is evaluates to false.
if(condition)
{
// Code to be executed if condition is true
} else
{
// Code to be executed if condition is false
}
Example:
<?php
$d = date("D");
if($d == "Fri")
{
echo "Have a nice weekend!";
} else{
echo "Have a nice day!";
}
?>
if(condition)
{
// Code to be executed if condition is true
} else if(condition)
{
// Code to be executed if condition is true
} else
{
// Code to be executed if condition is false
}
Unit I
Example:
<?php
$d = date("D"); Page | 13
if($d == "Fri")
{
echo "Have a nice weekend!";
} elseif($d == "Sun")
{
echo "Have a nice Sunday!";
} else
{
echo "Have a nice day!";
}
?>
Example:
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 label 1:
// Code to be executed if n=label1
break;
case label 2:
// Code to be executed if n=label2
break;
...
default:
// Code to be executed if n is different from all labels
}
Example:
Unit I
<?php
$today = date("D");
switch($today)
Page | 14
{
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.
Unit I
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.
Page | 15
foreach — loops through a block of code for each element in an array.
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);
?>
Unit I
Example:
<?php
for($i=1; $i<=3; $i++)
{
echo "The number is " . $i . "<br>";
}
?>
PHP foreach Loop:
The foreach loop is used to iterate over arrays.
foreach($array as $value){
// Code to be executed
}
Unit I
Example:
<?php
$colors = array("Red", "Green", "Blue");
Page | 17
There is one more syntax of foreach loop, which is extension of the first.
foreach($array as $key => $value){
// Code to be executed
}
Example:
<?php
$superhero = array(
"name" => "Peter Parker",
"email" => "[email protected]",
"age" => 18
);
PHP FUNCTIONS
A function is a self-contained block of code that can be called by your scripts. When
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
Unit I
n addition to the built-in 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
Page | 18
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
Functions can be reused in other application
Example:
<?php
// Defining function
function saikiran()
{
echo "welome to my world‖;
}
// Calling function
saikiran();
?>
Note:A function name must start with a letter or underscore character not with a
number, optionally followed by the more letters, numbers, or underscore characters.
Function names are case-insensitive.
Example:
<?php
// Defining function
function getSum($num1, $num2)
{
$sum = $num1 + $num2;
echo "Sum of the two numbers $num1 and $num2 is : $sum";
}
// Calling function
getSum(10, 20); ?
>
<?php
// Defining function
function getSum($num1, $num2)
{
$total = $num1 + $num2;
return $total;
}
// Printing returned value
echo getSum(5, 10); // Outputs: 15
?>
i.e. where the variable can be used or accessed. This accessibility is known as variable
scope.
By default, variables declared within a function are local and they cannot be viewed or
Page | 20
manipulated from outside of that function, as demonstrated in the example below:
Example:
<?php
// Defining function
function test()
{
$greet = "Hello World!";
echo $greet;
}
test(); // Outputs: Hello World!
echo $greet; // Generate undefined variable error
?>
The global Keyword:
There may be a situation when you need to import a variable from the main program
into a function, or vice versa. In such cases, you can use the global keyword before the
variables inside a function. This keyword turns the variable into a global variable,
making it visible or accessible both inside and outside the function, as show in the
example below:
Example:
<?php
$greet = "Hello
World!"; // Defining
function
function test()
{
global $greet;
echo $greet;
}
test();
echo $greet;
$greet = "Goodbye";
test();
echo $greet;
?>
Page | 21
Unit I
keep_track();
keep_track();
keep_track();
?>
Example:
<?php
function customFont($font, $size=1.5)
{
echo "<p style=\"font-family: $font; font-size: {$size}em;\">Hello, world!</p>";
}
customFont("Arial", 2);
customFont("Times", 3);
customFont("Courier"); ?
>
Passing Variable References to Functions
In PHP there are two ways you can pass arguments to a function: by value and by
reference. By default, function arguments are passed by value so that if the value of
the argument within the function is changed, it does not get affected outside of the
function. However, to allow a function to modify its arguments, they must be passed
by reference.
Unit I
Page | 23
Example:
<?php
function selfMultiply(&$number)
{
$number = $number*$number;
return $number;
}
$mynum = 5;
echo $mynum; // Outputs: 5
selfMultiply($mynum);
echo $mynum; // Outputs: 25
?>
PHP Arrays:-
PHP array is an ordered map (contains value on the basis of key). It is used to hold multiple values of
similar type in a single variable. An array is a special variable that can hold many values under a single
name, and you can access the values by referring to an index number or name.
Page | 24
Advantage of PHP Array
Less Code: We don't need to define multiple variables.
Easy to traverse: By the help of single loop, we can traverse all the elements of an array.
Multidimensional Array
1st way:
Ex: $season=array("summer","winter","spring","autumn");
Program:
<?php
$season=array("summer","winter","spring","autumn");
echo "Season are: $season[0], $season[1], $season[2] and $season[3]";
?>
Output:
2nd way:
Ex: $season[0]="summer";
$season[1]="winter";$season[2]="spring";
$season[3]="autumn";
Program:
<?php
$season[0]="summer";
$season[1]="winter";
$season[2]="spring"; Page | 25
$season[3]="autumn";
Output:
1st way:
Ex: $salary=array("Sonoo"=>"350000","John"=>"450000","Kartik"=>"200000");
Program:
<?php
$salary=array("Sonoo"=>"350000","John"=>"450000","Kartik"=>"200000");
echo "Sonoo salary: ".$salary["Sonoo"]."<br/>"; echo "John salary: ".
$salary["John"]."<br/>";
Output:
2nd way:
$salary["Sonoo"]="350000";
$salary["John"]="450000";
$salary["Kartik"]="200000";
Program:
<?php
$salary["Sonoo"]="350000";
$salary["John"]="450000";
$salary["Kartik"]="200000";
echo "Sonoo salary: ".$salary["Sonoo"]."<br/>";
echo "John salary: ".$salary["John"]."<br/>";
echo "Kartik salary: ".$salary["Kartik"]."<br/>";
?>
Output:
PHP multidimensional array can be represented in the form of matrix which is represented by row *
column.
Definition
$emp = array
(
array(1,"sonoo",400000),
array(2,"john",500000),
array(3,"rahul",300000) )
;
Let's see a simple example of PHP multidimensional array to display following tabular data. In this
example, we are displaying 3 rows and 3 columns.
Id Name Salary
1 sonoo 400000
2 john 500000
3 rahul 300000
<?php
$emp = array
(
array(1,"sonoo",400000),
array(2,"john",500000),
array(3,"rahul",300000) )
;
for ($row = 0; $row < 3; $row++)
{
for ($col = 0; $col < 3; $col++)
{
echo $emp[$row][$col]." ";
}
echo "<br/>";
}
Page | 27
?>
Output:
1 sonoo 400000
2 john 500000
3 rahul 300000 Page | 28
PHP OBJECTS
Object-oriented programming (OOP) is a popular programming paradigm that allows developers to create
more organized, efficient, and modular code. PHP is a versatile language that supports OOP, Whether you
are a beginner or an experienced developer, understanding classes and objects in PHP is essential for
building scalable and maintainable web applications. If you're looking to hire PHP developers, make sure
they have a strong understanding of OOP principles.
Syntax:
class MyClass
class MyClass
{
public $property1;
private $property2;
protected $property3;
public function method1()
{
// Code goes here
}
private function method2()
{
// Code goes here
}
protected function method3()
{
// Code goes here Page | 29
}
}
Creating an Object
To create an object from a class, use the new keyword followed by the class name and a pair of parentheses.
Eg:
To access the properties and methods of an object, use the arrow operator (→) followed by the property or
method name. Keep in mind that you can only access public and protected properties and methods from
outside the class.
$object1(→method1();
Program:1
<?php
class SayHello
{
function hello()
{
echo "Hello World";
}
}
$obj=new SayHello;
$obj->hello();
?>
Output
Hello World
Program-2
<?php
$obj=new stdClass;
$obj→name="Deepak";
$obj→age=21;
$obj→marks=75;
echo $obj;
?>
Output
stdClass Object(
[marks] => 75
Program-3
<?php
$arr=array("name"=>"Deepak", "age"=>21, "marks"=>75);
$obj=(object)$arr;
echo $obj;
?>
Output
stdClass Object(
[name] => Deepak
[age] => 21
[marks] => 75
)
Program-4
<?php
$obj=new stdClass;
$obj->name="Deepak";
$obj->age=21;
$obj->marks=75;
$arr=(array)$obj;
echo $arr;
?>
Output
Array(
[name] => Deepak
[age] => 21
[marks] => 75
)
Program-5 <?
php
$name="Deepak";
$age=21;
$percent=75.50;
$obj1=(object)$name;
print_r($obj1);
$obj2=(object)$age;
print_r($obj2);
$obj3=(object)$percent;
print_r($obj3);
?>
Output
stdClass Object(
[scalar] => Deepak
)
stdClass Object(
[scalar] => 21 Page | 31
)
stdClass Object(
[scalar] => 75.5
)
Formatting strings with PHP
The sprintf() function is an inbuilt function in PHP that is used for formatting strings in a manner similar to
the C language’s printf() function. It allows you to create formatted strings by substituting placeholders with
corresponding values.
Syntax:
string sprintf(string $format, mixed ...$values)
Parameters: This function accepts two parameters that are described below:
$format: This is a string that specifies the format of the output. It contains placeholders that begin with a
percent sign (%) followed by a character representing the type of value that should be inserted at that
position.
$values: These are the values that will replace the placeholders in the format string. You can provide any
number of arguments, depending on the number of placeholders in the format string and their types.
Return Values: The sprintf() function returns the string which is produced by this function.
1. Concatenation
Use the dot (.) operator to concatenate strings.
$name = "sai";
$greeting = "Hello". $name;
echo $greeting;
// Outputs: Hello sai
2. String Interpolation
Use double quotes to embed variables within strings.
$name = "sai";
$greeting = "Hello, $name";
echo $greeting;
// Outputs: Hello, sai
3. sprintf()
Use sprintf() to format strings with placeholders.
$name = "saikiran";
$age = 30;
$greeting = sprintf("Hello, %s You are %d years old.", $name, $age);
echo $greeting;
// Outputs: "Hello, saikiran You are 30 years old."
4. printf()
Use printf() to format and print strings.
$name = "saikiran";
$age = 30;
printf("Hello, %s You are %d years old.", $name, $age);
// Outputs: "Hello, saikiran You are 30 years old."
5. String Formatting with Arrays
Use implode() to format strings with arrays.
$fruits = array("apple", "banana", "cherry");
$fruitList = implode(", ", $fruits);
echo $fruitList;
// Outputs: apple, banana, cherry
Program:
<?php
$name = "John";
$greeting = "Hello, " . $name; Page | 32
echo $greeting . "\n";
$greeting = "Hello, $name";
echo $greeting . "\n";
$age = 30;
$greeting = sprintf("Hello, %s! You are %d years old.", $name, $age);
echo $greeting . "\n";
printf("Hello, %s! You are %d years old.", $name, $age);
echo "\n";
$fruits = array("apple", "banana", "cherry");
$fruitList = implode(", ", $fruits);
echo "Fruit list: $fruitList\n";
echo "Uppercase: " . strtoupper($name) . "\n";
echo "Lowercase: " . strtolower($name) . "\n";
$text = " Hello World! ";
echo "Trimmed: '" . trim($text) . "'\n";
echo "Padded: '" . str_pad($text, 20, "*") . "'\n";
?>
This program demonstrates the following string formatting techniques:
Concatenation
String Interpolation
sprintf()
printf()
String Formatting with Arrays
Uppercase and Lowercase
Trim and Pad
Investigating Strings with PHP& Manipulating Strings with PHP,
You do not always know everything about the data that you are working with. Strings can arrive from many
sources, including user input, databases, files, and Web pages. Before you begin to work with data from an
external source, you often will need to find out more about it. PHP provides many functions that enable you
to acquire information about strings.
<?php
$string = "Hello World!";
$length = strlen($string);
echo "Length: $length\n";
$position = strpos($string, "World");
echo "Position of 'World': $position\n";
$substring = substr($string, 6);
echo "Substring from position 6: $substring\n";
if (strpos($string, "World") !== false)
{
echo "String contains 'World'\n";
}
if (strpos($string, "Hello") === 0)
{
echo "String starts with 'Hello'\n";
}
if (substr($string, -5) === "World")
{
echo "String ends with 'World'\n";
}
$replaced = str_replace("World", "Universe", $string);
echo "String replaced with 'Universe': $replaced\n";
$uppercase = strtoupper($string);
$lowercase = strtolower($string); Page | 33
echo "Uppercase: $uppercase\n";
echo "Lowercase: $lowercase\n";
$trimmed = trim(" Hello World ");
echo "Trimmed string: $trimmed\n";
$fruits = explode(",", "apple,banana,cherry");
print_r($fruits);
?>
This program demonstrates the following string investigation techniques:
1. String Length
2. String Position
3. Substring
4. String Contains
5. String Starts With
6. String Ends With
7. String Replace
8. String Uppercase/Lowercase
9. String Trim
10. String Split
PHP Date and Time Functions:
the date/time functions allow you to get the date and time from the server where your PHP script runs. You
can then use the date/time functions to format the date and time in several ways.
Note: These functions depend on the locale settings of your server. Remember to take daylight saving time
and leap years into consideration when working with these functions.
Program:
<?php
echo "Current Date and Time: " . date("Y-m-d H:i:s") . "\n";
echo "Formatted Date: " . date("l, F j, Y") . "\n";
$timestamp = time();
echo "Timestamp: $timestamp\n";
echo "Converted Timestamp: " . date("Y-m-d H:i:s", $timestamp) . "\n";
echo "Date + 1 Week: " . date("Y-m-d", strtotime("+1 week")) . "\n";
date_default_timezone_set("America/New_York");
echo "Current Date and Time (New York): " . date("Y-m-d H:i:s") . "\n";
$date1 = new DateTime("2024-08-08");
$date2 = new DateTime("2024-08-15");
$interval = $date1->diff($date2);
echo "Date Interval: " . $interval->days . " days\n";
$start = new DateTime("2024-08-08");
$end = new DateTime("2024-08-15");
$interval = new DateInterval("P1D");
$period = new DatePeriod($start, $interval, $end);
echo "Date Period:\n";
foreach ($period as $date) {
echo $date->format("Y-m-d") . "\n";
}
?>
This program demonstrates the following date and time functions:
Current Date and Time
Formatting Dates
Date Arithmetic
Time Zones
Date Interval
Date Period Page | 34
Unit-III
PHP
PHP is an acronym for "Hypertext Preprocessor". It is a widely-used, open source scripting
language. This code can be executed on the server and the result is returned to the browser as plain
HTML. PHP files can contain text, HTML, CSS, JavaScript, and PHP code. PHP files have extension Page | 35
".php". You do not need to compile anything or install any extra tools php.
By using PHP we can generate dynamic page content which can collect form data and add, delete,
modify data in your database. PHP is not limited to output HTML. You can output images, PDF files,
and even flash movies. It can send and receive cookies and also control user-access.
PHP runs on various platforms (Windows, Linux, Unix, Mac OS X, etc.) and compatible with
almost all servers used today (Apache, IIS, etc.) so it supports a wide range of databases. It is easy to
learn and runs efficiently on the server side.
Executing PHP Programs:
1. Install PHP and MySQL in your Computer.
2. First create your own directory inside WWW directory which is located
at Local Disc C Wamp server directory.
Like C:\wamp\www
3. Then just create some .php files, that should to be placed in that
directory.
4. Start WAMP server located at start menu and put it online:
5. Open Web browser and go for http://localhost/. It will show PHP
option Under Your Projects open PHP-it contains all the phpfiles.
Click on your required file. You do not need to compile by using any
tools. It will be automatically execute your PHP file.
PHP 5 Syntax:
A PHP script is executed on the server, and the plain HTML result is sent back to the browser.
A PHP file normally contains HTML tags, and some PHP scripting code.
A PHP script can be placed anywhere in the document.
A PHP script starts with <?php and ends with ?>
<?php
// PHP code goes here
?>
The default file extension for PHP files is ".php".
PHP statements end with a semicolon (;)
PHP script that uses a built-in PHP function "echo" to output on a web page.
In PHP, all keywords (e.g. if, else, while, echo, etc.), classes, functions, and user-defined
functions are NOT case-sensitive.
Ex: ECHO,echo are the same,
However; all variable names are case-sensitive.
Ex: $color, $COLOR, and $coLOR are treated as three different variables.
PHP is a Loosely Typed Language- we did not have to tell PHP which data type the variable is.
PHP automatically converts the variable to the correct data type, depending on its value.
Example:
<!DOCTYPE html>
<html>
<body>
<h1>My first PHP page</h1>
<?php
echo "welcome to PHP programming";
?>
</body>
</html>
PHP Variables:
Variables are "containers or entities" for storing some information. In PHP, a variable starts with
the $ sign, followed by the name of the variable.
2. The global keyword is used to access a global variable from within a function. To do this, use
the global keyword before the variables (inside the function):
<?php
$x = 5;
$y = 10;
function calculate()
{
global $x, $y;
$y = $x + $y;
}
calculate ();
echo $y;
?>
PHP also stores all global variables in an array called $GLOBALS[index].The indexholds the
name of the variable. This array is also accessible from within functions directly.
function caliculate()
{
$GLOBALS['y'] = $GLOBALS['x'] + $GLOBALS['y'];
}
Static scope:
Normally, when a function is completed / executed, all of its variable values are deleted.
However, sometimes we want a local variable value NOT to be deleted. We need it for a further job. To
do this, use the static keyword when you first declare the variable:
<?php
function calculate()
{
static $x = 123;
echo $x;
Page | 39
$x+
+; }
calculate ();
calculate ();
?>
PHP Data Types:
Variables are containers which can store data of different types. PHP supports the following data
types:
1. Integer
2. Float (floating point numbers - also called double)
3. Boolean
4. Array
5. String
6. Object
7. NULL
8. Resource
PHP Integer: An integer data type is a non-decimal number. An integer must have at least one
digit, must not have a decimal point. It can be either positive or negative. Range of integer between -
2,147,483,648 and 2,147,483,647
Ex: $x = 5985;
PHP Float: A float is a number with a decimal point or a number in exponential form.
Ex: $x = 59.85;
PHP Boolean: A Boolean represents two possible states: TRUE or FALSE. Booleans are often
used in conditional testing.
Ex: $x = true;
$y = false;
PHP Array: An array stores multiple values in one single variable in continuous memory locations.
Ex: $cars = array("Volvo","BMW","Toyota");
$x=array(12,34,56,67);
echo $x[2]
PHP String: A string is a sequence of characters inside quotes. You can use single or double quotes:
Ex: $x = "Giribabu";
$y = 'Giribabu';
PHP Object: An object is a data type which stores data and information on how to process that data. In
PHP, an object must be explicitly declared. First we must declare a class of object. For this, we use the
class keyword. A class is a structure that can contain properties and methods:
<?php
class Car
{
function Car()
{
$this->model = "VOLVO";
}
Page | 40
}
$vehicle = new Car(); // create an object
echo $vehicle->model; // show object properties
?>
PHP NULL Value: Null is a special data type value. That has no value assigned to it.
Ex: $x = null;
Note: If a variable is created without a value, it is automatically assigned a value of NULL.
PHP Constants: Constants are like variables except that once they are defined its values cannot be
changed or undefined during the script. A valid constant name starts with a letter or underscore , no $
sign before the constant name.
Note: Unlike variables, constants are automatically global across the entire script.
Create a PHP Constant: To create a constant, use the define () function.
Syntax: define (name, value, case-insensitive)
Parameters:
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
The example below creates a constant with a case-sensitive name:
<?php
define("car", "VOLVO");
echo car;
?>
The example below creates a constant with a case-insensitive name:
<?php
define("car", "VOLVO", true);
echo car;
?>
PHP Operators: Operators are used to perform operations on operands (variables) and values.
1. Arithmetic Operators:
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 (Introduced
in PHP 5.6)
2. Assignment Operators:
Page | 41
The PHP assignment operators are used with numeric values to write a value to a variable.
Operator Name Example Description
= Equlas x=y left operand gets set to the value of the on the right
Expression
+= SumEquals x=x+y “
-= SubEquals x=x-y “
*= MultiplyEquals x=x*y “
/= DivideEquals x=x/y “
%= ModdivideEquals x = x % y “
Page | 46
The PHP foreach Loop:
The foreach loop works only on arrays, and is used to loop through each key/value pair in an
array.
Syntax: foreach ($array as $value) {
code to be executed;
Page | 47
}
For every loop iteration, the value of the current array element is assigned to $value and the array
pointer is moved by one, until it reaches the last array element.
Ex: <?php
$colors = array("red", "green", "blue", "yellow");
foreach ($colors as $value) {
echo "$value <br>";
}
?>
PHP Functions:
A function is a basic building block of statements that can be used repeatedly in a program to
improve re-usability. A function will be executed by a call to the function. Function contains set of
instructions enclosed by “{ }” which performs specific operation.
User Defined Functions: Besides the built-in PHP functions, we can create our own functions.
Declaration of a function:
A user-defined function declaration starts with the word function then it contains a name.
Syntax: function functionName() {
code to be executed;
}
Calling a function: This calls the user defined function definition.
Syntax: functionname();
Ex: <?php
function disply() //fuction definition
{
echo "hello Giribabu”;
}
disply(); // call the function
?>
PHP Function Arguments:
Information can be passed from calling function to called function through arguments. An
argument is just like a variable.
Arguments are specified after the function name, inside the parentheses. You can add as many
arguments as you want, just separate them with a comma.
The following example has a function with one argument ($fname). When the disply() function is
called, we also pass along a name, and the name is used inside the function, which output wish the name.
<?php
function disply ($name)
<?php
function disply ($name,$year)
{
echo "hello:$name this year is : $year";
}
disply("Giribabu","2018");
?>
PHP Default Argument Value:
If we call the function without arguments it takes the default value as argument:
<?php
function disply ($name,$year=2015)
{
echo "hello:$name this year is : $year";
}
disply("Giribabu","2018");
disply("Giribabu");
?>
Functions returning values:
A function returns a value from called fuction to calling function after execution of that by using
the return statement:
<?php
function sum($x, $y)
{
$z = $x + $y;
return $z;
}
echo "5 + 10 = " . sum(5, 10) . "<br>";
echo "7 + 13 = " . sum(7, 13) . "<br>";
echo "2 + 4 = " . sum(2, 4);
?>
PHP 5 Arrays:
An array is a special variable, which can hold more than one value at a time. An array can hold
many values under a single name, and you can access the values by referring to an index number.
In PHP, there are three types of arrays:
Indexed arrays - Arrays with a numeric index
Associative arrays - Arrays with named keys
Checkdate(): This function checks the validity of the date formed by the arguments.
The year is between 1 and 32767 inclusive. The month is between 1 and 12 inclusive. The day is
within the allowed number of days for the given month.
<?php
var_dump(checkdate(12, 1, 1990));
print "\n" ;
var_dump(checkdate(23, 29, 2011));
?>
[seconds] − seconds
[minutes] − minutes
[hours] − hours
[mday] − day of the month
[wday] − day of the week
[year] − year
[yday] − day of the year
[weekday] − name of the weekday
[month] − name of the month
<?php
$today = getdate();
print_r($today);
?>
I. INTRODUCTION TO FORMS:
Dynamic websites provide the functionalities that can use to store, update, retrieve, and delete
the data in a database while creating these websites we use forms. A form is a document that containing
black fields, that can be filled by the user with data or select the data. Casually the data will store in the
data base
II. HOW TO CREATE A INTERACTIVE FORM IN PHP?
The HTML <form> element defines a form that is used to collect user input. Form elements are
different types of input elements, like text fields, checkboxes, radio buttons, submit buttons, and more.
The <input> Element:
The <input> element is the most important form element.
The <input> element can be displayed in several ways, depending on the type attribute.
Here are some examples:-
<input type="text"> : Defines a one-line text input field. The default width of a text field
is 20 characters.
<input type="radio"> : Defines a radio button (for selecting one of many choices)
<input type="submit">: Defines a submit button (for submitting the form)
III. WHAT ARE ATTRIBUTES FOR FORM TAG?
The Name Attribute:
Each input field must have a name attribute to be submitted. If the name attribute is omitted, the
data of that input field will not be sent at all.
Example form:
<form>
<input type="text" name="firstname"><br>
<input type="radio" name="gender" value="male" checked> Male<br>
<input type="radio" name="gender" value="female"> Female<br>
<input type="submit" value="Submit">
</form>
The Action Attribute:
The action attribute of the <form> element defines the action to be performed when the form is
submitted. Normally, the form data is sent to a web page on the server when the user clicks on the
submit button.
Input.Php:
<html>
<head>
<title> Reading input from the form </title>
</head>
<body>
<?php
print "Welcome <b>$_POST[user]</b><p>\n\n";
print "Your address is:<p>\n\n<b>$_POST[address]</b><p>\n\n";
print "Your product choices are:<p>\n\n";
print "</ul>";
foreach ($_POST[products] as $value)
{
print "<li>$value\n";
}
print "</ul>";
?>
</body>
</html>
Although the looping technique is particularly useful with the SELECT element, it also works
with enables a user to choose many values within a single field name. As long as the name you choose
ends with empty square brackets, PHP compiles the user input for this field into an array.
Select Product:
<input type="checkbox" name="products[]" value="AC">AC<br>
<input type="checkbox" name="products[]" value="Washing Mechine"> Washing Mechine <br>
<input type="checkbox" name="products[]" value="TV"> TV <br>
<input type="checkbox" name="products[]" value="Refregirator"> Refregirator"<br>
Runtime Configuration:
The behaviour of the mail functions is affected by settings in php.ini.
Name Default Description Changeable
mail.add_x_header "0" Add X-PHP-Originating-Script that will PHP_INI_PERDIR
include UID of the script followed by the
filename. For PHP 5.3.0 and above
mail.log NULL The path to a log file that will log all mail() PHP_INI_PERDIR
calls. Log include full path of script, line
number, To address and headers. For PHP
5.3.0 and above
SMTP "localhost" Windows only: The DNS name or IP address PHP_INI_ALL
of the SMTP server
smtp_port "25" Windows only: The SMTP port number. For PHP_INI_ALL
PHP 4.3.0 and above
sendmail_from NULL Windows only: Specifies the "from" address PHP_INI_ALL
to be used when sending mail from mail()
sendmail_path "/usr/sbin/se Specifies where the sendmail program can be PHP_INI_SYSTEM
ndmail -t -i" found. This directive works also under
Windows. If set, SMTP, smtp_port and
sendmail_from are ignored
Ex: Send an email with extra headers.
<?php
$to = "[email protected]";
$subject = "My subject";
$txt = "Hello world!";
$headers = "From: [email protected]" . "\r\n" ."CC: [email protected]";
fileupload.php
<?php
if(isset($_FILES['image']))
{
$errors= array();
$file_name = $_FILES['image']['name'];
$file_size =$_FILES['image']['size'];
$file_tmp =$_FILES['image']['tmp_name'];
$file_type=$_FILES['image']['type'];
if(is_uploaded_file($_FILES['image']['tmp_name']))
{
$fname=$_Files['image']['name'];
if(move_uploaded_file($_Files['image']['tmp_name'],"uploads/$fname"))
Web Technologies Prepared By: Giribabu
echo "file is moved";
else
echno "not moved fie";
} Page | 65
Example:
Below example should allow upload images and gives back result as uploaded file information.
<?php
if(isset($_FILES['image']))
{
$errors= array();
$file_name = $_FILES['image']['name'];
$file_size = $_FILES['image']['size'];
$file_tmp = $_FILES['image']['tmp_name'];
$file_type = $_FILES['image']['type'];
$file_ext=strtolower(end(explode('.',$_FILES['image']['name'])));
$expensions= array("jpeg","jpg","png"); if(in_array($file_ext,
$expensions)=== false)
{
$errors[]="extension not allowed, please choose a JPEG or PNG file.";
}
if($file_size > 2097152)
{
$errors[]='File size must be excately 2 MB';
}
if(empty($errors)==true)
{
move_uploaded_file($file_tmp,"images/".$file_name);
echo "Success";
}
else
{
print_r($errors);
}
}?
>
<html>
Web Technologies Prepared By: Giribabu
<body>
<form action = "" method = "POST" enctype = "multipart/form-data">
<input type = "file" name = "image" />
<input type = "submit"/> Page | 66
<ul>
<li>Sent file: <?php echo $_FILES['image']['name']; ?>
<li>File size: <?php echo $_FILES['image']['size']; ?>
<li>File type: <?php echo $_FILES['image']['type'] ?>
</ul>
</form>
</body>
</html>
Page | 68
<body>
<?php
echo $_COOKIE["name"]. "<br />";
/* is equivalent to */ Page | 69
echo $HTTP_COOKIE_VARS["name"]. "<br />";
echo $_COOKIE["age"] . "<br />";
/* is equivalent to */
echo $HTTP_COOKIE_VARS["age"] . "<br />";
?>
</body>
</html>
Note: You can use isset() function to check if a cookie is set or not.
<html>
<head>
<title>Accessing Cookies with PHP</title>
</head>
<body>
<?php
if( isset($_COOKIE["name"]))
echo "Welcome " . $_COOKIE["name"] . "<br />";
else
echo "Sorry... Not recognized" . "<br />";
?>
</body>
</html>
Deleting Cookie with PHP
Officially, to delete a cookie you should call setcookie() with the name argument only but this
does not always work well, however, and should not be relied on.
It is safest to set the cookie with a date that has already expired −
Delete a Cookie
To delete a cookie, use the setcookie() function with an expiration date in the past:
Example
<?php
// set the expiration date to one hour ago
setcookie("name", "", time() - 3600);
Web Technologies
</body>
</html>
Web Technologies
A PHP session can be destroyed by session_destroy() function. This function does not need any
argument and a single call can destroy all the session variables. If you want to destroy a single session
variable then you can use unset() function to unset a session variable.
Ex: Here is the example to unset a single variable − Page | 72
<?php
unset($_SESSION["favcolor"]
?>
Ex: Here is the call which will destroy all the session variables −
<?php
session_destroy();
?>
Ex:- The following example starts a session then register a variable called counter that is incremented
each time the page is visited during the session.
<?php
session_start();
if( isset( $_SESSION['counter'] ) )
{
$_SESSION['counter'] += 1;
}
else
{
$_SESSION['counter'] = 1;
}
$msg = "You have visited this page ". $_SESSION['counter'];
$msg .= "in this session.";
?>
<html>
<head>
<title>Setting up a PHP session</title>
</head>
<body> <?
php
echo ( $msg );
?>
</body>
</html>
Web Technologies
Unit V
SYLLABUS: Files and directories: create and delete files, opening file for writing, reading
or appending. Writing or appending to file. Working with directories, Building a text editor, File
Uploading & Downloading. Page | 73
MySQL and PHP: interacting with MySQL using PHP, Performing basic database
operations, (DML) (Insert, Delete, Update, Select), Setting query parameter, Working with Data.
MySQL
What is a Database?
A database is a separate application that stores a collection of data. Each database has one or
more distinct APIs for creating, accessing, managing, searching and replicating the data it holds.
Other kinds of data stores can also be used, such as files on the file system or large hash tables
in memory but data fetching and writing would not be so fast and easy with those type of systems.
Nowadays, we use relational database management systems to store and manage huge volume
of data. This is called relational database because all the data is stored into different tables and
relations are established using primary keys or other keys known as Foreign Keys.
MySQL Database:
MySQL is a fast, easy-to-use RDBMS being used for many small and big businesses. MySQL
is developed, marketed and supported by MySQL AB, which is a Swedish company. MySQL is
becoming so popular because of many good reasons −
MySQL is released under an open-source license. So you have nothing to pay to use it.
MySQL works on many operating systems and with many languages including PHP, PERL, C,
C++, JAVA, etc.
MySQL works very quickly and works well even with large data sets.
Page | 74
MySQL supports large databases, up to 50 million rows or more in a table. The default file size
limit for a table is 4GB, but you can increase this (if your operating system can handle it) to a
theoretical limit of 8 million terabytes (TB).
MySQL is customizable. The open-source GPL license allows programmers to modify the
MySQL software to fit their own specific environments.
MySQL - PHP
Interacting with MySQL using PHP:
MySQL works very well in combination of various programming languages like PERL, C,
C++, JAVA and PHP. Out of these languages, PHP is the most popular one because of its web
application development capabilities.
PHP provides various functions to access the MySQL database and to manipulate the data
records inside the MySQL database. You would require to call the PHP functions in the same way
you call any other PHP function.
MySQL DataTypes:
A data type defines what kind of value a column can hold: integer data, character data, date and
time data, binary strings, and so on. Each column in a database table is required to have a name and a
data type. An MySQL developer must decide what type of data that will be stored inside each column
when creating a table.
Note: Data types might have different names in different database. And even if the name is the same,
the size and other details may be different.
In MySQL there are three main data types: text, number, and date.
1. Text data types:
Data type Description
CHAR(size) Holds a fixed length string (can contain letters, numbers, and special
characters). The fixed size is specified in parenthesis. Can store up to 255 Page | 75
characters
VARCHAR(size) Same as CHAR data type but difference is it Holds a variable length string.
Note: If you put a greater value than 255 it will be converted to a TEXT
type
TEXT Holds a string with a maximum length of 65,535 characters
BLOB For BLOBs (Binary Large OBjects). Holds up to 65,535 bytes of data
MEDIUMTEXT Holds a string with a maximum length of 16,777,215 characters
MEDIUMBLOB For BLOBs (Binary Large OBjects). Holds up to 16,777,215 bytes of data
LONGTEXT Holds a string with a maximum length of 4,294,967,295 characters
LONGBLOB For BLOBs (Binary Large OBjects). Holds up to 4,294,967,295 bytes of
data
ENUM(x,y,z,etc.) Let you enter a list of possible values. You can list up to 65535 values in an
ENUM list. If a value is inserted that is not in the list, a blank value will be
inserted.
Note: The values are sorted in the order you enter them.
You enter the possible values in this format: ENUM('X','Y','Z')
SET Similar to ENUM except that SET may contain up to 64 list items and can
store more than one choice
DOUBLE(size,d) A large number with a floating decimal point. The maximum number of digits
may be specified in the size parameter. The maximum number of digits to the
right of the decimal point is specified in the d parameter
DECIMAL(size,d) A DOUBLE stored as a string , allowing for a fixed decimal point. The
maximum number of digits may be specified in the size parameter. The
maximum number of digits to the right of the decimal point is specified in the
d parameter
*The integer types have an extra option called UNSIGNED. Normally, the integer goes from an
negative to positive value. Adding the UNSIGNED attribute will move that range up so it starts at zero
instead of a negative number.
*Even if DATETIME and TIMESTAMP return the same format, they work very differently. In an
INSERT or UPDATE query, the TIMESTAMP automatically set itself to the current date and time.
TIMESTAMP also accepts various formats, like YYYYMMDDHHMISS, YYMMDDHHMISS,
YYYYMMDD, or YYMMDD.
Constraints on Columns:
After the data type, you can specify other optional attributes for each column:
NOT NULL : Each row must contain a value for that column, null values are not allowed
DEFAULT value: Set a default value that is added when no other value is passed Page | 77
UNSIGNED : Used for number types, limits the stored data to positive numbers and zero
AUTO INCREMENT : MySQL automatically increases the value of the field by 1 each
time a new record is added
PRIMARY KEY : Used to uniquely identify the rows in a table. The column with primary
key setting is often an ID number, and is often used with AUTO_INCREMENT.
PHP Connect to MySQL:
PHP work with a MySQL database using either:
MySQLi extension (the "i" stands for improved)
PDO (PHP Data Objects)
PDO will work on 12 different database systems, whereas MySQLi will only work with
MySQL databases.
when using MySQLi extension there are two ways to conncect with MySQL database.
1. MySQLi (object-oriented)
2. MySQLi (procedural)
Before we can access data in the MySQL database, we need to be able to connect to the server:
<?php
$servername = "localhost";
Page | 78
$username = "username";
$password = "password";
// Create connection
$conn = mysqli_connect($servername, $username, $password);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully";
?>
PHP Create a MySQL Database Using MySQLi object oriented.
A database consists of one or more tables.nThe CREATE DATABASE statement is used to
create a database in MySQL.
Ex: create a database named "myDB":
<?php
$servername = "localhost";
$username = "username";
$password = "password";
// Create connection
$conn = new mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error)
{
die("Connection failed: " . $conn->connect_error);
}
// Create database
$sql = "CREATE DATABASE myDB";
$res= conn->query($sql);
if ($res)
{
echo "Database created successfully";
}
else
{
echo "Error creating database: " . $conn->error;
} Page | 79
$conn->close();
?>
PHP Create a MySQL Table Using MySQLi object oriented:
A database table has its own unique name and consists of columns and rows. The CREATE
TABLE statement is used to create a table in MySQL.
Ex: create a table named "Students", with five columns: "id", "firstname", "lastname",
"email" and "contactno":
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error)
{
die("Connection failed: " . $conn->connect_error);
}
// sql to create table
$sql = "CREATE TABLE students (id INT(6),firstname VARCHAR(30),
lastname VARCHAR(30),email VARCHAR(50),contactno int(10))";
$res=$conn->query($sql);
if ($res)
{
echo "Table Student is created successfully";
}
else
{
echo "Error creating table: " . $conn->error;
}
$conn->close();
?>
Insert Data Into MySQL Using MySQLi object oriented: Page | 80
After a database and a table have been created, we can start adding data in them.
Here are some syntax rules to follow:
The SQL query must be quoted in PHP
String values inside the SQL query must be quoted
Numeric values must not be quoted
The word NULL must not be quoted
Syntax:
INSERT INTO table_name (column1, column2,...) VALUES (value1, value2,...);
insert.php:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error)
{
die("Connection failed: " . $conn-
>connect_error); }
$sql = "INSERT INTO MyGuests (firstname, lastname, email,contactno)VALUES
('giri', 'babu', '[email protected]',1234567890)";
$res=$conn->query($sql);
if ($res)
{
echo "New record created successfully";
}
else
{
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
Select Data From a MySQL Database Using MySQLi object oriented: Page | 81
The SELECT statement is used to select data from one or more tables. There are two ways to
select data from a table.
1. Selecting Selected columns from a table.
Syntax: SELECT column_name(s) FROM table_name.
Ex: Select firstname,lastname from students.
2. we can use the * character to select ALL columns from a table:
Syntax: SELECT * FROM table_name.
Ex: Select * from students;
Select.php:
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error)
{
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT id, firstname, lastname FROM students";
$result = $conn->query($sql);
if ($result->num_rows > 0)
{
// output data of each row
while($row = $result->fetch_assoc())
{
echo "id: " . $row["firstname"]. " - Name: " . $row["lastname"]." ". $row["email"]."<br>";
}
}
else
{
echo "0
results"; }
$conn->close(); Page | 82
?>
In the above program, First, we set up an SQL query that selects the firstname,lastname and
email columns from "students" table. The next line of code runs the query and puts the resulting data
into a variable called "$result".
Then, the function num_rows() checks if there are more than zero rows returned. If there are
more than zero rows returned, the function fetch_assoc() puts all the results into an associative array
that we can loop through. The while() loop loops through the result set and outputs the data from the
firstname, last name and email columns.
Note: The WHERE clause specifies which record or records that should be deleted. If you omit the
WHERE clause, all records will be deleted!
Delete.php:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error)
{
die("Connection failed: " . $conn->connect_error);
}
// sql to delete a record
$sql = "DELETE FROM students WHERE contactno=12345";
$res=$conn->query($sql);
if ($res)
{ Page | 83
What is a directory?
A directory is a file that acts as a folder for other files. A directory can also contain other
directories (subdirectories); a directory that contains another directory is called the parent directory of
the directory it contains.
A directory tree includes a directory and all of its files, including the contents of all
subdirectories. (Each directory is a "branch" in the "tree.") A slash character alone (`/') is the name of
the root directory at the base of the directory tree hierarchy; it is the trunk from which all other files or
directories branch.
Handling files: File handling is the concept of reading the file contents as well as writing the
contents. PHP providing no of functions to read and write the file contents. If we want to read and
write contents of file, first we need to open the file with the specified file mode.
Mode specifies the access type of the file or stream. It can have the following possible values:
“r”(Read) : It represents Read only. It reads the file contents. It starts at the
beginning of the file.
“w”(Write) : It represents Write only. It opens and clears the contents of file or
create a new file if it doesn‟t exist.
“w+”(Write/Read) : It is same as Write mode, we can also read the file contents. It
opens and clears the contents of file or creates a new file if it
doesn‟t exist.
“a”(append) : It represents Write only. It opens and writes the new text at end
of the file or creates a new file if it doesn‟t exist.
$handle = fopen($my_file, 'w') or die('Cannot open file: '.$my_file); //implicitly creates file
$my_file = 'file.txt';
$data = fread($handle,filesize($my_file));
Write to a File: fwrite() is a method used to write new data into a file.
$my_file = 'file.txt';
fwrite($handle, $data);
Append to a File: append is a method used to add new data at end of an existing file.
$my_file = 'file.txt';
fwrite($handle, $data);
fwrite($handle, $new_data);
$my_file = 'file.txt';
fclose($handle);
unlink($my_file);