PHP and MySql Unit-1
PHP and MySql Unit-1
PHP and MySql Unit-1
org
UNIT-I
Building blocks of PHP: Variables, Data Types, Operators and Expressions, Constants.
Flow Control Functions in PHP: Switching Flow, Loops, Code Blocks and Browser Output.
Working with Functions: Defining Functions, Calling functions, returning the values from User-
Defined Functions, Variable Scope, Saving State between Function calls with the Static statement,
more about arguments.
----------------------------------------------------------------------------------------------------------------------------------
Introduction to PHP:
What is PHP?
• PHP is an acronym for "PHP: Hypertext Preprocessor"
• PHP is a widely-used, open source scripting language
• PHP scripts are executed on the server
• PHP is free to download and use
Why PHP?
• PHP runs on various platforms (Windows, Linux, Unix, Mac OS X, etc.)
• PHP is compatible with almost all servers used today (Apache, IIS, etc.)
• PHP supports a wide range of databases
• PHP is free. Download it from the official PHP resource: www.php.net
• PHP is easy to learn and runs efficiently on the server side
A PHP script is executed on the server, and the plain HTML result is sent back to the browser.
<?php
// PHP code goes here
?>
<!DOCTYPE html>
<html>
<body>
<?php
echo "Hello World!";
?>
</body>
</html>
A variable is a special container that you can define, which then “holds” a value, such as a number,
string, object, array, or a Boolean. Variables are fundamental to programming. without variables,
you would be forced to hard-code each specific value used in your scripts.
In PHP, a variable starts with the $ sign, followed by the name of the variable
<?php
$txt = "Hello world!";
$x = 5;
$y = 10.5;
?>
After the execution of the statements above, the variable $txt will hold the value Hello world!, the
variable $x will hold the value 5, and the variable $y will hold the value 10.5.
Note: When you assign a text value to a variable, put quotes around the value.
Note: Unlike other programming languages, PHP has no command for declaring a variable. It is
created the moment you first assign a value to it.
Example-1:
<?php
$txt = "W3Schools.com";
echo "I love $txt!";
?>
The following example will produce the same output as the example above:
Example-2:
<?php
$txt = "W3Schools.com";
echo "I love " . $txt . "!";
?>
Example-3:
The following example will output the sum of two variables:
<?php
$x = 5;
$y = 4;
echo $x + $y;
?>
<?php
$x = 5; // global scope
function myTest() {
// using x inside this function will generate an error
echo "<p>Variable x inside function is: $x</p>";
}
myTest();
A variable declared within a function has a LOCAL SCOPE and can only be accessed within that
function:
<?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>";
?>
You can have local variables with the same name in different functions, because local variables are
only recognized by the function in which they are declared.
PHP also stores all global variables in an array called $GLOBALS[index]. The index holds the name of
the variable. This array is also accessible from within functions and can be used to update global
variables directly. The example above can be rewritten like this:
<?php
$x = 5;
$y = 10;
function myTest() {
$GLOBALS['y'] = $GLOBALS['x'] + $GLOBALS['y'];
}
myTest();
echo $y; // outputs 15
?>
<?php
function myTest() {
static $x = 0;
echo $x;
$x++;
}
myTest();
myTest();
myTest();
?>
Then, each time the function is called, that variable will still have the information it contained from
the last time the function was called.
Note: The variable is still local to the function.
-----------------------------------------------------
2. PHP Data Types
Variables can store data of different types, and different data types can do different things.
PHP supports the following data types:
• String
• Integer
• Float (floating point numbers - also called double)
• Boolean
• Array
• Object
• NULL
• Resource
PHP 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:
<?php
$x = "Hello world!";
$y = 'Hello world!';
echo $x;
echo "<br>";
echo $y;
?>
PHP Integer
An integer data type is a non-decimal number between -2,147,483,648 and 2,147,483,647.
Rules for integers:
• 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)
PHP Float
A float (floating point number) is a number with a decimal point or a number in exponential form.
Booleans are often used in conditional testing. You will learn more about conditional testing in a
later chapter of this tutorial.
PHP Array
An array stores multiple values in one single variable.
In the following example $cars is an array. The PHP var_dump() function returns the data type and
value:
<?php
$cars = array("Volvo","BMW","Toyota");
var_dump($cars);
?>
OUTPUT:
array(3) { [0]=> string(5) "Volvo" [1]=> string(3) "BMW" [2]=> string(6) "Toyota" }
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 = "VW";
}
}
// create an object
$herbie = new Car();
<?php
$x = "Hello world!";
$x = null;
var_dump($x);
?>
PHP Resource
The special resource type is not an actual data type. It is the storing of a reference to functions and
resources external to PHP.
A common example of using the resource data type is a database call.
---------------------------------------------------------------------------------
3. PHP Operators and Expressions
• String operators
• Array operators
PHP has two operators that are specially designed for strings.
key/value pairs
same types
----------------------------------------------------------------------
4. PHP Constants.
Constants are like variables except that once they are defined they cannot be changed or
undefined.
A constant is an identifier (name) for a simple value. The value cannot be changed 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)
Where
• 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
è Constants are case sensitive in PHP
Constants are Global
Constants are automatically global and can be used across the entire script.
The example below uses a constant inside a function, even if it is defined outside the function:
<?php
define("GREETING", "Welcome to W3Schools.com!");
function myTest() {
echo GREETING;
}
myTest();
?>
Predefined Constants
PHP automatically provides some built-in constants for you. For example, the constant __FILE__
returns the name of the file that the PHP engine is currently reading. The constant __LINE__ returns
the current line number of the file. These are but two examples of what are called “magic
constants,” because they are not statically predefined and instead change depending on the
context in which they are used.
Chapter-I Questions
Very often when you write code, you want to perform different actions for different conditions. You
can use conditional statements in your code to do this.
• if...else statement - executes some code if a condition is true and another code if that
condition is false
• if...elseif....else statement - executes different codes for more than two conditions
Syntax
if (condition) {
code to be executed if condition is true;
}
The example below will output "Have a good day!" if the current time (HOUR) is less than 20:
<!DOCTYPE html>
<html>
<body>
<?php
$t = date("H");
The if....else statement executes some code if a condition is true and another code if that condition
is false.
Syntax
if (condition) {
} else {
The example below will output "Have a good day!" if the current time is less than 20, and "Have a
good night!" otherwise:
<?php
$t = date("H");
if ($t < "20") {
echo "Have a good day!";
} else {
echo "Have a good night!";
}
?>
The if....elseif...else statement executes different codes for more than two conditions.
Syntax
if (condition) {
Code to be executed if this condition is true;
} elseif (condition) {
Code to be executed if this condition is true;
} else {
Code to be executed if all conditions are false;
}
The example below will output "Have a good morning!" if the current time is less than 10, and
"Have a good day!" if the current time is less than 20. Otherwise it will output "Have a good night!":
<!DOCTYPE html>
<html>
<body>
<?php
$t = date("H");
echo "<p>The hour (of the server) is " . $t;
echo ", and will give the following message:</p>";
if ($t < "10") {
echo "Have a good morning!";
} elseif ($t < "20") {
echo "Have a good day!";
} else {
echo "Have a good night!";
}
?>
</body>
</html>
The switch statement is used to perform different actions based on different conditions. Use the
switch statement to select one of many blocks of code to be executed.
Syntax
switch (n) {
case label1:
code to be executed if n=label1;
break;
case label2:
code to be executed if n=label2;
break;
case label3:
code to be executed if n=label3;
break;
...
default:
code to be executed if n is different from all labels;
}
This is how it works: First we have a single expression n (most often a variable), that is evaluated
once. The value of the expression is then compared with the values for each case in the structure. If
there is a match, the block of code associated with that case is executed. Use break to prevent the
code from running into the next case automatically. The default statement is used if no match is
found.
<!DOCTYPE html>
<html>
<body>
<?php
$favcolor = "red";
switch ($favcolor) {
case "red":
echo "Your favorite color is red!";
break;
case "blue":
echo "Your favorite color is blue!";
break;
case "green":
echo "Your favorite color is green!";
break;
default:
echo "Your favorite color is neither red, blue, nor green!";
}
?>
</body>
</html>
Using the ?: Operator
The ?: or ternary operator is similar to the if statement, except that it returns a value derived from
one of two expressions separated by a colon. This construct provides you with three parts of the
whole, hence the name ternary. The expression used to generate the returned value depends on
the result of a test expression:
If the test expression evaluates to true, the result of the second expression is returned; otherwise,
the value of the third expression is returned.
Example:
<?php
$mood = “sad”;
$text = ($mood == “happy”) ? “I am in a good mood!” : “I am in a $mood mood.”;
echo “$text”;
?>
Often when you write code, you want the same block of code to run over and over again in a row.
Instead of adding several almost equal code-lines in a script, we can use loops to perform a task like
this.
In PHP, we have the following looping statements:
• while - loops through a block of code as long as the specified condition is true
• do...while - loops through a block of code once, and then repeats the loop as long as the
specified condition is true
• for - loops through a block of code a specified number of times
• foreach - loops through a block of code for each element in an array
The while loop executes a block of code as long as the specified condition is true.
Syntax
code to be executed;
The example below first sets a variable $x to 1 ($x = 1). Then, the while loop will continue to run as
long as $x is less than, or equal to 5 ($x <= 5). $x will increase by 1 each time the loop runs ($x++):
<?php
$x = 1;
while($x <= 5) {
$x++;
?>
The do...while loop will always execute the block of code once, it will then check the condition, and
repeat the loop while the specified condition is true.
Syntax
do {
code to be executed;
The example below first sets a variable $x to 1 ($x = 1). Then, the do while loop will write some
output, and then increment the variable $x with 1. Then the condition is checked (is $x less than, or
equal to 5?), and the loop will continue to run as long as $x is less than, or equal to 5:
<?php
$x = 1;
do {
echo "The number is: $x <br>";
$x++;
} while ($x <= 5);
?>
Notice that in a do while loop the condition is tested AFTER executing the statements within the
loop. This means that the do while loop would execute its statements at least once, even if the
condition is false the first time.
The example below sets the $x variable to 6, then it runs the loop, and then the condition is
checked:
<?php
$x = 6;
do {
echo "The number is: $x <br>";
$x++;
} while ($x <= 5);
?>
PHP for loops execute a block of code a specified number of times. The for loop is used when you
know in advance how many times the script should run.
Syntax
code to be executed;
Parameters:
• init counter: Initialize the loop counter value
• test counter: Evaluated for each loop iteration. If it evaluates to TRUE, the loop continues. If it
evaluates to FALSE, the loop ends.
• increment counter: Increases the loop counter value
The example below displays the numbers from 0 to 10:
<?php
for ($x = 0; $x <= 10; $x++) {
echo "The number is: $x <br>";
}
?>
Syntax
foreach ($array as $value) {
code to be executed;
}
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.
The following example demonstrates a loop that will output the values of the given array
($colors):
<?php
$colors = array("red", "green", "blue", "yellow");
foreach ($colors as $value) {
echo "$value <br>";
}
?>
<?php
$display_prices = true;
if ($display_prices) {
echo “<table border=\”1\”>\n”;
echo “<tr><td colspan=\”3\”>”;
echo “today’s prices in dollars”;
echo “</td></tr>”;
echo “<tr><td>\$14.00</td><td>\$32.00</td><td>\$71.00</td></tr>\n”;
echo “</table>”;
}
?>
If the value of $display_prices is set to true in line 2, the table is printed. Put these lines into a text
file called testmultiecho.php and place this file in your web server document root.
There’s nothing wrong with the way this is coded, but you can save yourself some typing by simply
slipping back into HTML mode within the code block.
<?php
$display_prices = true;
if ($display_prices) {
?>
<table border=”1”>
<tr><td colspan=”3”>today’s prices in dollars</td></tr>
<tr><td>$14.00</td><td>$32.00</td><td>$71.00</td></tr>
</table>
<?php
}
?>
The important thing to note here is that the shift to HTML mode on line 4 occurs only if the
condition of the if statement is fulfilled. This can save you the bother of escaping quotation marks
and wrapping our output in echo() statements. This approach might, however, affect the readability
of the code in the long run, especially if the script grows larger.
Chapter-II Questions:
Syllabus: Defining Functions, Calling functions, returning the values from User-Defined Functions,
Variable Scope, and Saving State between Function calls with the Static statement, more about
arguments.
……………………………………………………………… @@@ ……………………………………………………………...................
What is function?
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.
1. Defining functions:
Besides the built-in PHP functions, we can create our own functions.
• A function is a block of statements that can be used repeatedly in a program.
• A function will not execute immediately when a page loads.
• A function will be executed by a call to the function.
A user defined function declaration starts with the word "function":
Syntax
function functionName() {
code to be executed;
Note: A function name can start with a letter or underscore (not a number).
Tip: Give the function a name that reflects what the function does!
In the example below, we create a function named "writeMsg()". The opening curly brace ( { )
indicates the beginning of the function code and the closing curly brace ( } ) indicates the end of the
function. The function outputs "Hello world!". To call the function, just write its name:
<?php
function writeMsg() {
echo "Hello world!";
}
writeMsg(); // call the function
?>
2. Calling functions
Functions come in two flavors: those built in to the language and those you define yourself. PHP has
hundreds of built-in functions. Look at the following snippet for an example of a function in use:
strtoupper(“Hello Web!”);
A function call consists of the function name (strtoupper in this case) followed by parentheses. If
you want to pass information to the function, you place it between these parentheses. A piece of
information passed to a function in this way is called an argument. Some functions require that
more than one argument be passed to them, separated by commas:
some_function($an_argument, $another_argument);
<?php
function writeMsg() {
echo "Hello world!";
}
writeMsg(); // call the function
?>
The function writeMsg() is called without any parameters, however you can also pass parameters to
PHP functions and you can also set default values to PHP functions.
Information can be passed to functions 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 familyName()
function is called, we also pass along a name (e.g. Jani), and the name is used inside the function,
which outputs several different first names, but an equal last name:
<!DOCTYPE html>
<html>
<body>
<?php
function familyName($fname) {
echo "$fname Refsnes.<br>";
}
familyName("Jani");
familyName("Hege");
familyName("Stale");
familyName("Kai Jim");
familyName("Borge");
?>
</body>
</html>
A function can return a value using the return statement in conjunction with a value. The return
statement stops the execution of the function and sends the value back to the calling code.
Example:
<!DOCTYPE html>
<html>
<body>
<?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);
?>
</body>
</html>
4. Variable Scope
A variable declared within a function remains local to that function. In other words, it is not
available outside the function or within other functions. In larger projects, this can save you from
accidentally overwriting the contents of a variable when you declare two variables with the same
name in separate functions.
<?php
Function_test()
{
$testvariable = “this is a test variable”;
}
echo “test variable: “.$testvariable.”<br/>”;
?>
Put these lines into a text file called scopetest.php and place this file in your webserver document
root. When you access this script through your web browser, it should look like
Figure: Variable Scope: A Variable Declared Within a Function Is Unavailable Outside the Function.
The value of the variable $testvariable is not printed because no such variable exists outside the
test() function.
From within one function, you cannot (by default) access a variable defined in another function or
elsewhere in the script. Within a function, if you attempt to use a variable with the same name, you
will only set or access a local variable.
<?php
$life = 42;
function meaningOfLife()
{
echo “The meaning of life is “.$life”;
}
meaningOfLife();
?>
Put these lines into a text file called scopetest2.php and place this file in your web server document
root. When you access this script through your web browser, it should look like
Fig: Variables Defined Outside Functions Are Inaccessible from Within a Function by Default.
As you might expect, the meaningOfLife() function does not have access to the $life variable in line
2; $life is empty when the function attempts to print it. On the whole, this is a good thing because it
saves you from potential clashes between identically named variables, and a function can always
demand an argument if it needs information about the outside world. Occasionally, you might want
to access an important variable from within a function without passing it in as an argument. This is
where the global statement comes into play.
<?php
$life = 42;
function meaningOfLife()
{
global $life;
echo “The meaning of life is “.$life”;
}
meaningOfLife();
?>
Put these lines into a text file called scopetest3.php and place this file in your web server document
root. When you access this script through your web browser, it should look like.
• You need to use the global statement within every function that needs to access a particular
named global variable.
• You can declare more than one variable at a time with the global statement by simply
separating each of the variables you want to access with commas:
If you declare a variable within a function in conjunction with the static statement, the variable
remains local to the function, and the function “remembers” the value of the variable from
execution to execution.
<?php
function numberedHeading($txt)
{
static $num_of_calls = 0;
$num_of_calls++;
echo “<h1>”.$num_of_calls.” “. $txt.”</h1>”;
}
numberedHeading(“Widgets”);
echo “<p>We build a fine range of widgets.</p>”;
numberedHeading(“Doodads”);
echo “<p>Finest in the world.</p>”;
?>
Rather than just passing values as arguments to functions, PHP allows you to pass arguments as
default values and by references.
PHP provides a nifty feature to help build flexible functions. Until now, you’ve heard that some
functions require one or more arguments. By making some arguments optional, you can render
your functions a little less autocratic.
<?php
function fontWrap($txt, $fontsize)
{
echo “<span style=\”font-size:$fontsize\”>”.$txt.”</span>”;
}
fontWrap(“A Heading<br/>”,”24pt”);
fontWrap(“some body text<br/>”,”16pt”);
fontWrap(“smaller body text<br/>”,”12pt”);
fontWrap(“even smaller body text<br/>”,”10pt”);
?>
In above program a useful little function that wraps a string in an HTML span element (at line 4).
To give the user of the function the chance to change the font-size style, you can demand a
$fontsize argument in addition to the string( at line 2). The above program generates the following
output.
When you pass arguments to functions, they are stored as copies in parameter variables. Any
changes made to these variables in the body of the function are local to that function and are not
reflected beyond it.
You can change this behavior by creating a reference to your original variable. You can think of a
reference as a signpost that points to a variable. In working with the reference, you are
manipulating the value to which it points. This can be implemented as
<?php
function addFive(&$num)
{
$num += 5;
}
$orignum = 10;
addFive($orignum);
echo $orignum;
?
When you pass an argument to a function by reference, as in line 7, the contents of the variable
you pass ($orignum) are accessed by the argument variable and manipulated within the function,
rather than just a copy of the variable’s value (10). Any changes made to an argument in these
cases change the value of the original variable. You can pass an argument by reference by adding an
ampersand to the argument name in the function definition, as shown in line 2.