PHP Book To Publish - Final - Aa Devanu
PHP Book To Publish - Final - Aa Devanu
WHAT IS JAVASCRIPT
JavaScript is scripting language used for client side scripting.
JavaScript developed by Netscape in 1995.
JavaScript was designed to add interactivity to HTML pages.
JavaScript is a programming language used to make web pages interactive.
A scripting language is a lightweight programming language.
A JavaScript consists of lines of executable computer code.
A JavaScript is usually embedded directly into HTML pages.
JavaScript is an interpreted language (means that scripts execute without preliminary
compilation).
Everyone can use JavaScript without purchasing a license.
JavaScript is case-sensitive.
ADVANTAGES OF JAVASCRIPT
Associative Arrays.
Loosely Typed Variables.
Regular Expressions.
Objects and Classes.
Highly Evolved Date, Math, and String Libraries.
W3c Dom Support in the Javascript.
DISADVANTAGES OF JAVASCRIPT
Developer depends on the browser support for the JavaScript.
There is no way to hide the JavaScript code in case of commercial application.
-----Javascript code------------
</script>
OR
<script type=”text/javascript”>
-----Javascript code------------
</script>
To insert a JavaScript into an HTML page, we use the <script> tag. Inside the <script>
tag we use the "language=" attribute to define the scripting language. So, the <script
language="JavaScript"> and </script> tells where the JavaScript starts and ends:
1. Head Section:
Scripts that contain functions go in the head section of the document. Then we
can be sure that the script is loaded before the function is called.
<html>
<head>
<script language="JavaScript">
.............
.............
</script>
2. Body Section:
Execute a script that is placed in the body section.
<html>
<head>
</head>
<body>
<script language="JavaScript">
.............
.............
</script>
</body></html>
1.2 DATA TYPES AND LITERALS
The predefined identification of any variable is known as Data type. Or we can say
that the data type defines the characteristics of variables.
There are six Data Types in JavaScript, three of them are Primitive or also
known as Primary data type while everything else in JavaScript is Object or
Reference Typed also known as Composite data types.
STRING
String data type is use to represent text in JavaScript. A string is value
with zero or more characters which may include letters, punctuation marks
and digits. There is no separate data type for character (char) in JavaScript.
If you create a string with nothing in it, it is called an empty string. You
may use single or double quote for assigning value to string.
These are some examples of valid string data types in JavaScript:
EXAMPLE
<script language="JavaScript">
var str1 = "Hi, How are you?";
var str2 = "He said: 'Hi'";
var str3 = 'He said:"Hi" ';
var str4 = "25";
var str5 = "";
var str6 = 'C';
</script>
NUMBER
An integer is a base-10 whole number. In other words, it is a number with no
fractional component. JavaScript can handle integer values between 253 and -
253. Some JavaScript functions, however, cannot handle extremely large or
small numbers, so it is probably a good idea to try to keep your numbers in the
range of 231 and -231. Since that is plus or minus 2 trillion, this shouldn't be a
problem as long as you are not trying to track the national debt.
Another commonly used type of number is a floating-point number. A
floating-point number is a number that is assumed to have a decimal point.
The decimal point is the point that floats and gives the data type its name.
Floating-point numbers have a fractional component, even if that fractional
component is zero. They can be represented as a real number (integer -
decimal point - fractional value) such as in 3.1714, or using exponential
notation.
EXAMPLE
var num1 = 23; //integer value
var num2 = 42.25; //float value
var num3 = 22e5; //exponential 2200000
var num4 = 13e-5 //0.00013
BOOLEAN
Boolean data type can only have two values, literals true and false.
Comparison of two variables wills outcome a Boolean value. Boolean are
used for condition testing.
EXAMPLE
<script language="JavaScript">
var num1=54;
var result = (num1 === 2000); //will return false
var result1 = (num1 === 54); //will return true
document.write(result);
</script>
REFERENCE DATA TYPES
OBJECTS
An object is a collection of named values, called the properties of that object.
Functions associated with an object are referred to as the methods of that
object.
Properties and methods of objects are referred to with a dot.notation that starts
with the name of the object and ends with the name of the property. For
instance image.src.
Normally in objects there are only two nodes, the object and the property, but
as we will discover, sometimes the properties can have properties of their
own, creating an object tree which you have to specify the path through in the
same way you would with a directory tree (except you are using periods
instead of slashes).
For instance, document.form1.namefield.
Objects in JavaScript can be treated as associative arrays. This means that
image.src and image['src'] are equivalent. This flexibility has its uses, since
this means that you can pass property names as the values of variables.
For instance, this code snippet: img[iProp] = newImage[iProp];
JavaScript has many predefined objects, such as a Date object and a Math
object. These are used much as function libraries are used in a language like
C. They contain a collection of useful methods that are predefined and ready
for use in any JavaScript code you may write.
ARRAY
Array is collection containing zero or more items. Array items can be access
by using indexing on variable. In JavaScript specifications typeof Array is
object.
EXAMPLE
<script language="JavaScript">
var dataTypes=new Array();
dataTypes[0]="String";
dataTypes[1]="Number";
dataTypes[2]="Boolean";
//condensed array:
dataTypes=new Array("String","Number","Boolean");
//literal array:
dataTypes=["string","number","boolean"];
</script>
FUNCTION
A function is a piece of code, predefined or written by the person creating the
JavaScript that is executed based on a call to it by name.
A function is a data type in JavaScript. This is different from many other
programming languages. This means that they can be treated as containing
values that can be changed.
EXAMPLE
<script language="JavaScript">
var myFunc = function(){
alert("function is triggered");
};
myFunc();
</script>
UNDEFINED
The undefined value is default for a variable which is declared but never
assigned a value.
EXAMPLE
var myVar;
if((typeof var) === "undefined")
{
alert("variable is undefined");
}
1.3 LITERALS
Javascripts can’t support data types. But it supports Literals.
Literals are used to represent values of variables of particular data type in JavaScript.
These are fixed values not variables that you literally provide in your script.
Integer Literals :
var a = 112;
var b = - 44;
var a = 1.23;
var b = -4.9;
Boolean Literals:
Boolean Literals can be expressed as only with two values i.e. TRUE or FALSE.
You can just assign true or false values, it will automatically take 0 as true value and 1 as
false value.
Example :
var a = true;
var b = false;
String Literals:
String Literals can be expressed as a sequence of characters. It always enclose with either
single quote(‘) or double quotes(“).
Example :
Array Literals:
Array Literals can be expressed as a list of values that are called elements of Array.
The values may be numbers, strings or any type of Literal.
Example :
Object Literals:
Object Literals can be expressed as a list of pairs of property names and associated values
of an Object enclosed in { }.
NOTE: It is just a User Defined Object which is shown later on.
NULL Literals:
Null Literal consists of single value, which identifies a NULL i.e. empty.
It is used to set initial value of variable that is different from other valid values.
Example:
JavaScript is a loosely typed language meaning a variable can hold any data type at any
time. The data types are categorized as primitive and Composite, where a Primitive data
type holds single piece of data and a Composite data type holds a collection. The
Primitive data types are generally known to be Numbers, Strings and Booleans, while
Composite types are known to be Objects, Literals, Arrays and Functions.
By default JavaScript attempts to perform all required type conversions at the appropriate
times, but sometimes it is necessary to force cast a variable. A good example of this is
when returning a value from a function, where the return data type is expected in a
certain form.
Conversion Rules
JavaScript will attempt to carry out the specified conversions in the following situations:
Boolean is converted to a Number (1/0) before comparison.
In a Number comparison, if an entry is NaN it will be converted to false.
Also when comparing a Number, if an Object is entered it will attempt to cast it to an
Integer.
If two Objects are compared it is the memory address that is checked for comparison.
The Literals ‘null’ and ‘Undefined’ are judged to be the same entity. They will not cast to
0, “” or false.
If a String and a Number are compared, the String will be cast to an Integer.
If an Object and a String are compared, the Object will be cast to a String.
STRINGS
All Primitive data types in JavaScript are included with a ‘toString()’ method
which can be called manually to convert the data type to a string. When
dealing with floats, JavaScript will not maintain decimal places that are not
required. This method also has an optional radix parameter which can be used
to change the base level of the returned number.
Javascript Variables
var
This indicates you are about to declare a variable.
name
value
This is the initial value you want the variable to have. It can be a number,
words, true, false, or null.
EXAMPLE:
var cars;
var cost;
Assign value to variable
VAR CARS=3;
VAR COST=9.95;
VAR MOVIE="THE LOST WORLD";
VAR STORY=TRUE;
VAR MYMONEY=NULL;
EXAMPLE 1
<HTML>
<HEAD>
<SCRIPT LANGUAGE="JavaScript">
var name=prompt("Enter Your Name:","Name");
</SCRIPT>
</HEAD>
<BODY>
<SCRIPT LANGUAGE="JavaScript">
document.write('<IMG SRC="Chrysanthemum.jpg">');
document.write("<H1>Greetings, " + name + ". Welcome to JavaScript</H1>");
</SCRIPT>
</BODY>
</HTML>
EXAMPLE 2
<HTML>
<HEAD>
<SCRIPT LANGUAGE="JavaScript">
var name=prompt("Enter Your Name:","Name");
alert("Greetings " + name + ".");
name=prompt("Enter Your Friend's Name:","Friend's Name");
</SCRIPT>
</HEAD>
1.6<BODY>
JAVASCRIPT ARRAY
<SCRIPT LANGUAGE="JavaScript">
document.write('<IMG SRC="Chrysanthemum.jpg">');
document.write("<H1>Greetings, " + name + ". Welcome JavaScript</H1>");
</SCRIPT>
</BODY>
</HTML>
Using arrays, you can store multiple values under a single name. Instead of using a
separate variable for each item, you can use one array to hold all of them.
The index number is the location of the data element in the array.
Each stored value so indexed is referred to as an array element.
The order of the elements is fixed
The Array object is used to store a set of values in a single variable name.
We define an Array object with the new keyword.
TYPES OF ARRAY
1. One Dimensional Array
2. Two Dimensional Array
3. Multidimensional Array
SYNTAX
var array-name = new Array( number-of-values)
EXAMPLE
var product_name = new Array(“Nokia”,”LG”,” Samsung”)
OR
Size of array is defined based on array element.
SYNTAX
var array-name = new Array( number-of-elements )
Or
var array-name = new Array( )
EXAMPLE
var product_name = new Array(3)
Product_name[0]=”PHP”;
product_name[1]=”C++”;
product_name[2]=”VB”;
product_name[3]=”JAVASCRIPT”;
Where Array() is constructor and "new" keyword to instantiate the array in memory.
ASSOCIATIVE ARRAY
Associative arrays give you a way to label your array item keys instead of them being
numbered in the way that array elements are usually numerically indexed by default.
The key is directly associated to its value in a meaningful way.
EXAMPLE
var my_cars= new Array()
my_cars["cool"]="pradip";
my_cars["family"]="vsc-project";
my_cars["big"]="rajkot";
for (i in my_cars)
{
document.write(i+"<br>");
}
SYNTAX
EXAMPLE
<html><head>
<script language="javascript">
Subject= new Array (3);
for (i = 0; i < Subject.length; ++ i)
Subject[i] = new Array (3);
EXAMPLE
<script language="javascript">
var myarr=new Array(["HTML","CSS","JAVASCRIPT"],["PHP","ASP.NET","VB.NET","C#.NET"],
"VB","FOXPRO","MSACCESS"]);
document.write(myarr[0]);
document.write("<br>"+myarr[1]);
document.write("<br>"+myarr[2]);
</script>
Arithmetic Operators
Comparison Operators
Logical Operators
Bitwise Operators
Assignment Operators
String Operators
Conditional Operator
ARITHMETIC OPERATORS
Assignment operators are used to assign values to JavaScript variables.
Given that x=10 and y=5, the table below explains the assignment operators:
COMPARISON OPERATORS
Logical operators are used to determine the logic between variables or values.
Given that x=6 and y=3, the table below explains the logical operators:
BITWISE OPERATORS
ASSIGNMENT OPERATORS
= x=y x=5
STRING OPERATORS
The + operator can also be used to concatenate (add) strings.
EXAMPLE
If condition is true, the operator returns the value of expr1; otherwise, it returns the
value of expr2.
EXAMPLE
EXPRESSIONS
o The expression x = 7 is an example of the first type. This expression uses the =
operator to assign the value seven to the variable x. The expression itself evaluates to
seven.
o The code 3 + 4 is an example of the second expression type. This expression uses the
+ operator to add three and four together without assigning the result, seven, to a
variable.
EXAMPLE
var mood = (smile==true) ? happy : sad
TYPEOF OPERATOR
o The typeof operator is used to get the data type (returns a string) of its operand.The
operand can be either a literal or a data structure such as a variable, a function, or an
object. The operator returns the data type.
SYNTAX
typeof operand or typeof (operand)
o There are six possible values that typeof returns: object, boolean, function, number, string,
and undefined. The following table summarizes possible values returned by the typeof
operator.
Type of the operand Result
Object "object"
Boolean "boolean"
Function "function"
Number "number"
String "string"
Undefined "undefined"
EXAMPLE
<script language="JavaScript">
var a;
typeof a; //"undefined"
typeof b; //"undefined"
alert(a); //undefined
alert(b); //ReferenceError
var index = 8;
var result = (typeof index === 'number');
alert(result); // Output: true
var description = "w3resource";
var result = (typeof description === 'string');
alert(result); // Output: true
</script>
VOID
o The void operator is used to evaluate a JavaScript expression without returning a
value.
SYNTAX
void expression
EXAMPLE
<script language="javascript">
function testfunc()
{
alert ("testfunc");
}
</script>
</head>
<body>
<a href="javascript:void(alert('Thank you.'))">Click here to see a message</a>
<a href="javascript:void(testfunc())"> Click here to call testfunc()</a>
</body>
1.8 CONSTRUCTOR
In the world of OOP, the previous ways of defining an object is too limiting in many
situations. We need a way to create an object "type" that can be used multiple times
without having to redefine the object every time to meet each particular instance's
needs. The standard way to achieve this is to use the Object Constructor function.
A constructor is any function which is used as a constructor. The language doesn’t make a
distinction. A function can be written to be used as a constructor or to be called as a normal
function, or to be used either way.
A constructor is used with the new keyword:
o The interpreter creates the new function object from your declaration. Together with
the function, its prototype property is created and populated.
o This default value the prototype is an object with property constructor, which is set to
the function itself. In our case, to Rabbit:
Rabbit.prototype = { constructor: Rabbit }
So, when new Rabbit is called, the Rabbit.prototype becomes __proto__ and
the constructor becomes accessible from the object:
rabbit.__proto__ == { constructor: Rabbit )
EXAMPLE
function Rabbit() { }
var rabbit = new Rabbit()
alert( rabbit.hasOwnProperty('constructor') ) // false
alert( Rabbit.prototype.hasOwnProperty('constructor') ) // true
Conditional statements
A conditional statement uses conditional logic to determine what programming
statements to execute.
By using some conditional logic (a process of checking conditions), we determine if a
certain condition is true or false.
If the condition is true, we execute some part of the program. Otherwise, if the
condition is false, we use some other part of the program.
In JavaScript we have the following conditional statements:
o if statement
o if...else statement
o if...else if....else statement
o switch statement
IF STATEMENT
You should use the if statement if you want to execute some code only if a specified
condition is true.
SYNTAX
if (condition)
{
code to be executed if condition is true
}
EXAMPLE
<script language="JavaScript">
//Write a "Good morning" greeting if
//the time is less than 10
var d=new Date();
var time=d.getHours();
if (time<10)
{
document.write("<b>Good morning</b>");
}
</script>
IF...ELSE STATEMENT
If you want to execute some code if a condition is true and another code if the
condition is not true.
SYNTAX
if (condition)
{
code to be executed if condition is true
}
else
{
code to be executed if condition is not true
}
EXAMPLE
<script language="JavaScript">
//If the time is less than 10,
//you will get a "Good morning" greeting.
//Otherwise you will get a "Good day" greeting.
var d = new Date();
var time = d.getHours();
if (time < 10)
{
document.write("Good morning!");
}
else
{
document.write("Good day!");
}
IF...ELSE IF....ELSE STATEMENT
You should use the if....else if...else statement if you want to select one of many
sets of lines to execute.
SYNTAX
if (condition1)
{ code to be executed if condition1 is true }
else if (condition2)
{ code to be executed if condition2 is true }
else
{ code to be executed if condition1 and
condition2 are not true
}
EXAMPLE
<script language="JavaScript">
var d = new Date();
var time = d.getHours();
if (time<10)
{document.write("<b>Good morning</b>");}
else if (time>10 && time<16)
{document.write("<b>Good day</b>");}
else
{document.write("<b>Hello World!</b>");}
</script>
SWITCH STATEMENT
Conditional statements in JavaScript are used to perform different actions based
on different conditions.
This is how it works:
o First we have a single expression n (most often a variable), that is evaluated
once.
o The value of the expression is then compared with the values for each case in
the structure.
o If there is a match, the block of code associated with that case is executed.
o Use break to prevent the code from running into the next case automatically.
SYNTAX
switch(n)
{
case 1:
execute code block 1
break;
case 2:
EXAMPLE
execute code block 2
<script language="JavaScript">
break;
//You will receive a different greeting based
default:
//on code today
what it is. Noteifthat
be executed n is Sunday=0,
//Monday=1, Tuesday=2,
different from case 1 and 2etc.
var} d=new Date();
var theDay=d.getDay();
switch (theDay)
{ ENDLESS LOOP
case 5:
document.write("Finally Friday");
break;
case 6: FUNCTIONS IN JAVASCRIPT
document.write("Super Saturday");
break;
case 0:
document.write("Sleepy Sunday");
break;
USER DEFINE FUNCTION
default:
document.write("I'm looking forward to this weekend!");
}
</script>
WHILE
The while statement will execute a block of code while a condition is true.
SYNTAX
while (condition)
{
code to be executed
}
EXAMPLE
<html>
<head>
<script language="javascript">
i=0;
DO...WHILE while(i<=5)
The do...while { statement will execute a block of code once, and then it will repeat
the loop whiledocument.write(i+"<br>");
a condition is true.
SYNTAX i++;
}
do
</script>
{
</head><body></body></html>
code to be executed
}
while (condition)
EXAMPLE
<html><body>
<script type="text/javascript">
i=0
do
{
document.write("<b>The number is " + i + "</b>")
document.write("<br>")
i++
}
while (i<=5)
</script>
</body></html>
FOR
The for statement will execute a block of code a specified number of times
SYNTAX
for (initialization; condition; increment)
{ code to be executed }
EXAMPLE
<html>
<body>
<script type="text/javascript">
for (i=0; i<=5; i++)
{
document.write("<b>The number is " + i + "</b>")
document.write("<br>")
}
</script>
</body>
1.11 WHAT IS USER DEFINE FUNCTION?
A function is a reusable code-block that will be executed by an event, or when the
function is called.
Function provides the ability to combine no. of statements in single unit.
JavaScript provides Functions through which you can perform certain task.
JavaScript allows users to create our own Functions, are called “User Defined
Functions”.
User Defined Function first need to be declared after that function can be invoked by
calling it using its name when it was declared.
The data needed to execute a function is passed as a Parameter.
“parameter-list” are optional and passed to the function appears in parentheses and
commas separate member of list.
“return” statement can be used to return any valid expression that Evaluates a single
value.
EXAMPLE
<html> <head>
<script language=”javacript”>
function displayMsg( )
{
alert(“Welcom to Digital City…”);
}
</script> </head>
<body>
<input type=”button” value=”Click Here” onClick=”displayMsg()”>
</body> </html>
Function accepts argument but it does not return a value back to the calling Program.
EXAMPLE
<html> <head>
<script language="javascript">
function simple()
{
alert("Function is Call");
}
</script>
</head>
<body>
<input type="button" value="Click Me!" onclick="simple()">
</body>
</html>
EXAMPLE
function simple(a,b)
{
var c=a+b;
alert(c);
}
</script>
<input type="button" value="Click Me!" onclick="simple(10,20)">
NO ARGUMENT & WITH RETURN VALUE
Function does not accepts argument but it return a value back to the calling Program .
SYNTAX
function fun_name()
{
--- code -----
return variale;
}
fun_name();
EXAMPLE
function simple()
{
var a=10;
var b=20;
var c;
c=a+b;
return c;
}
document.write(simple());
function_name()
EXAMPLE
function simple(a,b)
{
var c;
c=a+b;
return c;
}
document.write(simple(20,20));
1.12 BUILT-IN FUNCTIONS
1. eval()
Syntax:
eval(string-expression)
Example:
<script language=”javascript”>
s = eval(no1) + eval(no2);
document.write(“Sum : ”+s);
</script
2. parseInt()
Syntax:
parseInt(string)
Example:
<script language=”javascript">
document.write(parseInt("15") + "<br />");
document.write(parseInt("15.34") + "<br />");
document.write(parseInt("25 35 45") + "<br />");
document.write(parseInt(" 100 ") + "<br />");
document.write(parseInt("30 years") + "<br />");
document.write(parseInt("Hello") + "<br />");
document.write(parseInt("15",10)+ "<br />");
document.write(parseInt("015")+ "<br />");
document.write(parseInt("15",8)+ "<br />");
document.write(parseInt("0x10")+ "<br />");
document.write(parseInt("10",16)+ "<br />");</script>
Output:
15
15
25
100
30
NaN
15
8
8
16
16
3. parseFloat():
The parseFloat() function parses a string and returns a floating point number.
This function determines if the first character in the specified string is a number.
If it is, it parses the string until it reaches the end of the number, and returns the
number as a number, not as a string.
Syntax:
parseFloat(string);
Example:
<script type="text/javascript">
document.write(parseFloat("15") + "<br />");
document.write(parseFloat("15.46") + "<br />");
document.write(parseFloat("35 45 55") + "<br />");
document.write(parseFloat(" 100 ") + "<br />");
document.write(parseFloat("30 years") + "<br />");
document.write(parseFloat("Hello") + "<br />");
</script>
Output:
15
15.46
35
100
30
NaN
ALERT BOX
An alert box is often used if you want to make sure information comes through to the
user.
When an alert box pops up, the user will have to click "OK" to proceed.
The alert() method is used for this type of use include
o Incorrect information in a form.
o An invalid result from a calculation.
o A warning that a service is not available on a given date.
SYNTAX
alert("sometext");
EXAMPLE
<html>
<head>
<script language="javascript">
function msgbox()
{
alert("This is an Alert Box");
}
</script>
</head><body>
<input type="button" value="alert box" onClick="msgbox()">
</body></html>
Output
CONFIRM BOX
A confirm box is often used if you want the user to verify or accept something.
When a confirm box pops up, the user will have to click either "OK" or "Cancel" to
proceed.
Confirm displays a dialog box with two buttons: OK and Cancel.
If the user clicks "OK", the box returns true. If the user clicks "Cancel", the box
returns false.
SYNTAX
confirm("sometext");
EXAMPLE
<html> <head><script language="javascript">
function msgbox()
{
var ans=confirm("Are You Agree !");
if(ans=="true")
{ alert("You have Press Ok Button"); }
else
{ alert("You have Press Cancle Button"); }
}
</script></head><body> <input type="button" value="confirm box"
onClick="msgbox()"> </body></html>
Output
PROMPT BOX
A prompt box is often used if you want the user to input a value before entering a
page.
When a prompt box pops up, the user will have to click either "OK" or "Cancel" to
proceed after entering an input value.
If the user clicks "OK" the box returns the input value. If the user clicks "Cancel" the
box returns null.
SYNTAX
var variable-name=Prompt(“sometext”,”defaultvalue");
EXAMPLE
<html><body>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction()
1.14 JAVASCRIPT {
OBJECT
var x;
if (confirm("Press
What is Object? a button!") == true) {
x = "You pressed OK!";
} else
“Object” is{ just a special kind of data. Each Object have its state and behavior.
x =the
State of "You pressed
Object Cancel!";
refers as Property.
}
Behavior of the Object refers as Methods.
document.getElementById("demo").innerHTML = x;
}
Properties:
</script></body></html>
Output are used to define the characteristics of an Object.
Properties
Properties are used to access the data values present in the object.
To access the property of an Object:-
o ObjectName.propertyName
Methods:
Built-In Objects :
Javascript provides two types of Built-In Objects.
Native Objects
o String Object
o Math Object
o Array Object
o Date Object
Browser Objects
o Window Object
o History Object
o Location Object
o Screen Object
o Navigator Object
o Document Object
String Object:
Property:
Methods:
o bold:
o italics:
o strike:
o sup:
o sub:
o fontcolor:
o fontsize:
o link:
o blink:
o charAt:
o concat:
o indexOf:
o lastIndexOf:
o match:
o replace:
o search:
o slice:
o substr:
o substring:
o toLowercase:
o toUppercase:
bold:
o This method is used to display a string in a bold font.
Syntax:
Stringobject.bold()
Italics:
o This method is used to display a string in italics font.
Syntax:
Stringobject.italics()
Big:
o This method is used to display a string in big font.
Syntax:
Stringobject.big()
Small:
o This method is used to display a string in small font.
Syntax:
Stringobject.small()
Sub:
o This method is used to give subscript effect to the string.
Syntax:
Stringobject.sub()
Sup:
o This method is used to give superscript effect to the string
Syntax:
Stringobject.small()
Fontsize:
o This method is used to specify the size of font.
Syntax:
Stringobject.fontsize(size)
Fontcolor:
o This method is used to specify the color of font.
Syntax:
Stringobject.fontcolor(color)
Syntax:
Stringobject.strike()
Example:
<script language=”Javascript”>
var myString = "Good Morning"
var myString2 = " Happy World”
var str=”st”;
var str1=”2”;
document.write("<b>My String is</b>: "+myString);
document.write("<b>Bold</b> : "+myString.bold());
document.write("<b>Italics</b> : "+myString.italics());
document.write("<b>Strike</b>: "+myString.strike());
document.write("<b>Superscript</b> : 1"+str.sup());
document.write("<b>Subscript</b>H : "+str1.sub()+”O”);
document.write("<b>FontColor</b>:"+myString.fontcolor("red”) );
document.write("<b>FontColor</b>"+myString.fontcolor("rgb (0,255,0)") );
document.write("<b>FontColor</b>:String.fontcolor("0000FF");
document.write("<b>FontSize</b> : "+myString.fontsize(15));
document.write("<b>Link</b>"+myString.link("javascript") )
CharAt:
o The charAt () method is used to find the character at specified position.
o This method is case sensitive.
Syntax:
Stringobject.charAt(index)
Example:
Var str=”My string”
document. write(charAt(3));
Output:
S
Concat:
Example:
Var st1=”This is“
Var st2=”Computer”
Docement.write(st1.concat(st2))
Output:
This is computer
indexOf:
o this method returns the position of the first occurrence of a specified string value
in a string object.
o It is case sensitive.
o Returns -1 if no match found.
Syntax:
Stringobject.indexOf(stringvalue,startIndex)
Here the string value is required and start index is optional.
Example:
Str=”Have a nice Day”;
document.write(str.indexOf(“Have”))
document.write(str.indexOf(“Nice”))
output:
0
-1
lastIndexOf:
o This method returns position of the last occurrence of a specified string value.
o It is case sensitive.
o It returns -1 if no match found.
Syntax:
Stringobject.lastIndexOf(stringValue,startIndex)
Example:
Var str=”Hello World”
document.write(str.lastIndexOf(“o”))
Output:
7
match
o It searches for specified string value in a string.
o It is similar to indexOf() and lastIndexOf(), but returns specified string, instead of
position of the string.
o Case sensitive.
o Returns null if no match found.
Syntax:
stringObject.match(search value)
Example:
Str=”Have a nice Day”;
document.write(str.indexOf(“Have”))
document.write(str.indexOf(“Nice”))
Output:
Have
Null
Replace:
o The replace() method is used to replace some characters with some other
characters in a string.
o The replace() method is case sensitive.
Syntax:
stringObject.replace (findstring, newstring)
Example:
Var str=”Play Cricket”;
Document.write (str.repalce (“Cricket”,” Chess”)
Output:
Play Chess
Search:
o The search() method is used to search a string for specified value.
o The search() method returns the position of the specified value in the. If no match
was found it returns -1.
o This method is case sensitive.
Syntax:
StringObject.search(searchvalue)
Example:
Var str=”Have a nice day”
Document.write (str.search (“day”))
Output:
12
Slice:
o The slice() method extracts a part of a string and returns the extracted part in a
new string.
o You can use negative numbers to select from the end of the string.
o If the end is not specified, slice () selects all characters from the specified start
position and to the end of the string.
Syntax:
stringObject.slice(start,end)
Example:
Var str=”Hello, How are you?”
Document.write(str.slice(6));
Document.write(str.slice(6,11));
Output:
How are you?
How ar
Substr:
Substring:
o The substring () method extracts the characters in a string between two specified
indices.
o To extract the character from the end of the string, use negative start number. The
start index starts at 0.
o If the stop parameter is omitted, this method extracts to the end of the string.
Syntax:
stringObject.substring(start,stop)
Example:
Var str=”Hello world”;
Document.write(str.substr(3))
Document.write(str.substr(3,7))
Output:
Lo world
Lo w
toLowerCase:
o The toLowerCase() method is used to display a string in lowercase letters.
Syntax:
stringObject.toLowerCase()
Example:
Var str=”Hello World!”
Output:
hello world!
toUpperCase:
o The toUpperCase() method is used to display a string in up-percase letters.
Syntax:
stringObject.toUpperCase()
Example:
Var str=”Hello World!”
Output:
HELLO WORLD!
STRING OBJECT PROPERTY:
length:
o This property is used to count the length of the specified string.
Syntax:
stringObject.length
Example:
Var str=”Hello World”;
Output:
11
Math Object:
Methods:
abs:
It returns absolute value of a number.
Syntax:
Math.abs(number)
Example:
document.write(Math.abs(-7.25));
document.write(Math.abs(7.25));
ceil:
It returns value of number rounded UPWARDS to the nearest integer.
Syntax:
Math.ceil(number)
Example:
Document.write(Math.ceil(0.60))
Document.write(Math.ceil(0.40))
Document.write(Math.ceil(- 5.1))
Document.write(Math.ceil(5.1))
floor:
It returns the value of number rounded DOWNWARDS to the nearest integer.
Syntax:
Math.floor(number)
Example:
document.write(Math.floor (0.60))
cos:
It returns the value of cosine of number.
It returns numeric value between -1 to 1.
Syntax:
Math.cos (number)
Example:
document.write(Math.cos (3))
sin:
Syntax:
Math.sin(number)
Example:
document.write(Math.sin (3))
tan:
It returns the number that represents tangent of an angle.
Syntax:
Math.tan(number)
Example:
document.write(Math.tan (1))
log:
It returns the natural log (base E) of number.
If the number is negative(-), NaN is returned.
Syntax:
Math.log(number)
Example:
document.write(Math.log(1))
pow:
It returns the value of X to power of Y.
Syntax:
Math.pow(x,y)
Example:
document.write(Math.pow(2,3));
document.write(Math.pow(5,2));
random:
It returns a random number between 0 to 1.
Syntax:
Math.random()
Example:
document.write(Math.random());
max:
It returns the number with highest value of two specified numbers.
Syntax:
Math.max(x,y)
Example:
document.write(Math.max(10,15));
min:
It returns the number with lowest value of two specified numbers.
Syntax:
Math.min(x,y)
Example:
document.write(Math.min(10,15));
round:
It rounds the number to nearest integer.
Syntax:
Math.round(number)
Example:
document.write(Math.round(0.60));
document.write(Math.round(0.49));
sqrt:
It returns the square root of a number.
Syntax:
Math.sqrt(number)
Example:
document.write(Math.sqrt(16));
Array Object
An array is the collection of elements having similar datatypes or we can say that array provides
the facility to store multiple values in single variable name.
Property:
length:
It returns the length of the Array.
Syntax:
ArrayObject.length
Example:
<script languagae=”javacript”>
arr[0] = “PHP”
arr[1] = “C”
arr[2] = “VB”
document.write(subArr.length)
</script>
Output:
3
Methods:
concat():
It is used to join two or more Arrays.
This method does not change the original arrays.
It only returns a copy of joined arrays.
Syntax:
ArrayObject.concat()
Example:
<script languagae=”javacript”>
subArr[0] = “PHP”
moreArr[0] = “Java”
moreArr[1] = “Oracle”
document.write(subArr.concat(moreArr))
document.write(subArr.length)
</script>
Output:
PHP,C,VB,Java,Oracle
join():
It is used to put all the elements of array into string.
The elements will be seprated by Seprator, comma(,) is default if you omitted the
parameter.
Syntax:
ArrayObject.join(seprator)
Example:
<script languagae=”javacript”>
arr[0] = “PHP”
arr[1] = “C”
arr[2] = “VB”
document.write(subArr.join(“:”))
</script>
Output:
PHP: C :VB
pop():
It is used to remove and return “Last Element” of Array.
This method changes the length of original Array.
Syntax:
ArrayObject.pop()
Example:
<script languagae=”javacript”>
arr[0] = “PHP”
arr[1] = “C”
arr[2] = “VB”
document.write(subArr.pop())
</script>
Output:
VB
shift():
It is used to remove and return “First Element” of Array.
This method changes the length of original Array.
Syntax:
ArrayObject.shift()
Example
<script languagae=”javacript”>
arr[0] = “PHP”
arr[1] = “C”
arr[2] = “VB”
document.write(subArr.shift())
</script>
Output:
PHP
push():
It is used to add one or more elements to end of the Array and returns new length.
Synatx:
ArrayObject.push(newElement1,newElement2,…)
Example:
<script languagae=”javacript”>
arr[0] = “PHP”
arr[1] = “C”
arr[2] = “VB”
document.write(subArr.push(“java”))
</script>
Output:
4
unshift():
It is used to add one or more elements to the beginning of the Array and returns
new length.
Syntax:
ArrayObject.unshift(newElement1,newElement2,…)
Example:
<script languagae=”javacript”>
arr[0] = “PHP”
arr[1] = “C”
arr[2] = “VB”
document.write(subArr.unshift(“oracle”))
</script>
Output:
4
reverse():
It is used to reverse the order of elements in Array.
It changes the original Array.
Syntax:
ArrayObject.reverse()
Example:
<script languagae=”javacript”>
arr[0] = “PHP”
arr[1] = “C”
arr[2] = “VB”
document.write(subArr.reverse())
</script>
Output:
VB,C,PHP
slice():
Its is used to extract a section of an Arrya and returns a new Array.
Syntax:
ArrayObject.slice(start_index,end_index)
Example:
<script languagae=”javacript”>
arr[0] = “PHP”
arr[1] = “C”
arr[2] = “VB”
document.write(subArr.slice(0,1))
</script>
Output:
PHP
sort():
It is used to sort the elements of an Array.
This method wil sort the elements alphabetically by default.
Numbers will not be sorted correctly.
To sort numbers, we must create function that compare numbers.
After sort() method, Array is changed.
Syntax:
ArrayObject.sort()
Example:
<script languagae=”javacript”>
arr[0] = “PHP”
arr[1] = “C”
arr[2] = “VB”
document.write(subArr.sort())
</script>
Output:
C,PHP,VB
DATE OBJECT:
Javascript does not have the datatype as Date.
However, we can use Date object & its methods to work with dates and times.
Some important things about methods of date object.
Seconds & minutes 0 to 59
Hours 0 to 23
Day 0(Sunday) to 6(Saturday)
Date 1 to 31
Month 0(January) to 11 (December)
Year Years since 1900
Methods:
Date()
o This method returns today’s date and time.
Syntax:
dateObject.Date()
Example:
Var d=new Date()
document.write(d.Date())
getDate()
o The getDate() method returns the day of the month.
o The value returned by getDate() us a number between 1 and 31.
o This method is always used in conjunction with a Date object.
Syntax:
dateObject.getDate()
Example:
Var d=new Date()
document.write(d.getDate())
getDay()
o The getDay() method returns a number that represents the day of the week.
o The value returned by getDay() is a number between 0 and 6. Sunday is 0,
Monday is 1 and so on..
o This method is always used in conjunction with a Date.
Syntax:
dateObject.getDay()
Example:
Var d=new Date()
document.write(d.getDay())
getMonth()
o The getMonth() method reurns the month as a number.
o The value returned by the getMonth() is a number between 0 and 11. January is 0
and February is 1 and so on..
o This method is always used in conjunction with a Date object.
Syntax:
dateObject.getMonth()
Example:
Var d=new Date()
document.write(d.getMonth())
getYear()
o The getYear() method returns the month, as a number.
o The value returned by getMonth() is a number between 0 & 11. January is 0,
February is 1 and So on…
o This method is always used in conjunction with date object.
Syntax:
dateObjecct.getYear()
Example:
Var d=new Date()
Document.write(d.getYear())
getFullYear()
o The getFullYear() method returns a four digit number that represents a year.
o This method is always used in conjunction with a date object.
Syntax:
dateObject.getFullYear()
Example:
Var d=new Date()
Document.write(d.getFullYear())
getHours()
o The getHours() method returns the hour of a time.
o The value returned by this method is a number that represents the Hour of a day.
o This method is always used in conjunction with date object.
Syntax:
dateObject.getHours()
Example:
Var d=new Date()
Document.write(d.getHours())
getMinutes()
o The getMinutes() method returns the minutes of a time.
o The value returned by the getMinutes() is a number that represents minutes of a
current Hour.
o This method is used with conjunction with the date object.
Syntax:
dateObject.getMinutes()
Example:
Var d=new Date()
Document.write(d.getMinutes())
getSeconds()
o This method returns the seconds of a time.
o The value returned by this method is a number that represents the second of a
current time.
o This method is always used in conjunction with date object.
Syntax:
dateObject.getSeconds()
Example:
Var d=new Date()
Document.write(d.getSeconds())
getMilliseconds()
o The getMilliseconds() returns the milliseconds of a time.
o The value returned by this method is a number that represents a milliseconds of a
current time.
o This method is always used in conjunction with date object.
Syntax:
Dateobject.getMilliseconds()
Example:
Var d=new Date()
Document.write(d.getMilliseconds())
getTime()
o The getTime() returns the number of milliseconds since midnight of January 1,
1970.
o This method is always used in conjunction with Date object.
Syntax:
dateObject.getTime()
Example:
Var d=new Date()
Document.write(d.getTime())
setDate()
o The setDate() method is used to set the day of the month.
o The value set by setDate() is a number between 1 and 31, that represents the day
number of month.
o This method is always used in conjunction with Date object.
Syntax:
dateObject.setDate(day)
Example:
Var d=new Date()
d.setDate(4)
setMonth()
o The setMonth() method is used to set the month.
o You can set month by specifying the value of month and value of day.
o The month value in setMonth() is a number between 0 and 11. January is 0,
February is 1 and so on… and the day value in setMonth() is a number between 1
and 31, represents the day of month.
o This method is always used in conjunction with Date object.
o Here the parameter day is optional and month is required.
Syntax:
dateObject.setMonth(month,day)
Example:
Var d=new Date()
d.setMonth(8)
setFullYear()
o The setFullYear() method is used to set the year.
o You can set the year by specifying the year, month and day value.
o The year value represents the four digit value specifies the year.
o The month value represents the number between the 0 and 11 specifies the month.
o The day value represents the number between 1 and 31, specifies the date.
o Here the parameter year is required and month and day are optional.
Syntax:
dateObject.setFullYear(year,month,day)
Example:
Var d=new Date()
d.setFullYear(2009)
setYear()
o The setYear() method is used to set the year.
o The value set by the setYear() is a numeric value that represents the year value.
o Always used in conjunction with date Object.
Syntax:
dateObject.setYear(year)
Example:
Var d=new Date()
d.setYear(year)
setHours()
o The setHours() method is used to set the hour of a specified time.
o You can set hours by specifying the values of hours, minutes, seconds and
milliseconds.
o Here the parameter hours is required. Where as minutes, seconds, milliseconds are
optional.
o Always used in conjunction with date object.
Syntax:
dateObject.setHours(hour,minutes,seconds,millisec)
Example:
Var d=new Date()
d.setHours(10)
setMinutes()
o The setMinutes() method is used to set the minutes of a specified time.
o You can set the minutes by specifying the values of minutes, seconds and
milliseconds.
o Here the parameter minute is required where as seconds and milliseconds are
optional.
o Always used in conjunction with date object.
Syntax:
dateObject.setMinutes(minute,seconds,milliseconds)
Example:
Var d=new Date()
d.setMinutes(20)
setSeconds()
o The setSeconds() method is used to set the seconds of a specified time.
o You can set the seconds by specifying the values of seconds and milliseconds.
o Here the parameter second is required and millisecond is optional.
o Always used in conjunction with date Object.
Syntax:
dateObject.setSeconds(seconds,milliseconds)
Example:
Var d=new Date()
d.setSeconds(20);
WINDOW OBJECT
When you load your browser application, a window immediately appears. This window is known
as browser window or window in short. You can use JavaScript to open a window, as the result
of a button click or any other operation. Since each window is represented as a distinct window
object, opening a new window actually creates another window object.
CREATE A WINDOW
<html><head>
<script type="text/javascript">
function open_win()
window.open("","my1","menubar,status,toolbar,height=100,width
=500")
window.open("","my2","fullscreen,menubar,status,toolbar")
</script>
</head>
<body>
<form>
</form></body></html>
Example 2
<html>
<head>
<script type="text/javascript">
function closeWin()
myWindow.close()
}
</script>
</head>
<body>
<script type="text/javascript">
myWindow=window.open('','','width=200,height=100)
myWindow.document.write("This is 'myWindow'")
</script>
<form>
</form>
</body>
</html>
Example 3
<html>
<head>
<script type="text/javascript">
function resizeWindow1()
window.resizeBy(-100,-100)
function resizeWindow2()
window.resizeTo(500,300)
/*method is used to resize the window to the specified width and height.*/
</script></head>
<body>
<form>
</form>
</body></html>
HISTORY OBJECT
The browser maintains a list of most recent URL’s, which can be viewed in IE as well as
Netscape. The history list behaves like a LIFO queue (Last In First Out). The history list is
represented in JavaScript by the window.history object. It allows u to deal with list but not with
the data.
Example 1
<html>
<head>
function ShowHistory()
</script>
</head>
<body onload="ShowHistory()">
</body>
</html>
Example 2
<html>
<head>
<script type="text/javascript">
function goBack()
history.back()
}
</script>
</head>
<body>
<input type="button"
value="Back"
onclick="goBack()" />
</body>
</html>
Example 3
<html>
<head>
<script type="text/javascript">
function goBack()
history.go(-3)
</script>
</head>
</html>
LOCATION OBJECT
The Location object is actually a JavaScript object, not an HTML DOM object. The Location
object is automatically created by the JavaScript runtime engine and contains information about
the current URL. Example: Send a user to a new location. The Location object is part of the
Window object and is accessed through the window.location property.IE: Internet Explorer, F:
Firefox, O: Opera.
assign()
Example 1
<html>
<head>
<script type="text/javascript">
function newDoc()
window.location.assign("http://www.yahoo.com")
</script>
</head>
<body>
<input type="button"
onclick="newDoc()" />
</body></html>
reload()
Example 2
<html>
<head>
<script type="text/javascript">
function reloadPage()
window.location.reload()
</script>
</head>
<body>
<input type="button"
value="Reload page"
onclick="reloadPage()" />
</body>
</html>
replace()
Example 3
<html>
<head>
<script type="text/javascript">
function replaceDoc()
window.location.replace("http://www.yahoo.com")
</script>
</head>
<body>
<input type="button"
value="Replace document"
onclick="replaceDoc()" />
</body>
</html>
Search property
Example 4
<html>
<body>
<script type="text/javascript">
document.write(location.search);
</script>
</body>
</html>
Href property
Example 5
<html>
<body>
<script type="text/javascript">
document.write(location.href);
</script>
</body>
</html>
NAVIGATOR OBJECT
The Navigator object is actually a JavaScript object, not an HTML DOM object. The Navigator
object is automatically created by the JavaScript runtime engine and contains information about
the client browser. IE: Internet Explorer, F: Firefox, O: Opera.
Navigator Attribute Description
appCodeName Returns the code name of the browser
appMinorVersion Returns the minor version of the browser
appName Returns the name of the browser
appVersion Returns the platform and version of the browser
browserLanguage Returns the current browser language
cookieEnabled Returns a Boolean value that specifies whether cookies are
enabled in the browser
cpuClass Returns the CPU class of the browser's system
onLine Returns a Boolean value that specifies whether the system is
in offline mode
platform Returns the operating system platform
systemLanguage Returns the default language used by the OS
userAgent Returns the value of the user-agent header sent by the client
to the server
userLanguage Returns the OS' natural language setting
javaEnabled() Specifies whether or not the browser has Java enabled
taintEnabled() Specifies whether or not the browser has data tainting
enabled
Example
<html>
<body>
<script type="text/javascript">
document.write("<p>Browser: ")
document.write(navigator.appName + "</p>")
document.write("<p>Browserversion: ")
document.write(navigator.appVersion + "</p>")
document.write("<p>Code: ")
document.write(navigator.appCodeName + "</p>")
document.write("<p>Platform: ")
document.write(navigator.platform + "</p>")
document.write(navigator.userAgent + "</p>")
</script>
</body>
</html>
Example
<html>
<body>
<script language="javascript">
myobj.part1="Dhtml"
myobj.part2="Javascript"
myobj.part3="Php and Mysql"
document.write(myobj.subject+"<br>")
document.write(myobj.part1+"<br>")
document.write(myobj.part2+"<br>")
document.write(myobj.part3+"<br>")
</script>
</body>
</html>
Example
<html>
<body>
<script language="javascript">
function myobject(subject,part1,part2,part3)
this.subject = subject
this.part1= part1
this.part2= part2
this.part3= part3}
document.write(myobj.part1+"<br>")
document.write(myobj.part2+"<br>")
document.write(myobj.part3+"<br>")
</script>
</body>
</html>
1. getElementById()
2. getElementByName()
3. innerHTML property
getElementById()
If you want to quickly access the value of an HTML input, than these method can
be used.
It return a reference of the HTML element(control).
Syntax:
getElementById(Control Reference);
For example:
<head>
<script language=javascript>
Function notEmpty()
var mytextfield=document.getElementById(“mytext”);
if(mytextfield.value!=” “)
alert(“You entered”+mytextfield.value);
else
</script>
<body>
<form>
</form>
</body></script>
Syntax:
document.getElementByName(Name);
for example:
<head>
<script language=javascript>
function getElements()
var x=document.getElementByName(“myinput”);
alert(x.length);
</script>
</head>
<body>
<form>
</script>
</body>
innerHTML property
The innerHTML property sets or returns the HTML content (inner HTML) of an
element.
Syntax
HTMLElementObject.innerHTML
HTMLElementObject.innerHTML=text
for Example
<body>
</body>
<head>
<script type="text/javascript">
function f()
document.getElementById("mytext").innerHTML="JavaScript";
}
</script>
</head>
Every web page resides inside a browser window which can be considered as an
object.
A Document object represents the HTML document that is displayed in that window.
The Document object has various properties that refer to other objects which allow
access to and modification of document content.
The way that document content is accessed and modified is called the Document
Object Model, or DOM. The Objects are organized in a hierarchy. This hierarchical
structure applies to the organization of objects in a Web document.
o Window object: Top of the hierarchy. It is the outmost element of the object
hierarchy.
o Document object: Each HTML document that gets loaded into a window becomes a
document object. The document contains the content of the page.
o Form object: Everything enclosed in the <form>...</form> tags sets the form object.
o Form control elements: The form object contains all the elements defined for that
object such as text fields, buttons, radio buttons, and checkboxes.
o Here is a simple hierarchy of few important objects:
o There are several DOMs in existence. The following sections explain each of these
DOMs in detail and describe how you can use them to access and modify document
content.
The Legacy DOM: This is the model which was introduced in early versions
of JavaScript language. It is well supported by all browsers, but allows access
only to certain key portions of documents, such as forms, form elements, and
images.
The W3C DOM: This document object model allows access and
modification of all document content and is standardized by the World Wide
Web Consortium (W3C). This model is supported by almost all the modern
browsers.
The IE4 DOM: This document object model was introduced in Version 4 of
Microsoft's Internet Explorer browser. IE 5 and later versions include support
for most basic W3C DOM features.
forms[ ] An array of Form objects, one for each HTML form that
appears in the document.
Example: document.forms[0], document.forms[1] and so
on
links[ ] links[ ]
Example: document.links[0], document.links[1] and so
on
EXAMPLE
o We can locate any HTML element with-in any HTML document using HTML DOM. For
instance, if a web document contains a form element then using JavaScript we can refer
to it as document.forms[0]. If your Web document includes two form elements the first
form is referred to as document.forms[0] and the second document.forms[1].
o Using the hierarchy and properties given above, we can access first form element using
document.forms[0].elements[0] and so on.
o Here is an example to access document properties using Legacy DOM method:
<html>
<head>
<title> Document Title </title>
<script type="text/javascript">
function myFunc()
{
var ret = document.title;
alert("Document Title : " + ret );
THE}W3C DOM
</script>
o This document object model allows access and modification of all document content
</head>
and is standardized by the World Wide Web Consortium (W3C). This model is
<body>
supported by almost all the modern browsers.
<h1 id="title">This is main title</h1>
o The W3Cthe
<p>Click DOM standardizes
following most
to see the of the features of the legacy DOM, but also adds
result:</p>
important new ones. In addition to supporting forms[ ], images[ ], and other array
<form name="FirstForm">
properties of the Document object, it defines methods that allow scripts to access and
<input type="button" value="Click Me" onclick="myFunc();" />
<input type="button" value="Cancel">
</form>
manipulate any document element and not just special-purpose elements like forms
and images.
DOCUMENT PROPERTIES IN W3C DOM:
This model supports all the properties available in Legacy DOM.
Additionally, here is the list of document properties which can be accessed
using W3C DOM:
EXAMPLE
o This is very easy to manipulate ( Accessing and Setting ) document element using
W3C DOM. You can use any of the methods like getElementById,
getElementsByName, or getElementsByTagName.
<html>
<head>
<title> Document Title </title>
<script type="text/javascript">
function myFunc()
THE IE 4 DOM
all[ ] An array of all Element objects within the document. This array
may be indexed numerically to access elements in source order, or
it may be indexed by element id or name.
Example: document.all[ ]
children[ ] An array that contains the HTML elements that are direct children
of the document. Note that this is different than the all[ ] array
that contains all elements in the document, regardless of their
position in the containment hierarchy.
Example: document.children[ ]
Interactive The document has loaded sufficiently for the user to interact with
it.
Example: document.interactive
EXAMPLE:
o The IE 4 DOM does not support the getElementById( ) method. Instead, it allows you to
look up arbitrary document elements by id attribute within the all[ ] array of the
document object.
o Here's how to find all <li> tags within the first <ul> tag. Note that you must specify the
desired HTML tag name in uppercase with the all.tags( ) method.
var lists = document.all.tags("UL");
o Here is another example to access document properties using IE4 DOM method:
<html>
<head>
<title> Document Title </title>
<script type="text/javascript">
function myFunc()
{
var ret = document.all["heading"];
alert("Document Heading : " + ret.innerHTML );
BUILT IN OBJECTS IN JAVASCRIPT
COOKIES
Cookies are data, stored in small text files, on your computer.Web Browser and Server use
HTTP protocol to communicate and HTTP is a stateless protocol. But for a commercial
website it is required to maintain session information among different pages.
HOW IT WORKS
Your server sends some data to the visitor's browser in the form of a cookie. The browser
may accept the cookie. If it does, it is stored as a plain text record on the visitor's hard
drive. Now, when the visitor arrives at another page on your site, the browser sends the
same cookie to the server for retrieval. Once retrieved, your server knows/remembers
what was stored earlier.
Cookies are a plain text data record of 5 variable-length fields:
Expires: The date the cookie will expire. If this is blank, the cookie will
expire when the visitor quits the browser.
Domain: The domain name of your site.
Path: The path to the directory or web page that set the cookie. This may be
blank if you want to retrieve the cookie from any directory or page.
Secure: If this field contains the word "secure" then the cookie may only be
retrieved with a secure server. If this field is blank, no such restriction exists.
Name=Value: Cookies are set and retrieved in the form of key and value
pairs.
Cookies were originally designed for CGI programming and cookies' data is
automatically transmitted between the web browser and web server, so CGI scripts on the
server can read and write cookie values that are stored on the client.
JavaScript can also manipulate cookies using the cookie property of the Document
object. JavaScript can read, create, modify, and delete the cookie or cookies that apply to
the current web page.
STORING COOKIES:
The simplest way to create a cookie is to assign a string value to the document.cookie
object, which looks like this:
SYNTAX
document.cookie = "key1=value1;key2=value2;expires=date";
Here expires attribute is option. If you provide this attribute with a valid date or time
then cookie will expire at the given date or time and after that cookies' value will not
be accessible.
EXAMPLE
<html>
<head>
<script type="text/javascript">
function WriteCookie()
READING COOKIES
{
Reading a cookie is just as simple==as"" writing
if( document.myform.customer.value ){ one, because the value of the
document.cookie object
alert("Enter some is the cookie. So you can use this string whenever you want
value!");
return;
to access the cookie.
The} document.cookie string will keep a list of name=value pairs separated by
semicolons, where name is the name of a cookie and value is its string value.
cookievalue= escape(document.myform.customer.value) + ";";
EXAMPLE
document.cookie="name=" + cookievalue;
alert("Setting Cookies : " + "name=" + cookievalue );
<html>
}<head>
<script type="text/javascript">
</script>
function ReadCookie()
</head>
{
<body>
var allcookies = document.cookie;
<form name="myform"
alert("All Cookies : " + action="">
allcookies );
Enter name: <input type="text" name="customer"/>
<input
// Gettype="button"
all the cookiesvalue="Set
pairs in anCookie"
array onclick="WriteCookie();"/>
</form>
cookiearray = allcookies.split(';');
</body>
</html>
// Now take key value pair out of this array
for(var i=0; i<cookiearray.length; i++){
name = cookiearray[i].split('=')[0];
value = cookiearray[i].split('=')[1];
alert("Key is : " + name + " and Value is : " + value);
}
}
</script>
</head>
<body>
SETTING THE COOKIES EXPIRATION DATE
You can extend the life of a cookie beyond the current browser session by setting an
expiration date and saving the expiration date within the cookie. This can be done by
setting the expires attribute to a date and time.
<html>
<head>
<script type="text/javascript">
<!--
function WriteCookie()
{
var now = new Date();
now.setMonth( now.getMonth() + 1 );
cookievalue = escape(document.myform.customer.value) + ";"
document.cookie="name=" + cookievalue;
document.cookie = "expires=" + now.toUTCString() + ";"
alert("Setting Cookies : " + "name=" + cookievalue );
}
//-->
</script>
</head>
<body>
<form name="formname" action="">
Enter name: <input type="text" name="customer"/>
<input type="button" value="Set Cookie" onclick="WriteCookie()"/>
</form>
</body>
</html>
DELETING A COOKIE:
Sometimes you will want to delete a cookie so that subsequent attempts to read the
cookie return nothing. To do this, you just need to set the expiration date to a time in
the past.
EXAMPLE:
The following example illustrates how to delete cookie by setting expiration date one
Month in past :
<html>
<head>
<script type="text/javascript">
function WriteCookie()
{
var now = new Date();
now.setMonth( now.getMonth() - 1 );
cookievalue = escape(document.myform.customer.value) + ";"
document.cookie="name=" + cookievalue;
document.cookie = "expires=" + now.toUTCString() + ";"
alert("Setting Cookies : " + "name=" + cookievalue );
}
</script>
Writing Server Side Script
</head>
<body>
<form name="formname" action="">
Enter name: <input type="text" name="customer"/>
<input type="button" value="Set Cookie" onclick="WriteCookie()"/>
</form>
</body>
</html>
ADVANTAGES OF PHP
Cost: PHP costs you nothing. It is open source software and doesn’t need to purchase
it for development.
Ease to use: PHP is easy to learn, compared to the others. A lot of Ready-made PHP
scripts are freely available in market so, you can use them in your project or get some
help from them.
HTML – Support: PHP is embedded within HTML; In other words, PHP pages are
ordinary HTML pages that escape into PHP mode only when necessary. When a
client requests this page, the web server preprocesses it. This means it goes through
the page from top to bottom, looking for sections of PHP, which it will try to resolve.
Cross-platform Compatibility: PHP and MySQL run native on every popular flavor
of Unix and Windows. A huge percentage of the world’s HTTP servers run on one of
these two classes of operating system.
PHP is compatible with the three leading Web server: Apache HTTP Server for Unix
and windows. Microsoft Internet Informing Server (IIS), and Netscape Enterprise
Server, It Also works with several lesser-known servers, including Alex Blits’
fhttpd, Microsoft’s Personal Web server, AOL Server and Omnicentrix’s Omni server
application server.
Stability : The word stable means two different things in this context :
The server doesn’t need to be rebooted often
The software doesn’t change radically and incompatibly from release to
release.
To our advantage, both of these apply to both MySQL and PHP.
Speed: PHP is pleasingly zippy in its execution, especially when compiled as and
Apache module of the UNIX side. Although it takes a slight performance his by being
interpreted rather than compiled, this is far outweighed by benefits PHP drives from
its status as a Web server module.
DIS-ADVANTAGES OF PHP
Security :
Since it is open sourced, so all people can see the source code, if there are bugs in the
source code, it can be used by people to explore the weakness of PHP.
Not suitable for large applications:
Hard to maintain since it is not very modular.
Weak type:
Implicit conversion may surprise unwary programmers and lead to unexpected bugs.
For example, the strings “1000” and “1e3” compare equal because they are implicitly
cast to floating point numbers.
o short_open_tag = Off
Short open tags look like this: <? ?>. This option must be set to Off if you want to use
XML functions
o safe_mode = Off
If this is set to On, you probably compiled PHP with the --enable-safe-mode flag.
Safe mode is most relevant to CGI use. See the explanation in the section "CGI
compile-time options". earlier in this chapter.
o safe_mode_exec_dir = [DIR]
This option is relevant only if safe mode is on; it can also be set with the --with-exec-
dir flag during the Unix build process. PHP in safe mode only executes external
binaries out of this directory. The default is /usr/local/bin. This has nothing to do with
serving up a normal PHP/HTML Web page.
o safe_mode_allowed_env_vars = [PHP_]
This option sets which environment variables users can change in safe mode. The
default is only those variables prepended with "PHP_". If this directive is empty,
most variables are alterable.
o safe_mode_protected_env_vars = [LD_LIBRARY_PATH]
This option sets which environment variables users can't change in safe mode, even if
safe_mode_allowed_env_vars is set permissively
o max_execution_time = 30
The function set_time_limit() won.t work in safe mode, so this is the main way to
make a script time out in safe mode. In Windows, you have to abort based on
maximum memory consumed rather than time. You can also use the Apache timeout
setting to timeout if you use Apache, but that will apply to non-PHP files on the site
too.
o error_reporting = E_ALL & ~E_NOTICE
The default value is E_ALL & ~E_NOTICE, all errors except notices. Development
servers should be set to at least the default; only production servers should even
consider a lesser value
o error_prepend_string = [""]
With its bookend, error_append_string, this setting allows you to make error
messages a different color than other text, or what have you.
o warn_plus_overloading = Off
This setting issues a warning if the + operator is used with strings, as in a form value.
o variables_order = EGPCS
This configuration setting supersedes gpc_order. Both are now deprecated along with
register_globals. It sets the order of the different variables: Environment, GET,
POST, COOKIE, and SERVER (aka Built-in).You can change this order around.
Variables will be overwritten successively in left-to-right order, with the rightmost
one winning the hand every time. This means if you left the default setting and
happened to use the same name for an environment variable, a POST variable, and a
COOKIE variable, the COOKIE variable would own that name at the end of the
process. In real life, this doesn't happen much.
o register_globals = Off
This setting allows you to decide whether you wish to register EGPCS variables as
global. This is now deprecated, and as of PHP4.2, this flag is set to Off by default.
Use superglobal arrays instead. All the major code listings in this book use
superglobal arrays.
o gpc_order = GPC
This setting has been GPC Deprecated.
o magic_quotes_gpc = On
This setting escapes quotes in incoming GET/POST/COOKIE data. If you use a lot of
forms which possibly submit to themselves or other forms and display form values,
you may need to set this directive to On or prepare to use addslashes() on string-type
data.
o magic_quotes_runtime = Off
This setting escapes quotes in incoming database and text strings. Remember that
SQL adds slashes to single quotes and apostrophes when storing strings and does not
strip them off when returning them. If this setting is Off, you will need to use
stripslashes() when outputting any type of string data from a SQL database. If
magic_quotes_sybase is set to On, this must be Off.
o magic_quotes_sybase = Off
This setting escapes single quotes in incoming database and text strings with Sybase-
style single quotes rather than backslashes. If magic_quotes_runtime is set to On, this
must be Off.
o auto-prepend-file = [path/to/file]
If a path is specified here, PHP must automatically include() it at the beginning of
every PHP file. Include path restrictions do apply.
o auto-append-file = [path/to/file]
If a path is specified here, PHP must automatically include() it at the end of every
PHP file.unless you escape by using the exit() function. Include path restrictions do
apply.
o include_path = [DIR]
If you set this value, you will only be allowed to include or require files from these
directories. The include directory is generally under your document root; this is
mandatory if you.re running in safe mode. Set this to . in order to include files from
the same directory your script is in. Multiple directories are separated by colons:
.:/usr/local/apache/htdocs:/usr/local/lib.
o doc_root = [DIR]
If you.re using Apache, you.ve already set a document root for this server or virtual
host in httpd.conf. Set this value here if you.re using safe mode or if you want to
enable PHP only on a portion of your site (for example, only in one subdirectory of
your Web root).
o file_uploads = [on/off]
Turn on this flag if you will upload files using PHP script.
o upload_tmp_dir = [DIR]
Do not uncomment this line unless you understand the implications of HTTP uploads!
o session.save-handler = files
Except in rare circumstances, you will not want to change this setting. So don't touch
it.
o ignore_user_abort = [On/Off]
This setting controls what happens if a site visitor clicks the browser.s Stop button.
The default is On, which means that the script continues to run to completion or
timeout. If the setting is changed to Off, the script will abort. This setting only works
in module mode, not CGI.
o mysql.default_host = hostname
The default server host to use when connecting to the database server if no other host
is specified.
o mysql.default_user = username
The default user name to use when connecting to the database server if no other name
is specified.
o mysql.default_password = password
The default password to use when connecting to the database server if no other
password is specified.
o upload_max_filesize = 10M
The maximum size of an uploaded file.
o memory_limit
This sets the maximum amount of memory in bytes that a script is allowed to allocate.
This helps prevent poorly written scripts for eating up all available memory on a
server. Note that to have no memory limit, set this directive to -1.
o post_max_size = 10M
Sets max size of post data allowed. This setting also affects file upload. To upload
large files, this value must be larger than upload_max_filesize. If memory limit is
enabled by your configure script, memory_limit also affects file uploading. Generally
speaking, memory_limit should be larger than post_max_size.
o There are four different pairs of opening and closing tags which can be used in
php. Here is the list of tags.
o Default syntax
o Short open Tags
o HTML Script Tags
o ASP Style Tags
Default Syntax
o The default syntax starts with "<? php" and ends with "?>".
Example
<?php
echo "Default Syntax";
?>
Comments
Syntax
// This is a single-line comment
/*
This is
a multi-line
comment.
*/
VARIABLES in PHP
A variable is a holder for a type of data. Variable in PHP are represented by a dollar
sing followed by the name of the variable.
The variable name is case-sensitive.
Variable naming rule is: A valid variable name starts with a letter or underscore,
followed by any number of letters, numbers, or underscores.
Syntax:
$varName = "Value";
CASE SENSITIVITY
o One thing that causes many problems and take hours of finding mistakes is case sensitivity.
PHP is case sensitive.
EXAMPLE
<?php
$myVar = "WebCheatSheet";
$myvar = "PHP tutorial";
echo "$myVar - $myvar"; //outputs "WebCheatSheet - PHP tutorial"
?>
Variable, function and class names are all identifiers and all follow the rules below, with
the exception that function names are not case sensitive.
TYPE STRENGTH
PHP is weakly typed, meaning that variables do not need to be assigned a type (e.g,
Integer) at the time they are declared. Rather, the type of a PHP variable is determined by
the value the variable holds and the way in which it is used.
Hello Variables!
Here is the "Hello World!" script again, but this time we use a variable.
Code Sample:
<?php
$greeting = 'Hello World!';
?>
<body>
<?php
echo $greeting;
?>
</body>
</html>
This time the string "Hello World!" is stored in the $greeting variable, which is output in
the title and body of the page with an echo command.
VARIABLE SCOPE
A variable's scope determines the locations from which the variable can be accessed. PHP
variables are superglobal, global, or local.
VariableScope Explanation
Global variables are visible throughout the script in which they are
Global declared. However, they are not visible within functions in the script unless
they are re-declared within the function as global variables.
Variables in the function scope are called local variables. Local variables
are local to the function in which they are declared.
SUPERGLOBALS
Again, superglobal variables are predefined arrays, including $_POST and $_GET and
are accessible from anywhere on the page. The complete list of superglobals is shown
below.
The elements within superglobal variables can be accessed in three different ways, which
the authors of PHP and MySQL Web Development refer to as short style, medium style,
and long style.
GLOBALS
o $GLOBALS is a php super global variable which can be used instead of 'global'
keyword to access variables from global scope, i.e. the variables which can be
accessed from anywhere in a php script even within functions or methods.
o EXAMPLE
<?php
$s = 25;
$t = 50;
function subtraction()
{
$GLOBALS['v'] = $GLOBALS['t'] - $GLOBALS['s'];
}
subtraction();
echo $v;
?>
CONSTANTS
o A constant is an identifier for a simple value. The value cannot be modified
during the script's execution. A valid constant name starts with a letter or
underscore (no dollar ($) sign before the name) and by convention constant
identifier are always uppercase.
o Constants are defined by using the define() function or by using the const
keyword outside a class definition.
o The name of the constant and the value must be placed within the parentheses.
After defining it can never be changed or undefined.
o Only scalar data i.e. boolean, integer, float and string can be contained in
constants.
SYNTAX
define(name, value, case-insensitive)
PARAMETERS
EXAMPLE
<?php
// first we define a constant PASSWORD
define("PASSWORD","admin");
PHP provides built-in functions for checking if a variable exists, checking if a variable
holds a value, and removing a variable.
To output the results of these functions to a browser, use the var_dump() function (e.g.
var_dump(isset($a));).
Example
<?php
$xyz='w3resource.com';
unset($xyz);
?>
Example
<?php
$var1 = 'test';
var_dump(isset($var1));
?>
Example
<?php
$var = 0;
{
echo '$var is either 0, empty, or not set at all';
}
{
echo '$var is set even though it is empty';
}
?>
Example
<?php
$var = 0;
{
echo '$var is set even though it is empty';
}
?>
PHP OPERATORS
Arithmetic Operators
Comparison Operators
Logical (or Relational) Operators
Assignment Operators
Conditional (or ternary) Operators
Incrementing/Decrementing Operators
ARITHMETIC OPERATORS
Assume variable $a holds 10 and variable $b holds 20 then:
Operator Description Example
ASSIGNMENT OPERATORS
Assignment operators allow writing a value to a variable. The first operand must be a
variable and the basic assignment operator is "=". The value of an assignment
expression is the final value assigned to the variable. In addition to the regular
assignment operator "=", several other assignment operators are composites of an
operator followed by an equal sign.
SYNTAX:
The ternary operator in PHP consists of three expressions: a condition, and two operands
that describe what action should be taken if the condition is true or false
$variable = ( condition ) ? true : false;
EXAMPLE:
<?php
$a=10;
$b=20;
$answer = ($a >= $b) ? "Condition is Ture" : "Condition is False";
echo $answer;
?>
Output:
Condition is False
INCREMENTING/DECREMENTING OPERATORS
o There are different ways by which values of variables can be passed between
pages. One of the ways is to use the URL to pass the values or data.
o Here the biggest advantage is we can pass data to a different site even running at
different servers.
o Any scripting language like ASP, JSP, PHP or Perl running at receiving end can
process and collect the value from the query string or from the URL.
o Here one main concern is the data gets exposed in address bar of the browser and
can be easily accessible by using browser history.
o So this is not a good idea to pass sensitive data like password through the URL to
different pages or different sites.
EXAMPLE
<?php
$name='vsc';
echo "<a href='page2.php?user=$name'>link to page1</a>";
?>
o When the above link is clicked, page2.php gets the variables user with variable
$name. Here is the code to collect data in PHP.
EXAMPLE
echo $_GET[user]; // output vsc
FIRST PHP SCRIPT
In this exercise, you will write a simple PHP script from scratch. The script will declare a
variable called $today that stores the day of the week.
2. Declare a variable called $today that holds the current day of the week as literal text.
3. Output $today in the title and body of the page.
4. Test your solution in a browser. The resulting HTML page should look like this:
FLOW CONTROLS
Flow control in PHP with if-elseif-else conditions and with loops.
2.6.1 CONDITIONAL STRUCTURE
IF STATEMENT
Use this statement to execute some code only if a specified condition is true.
SYNTAX:
<?php
if (condition)
statement; //code to be executed if condition is true;
?>
EXAMPLE:
<?php
$a=10;
$b=20;
if ($a<=$b)
Use this statement to execute some code if a condition is true and another code if the
condition is false.
SYNTAX:
<?php
if (condition)
{
statement; //code to be executed if condition is true;
}
else
{
statement; //code to be executed if condition is false;
}
EXAMPLE:
<?php
$a=10;
$b=20;
if ($a==$b)
{
echo "A is Equal to B";
}
else
{
echo "A is Greater than or Equal to B";
}
?>
Output
A is Greater than or Equal to B
IF...ELSEIF....ELSE STATEMENT
Used with the if...else statement to execute a set of code if one of several condition are
true.
SYNTAX
if (condition)
{
statement; //code to be executed if condition is true;
}
elseif (condition)
{
statement; //code to be executed if condition is true;
}
else EXAMPLE
{
statement; //code to be executed if condition is false;
}
<?php
$a=10;
$b=20;
if ($a==$b)
{ echo "A is Equal to B"; }
else if($a>=$b)
{ echo "A is Greater than or Equal to B"; }
else
SWITCH STATEMENT
SYNTAX
switch ( expression ) {
case result1:
// execute this if expression results in result1
break;
case result2:
// execute this if expression results in result2
EXAMPLE
break;
default:
// execute this if no break statement
// has been encountered hitherto
}
EXAMPLE
<?php
switch ($i) {
case 0:
echo "i equals 0";
case 1:
echo "i equals 1";
2.6.2 LOOPING STRUCTURE
case 2:
echo "i equals 2";
} ?>
for
while
do...while
foreach
FOR LOOP
SYNTAX:
EXAMPLE
<?php
WHILE LOOP
SYNTAX:
while (condition)
{
code to be executed;
}
EXAMPLE:
<?php
$i = 1;
while($i < 5)
{
echo $i;
$i++;
} ?>
Output:
12345
DO...WHILE LOOP
Loops through a block of code once, and then repeats the loop as long as a special
condition is true.
SYNTAX:
do
{
code to be executed;
}
while (condition);
EXAMPLE:
<?php
$i = 1;
do
{
echo $i;
$i++;
}
while( $i < 5 );
?>
Output:
12345
FOREACH LOOP
The foreach statement is used to loop through arrays. For each pass the value of the
current array element is assigned to $value and the array pointer is moved by one and in
the next pass next element will be processed.
SYNTAX
EXAMPLE
<?php
$array = array( 1, 2, 3, 4, 5);
foreach( $array as $value )
{
echo "Value is $value <br />";
2.7 ARRAY
An array is a special variable, which can store multiple values of same datatype in
one single variable.
For example if you want to store 99 numbers then instead of defining 100 variables
it’s easy to define an array of 99 lengths.
TYPES OF ARRAY:
SYNTAX
EXAMPLE
ASSOCIATIVE ARRAY
SYNTAX
EXAMPLE
<?php
$student_marks["Ronak"] = 80;
$student_marks["Vipul"] = 90;
$student_marks["Shakshi"] = 85;
Example:1
foreach ($student_marks as $name=>$marks)
{
echo "Studnet name is ".$name ." have got ".$marks." Marks<br>";
}
?>
Output of Example1:
Studnet name is Ronak have got 80 Marks
Studnet name is Vipul have got 90 Marks
Studnet name is Shakshi have got 85 Marks
Example2:
foreach ($student_marks as $name)
{
echo "Studnet Marks is ".$name."<br>";
}
Output:
Studnet Marks is 80
Studnet Marks is 90
Studnet Marks is 85
MULTIDIMENSIONAL ARRAY:
In multi-dimensional array each element in the main array can also be an array.
Each element in the sub-array can be an array, and so on.
Values in the multi-dimensional array are accessed using multiple indexes.
SYNTAX
$var_name=array(keys1=>array(childkey1=>value1,childkey2=>value2….));
EXAMPLE:
<?php
$marks = array(
"Amar" => array
(
"physics" => 35,
"maths" => 30,
"chemistry" => 39
<?php
$family = array("Mike"=>array("Ben","Katty","Paul"));
$family = array("Mike"=>array("Ben","klatty","Paul"),"Johnson"=>array("Shena","Glenn"));
echo "The family Johnson have two members;". $family['Johnson'][0] . "and " .
$family['Johnson'][1] ;
?>
GET METHOD
The GET method sends the encoded user information appended to the page request. The
page and the encoded information are separated by the? Character.
http://localhost/index.php?name1=value1&name2=value2
<?php
if(isset($_GET["submit"]))
{
echo $_GET['name'];
echo $_GET['city'];
}
?>
<html>
<body>
<form method="GET">
Name: <input type="text" name="name" />
City: <input type="text" name="city" />
<input type="submit" name="submit" /> </form></body></html>
POST METHOD
The POST method transfers information via HTTP headers. The information is encoded
as described in case of GET method and put into a header called QUERY_STRING.
The POST method does not have any restriction on data size to be sent.
The POST method can be used to send ASCII as well as binary data.
The data sent by POST method goes through HTTP header so security depends on HTTP
protocol. By using Secure HTTP you can make sure that your information is secure.
The PHP provides $_POST associative array to access all the sent information using GET
method.
EXAMPLE:
<?php
if(isset($_POST["submit"]))
{
echo $_POST['name'];
echo $_POST['city'];
}
?>
<html>
<body>
<form method="POST">
Name: <input type="text" name="name" />
City: <input type="text" name="city" />
<input type="submit" name="submit" />
</form>
</body>
</html>
o A web form has two parts: the HTML ‘front end’ and a back end form processor. The HTML
front end part handles the presentation while the back end handles the form submissions (like
saving the form submissions, sending emails etc).
o The back end form processor script is usually written in languages like PHP, ASP or Perl.
o The image below illustrates the concept:
1. A visitor visits a web page that contains a form.
2. The web browser displays the HTML form.
3. The visitor fills in the form and submits
4. The browser sends the submitted form data to the web server
5. A form processor script running on the web server processes the form data
6. A response page is sent back to the browser.
Concatenation
Concatenation is a programming word for adding strings together. In PHP, the concatenation
operator is a dot (.). Generally, concatenation is used to combine literal text with variables or
values returned from functions. The example below illustrates this.
Code Sample:
<body>
<h1>Concatenation</h1>
<?php
$firstName = 'Paul';
$greeting = 'Hello';
echo $greeting . ' ' . $firstName . '!';
?>
<h2>Using Double Quotes to Avoid the Concatenation Operator</h2>
<?php
echo "$greeting $firstName!";
?>
<h2>Double quotes don't work when concatenating
the results of a function call</h2>
<?php
echo $greeting . ' ' . $firstName . '! Today is ' . date('l') . '.';
?>
</body>
chr()
The chr() function returns a character from the specified ASCII value.
SYNTAX:
chr(ascii)
PARAMETER:
Parameter Description
ord()
The ord() function returns the ASCII value of the first character of a string.
SYNTAX:
PARAMETER:
EXAMPLE:
strtolower()
This function converts the string to lower case.
SYNTAX:
PARAMETER:
Parameter Description
string Required. Specifies the string to convert
EXAMPLE:
<?php
echo strtolower("Hello BCA 3 Sem");
?>
Output:
hello bca 3 sem
strtoupper()
This function converts the string to upper case.
SYNTAX:
strtoupper(<string>);
PARAMETER:
Parameter Description
EXAMPLE:
<?php
echo strtoupper("Hello BCA 3 Sem");
?>
Output:
HELLO BCA 3 SEM
strlen()
This function returns the length of the string.
SYNTAX:
strlen(<string>);
PARAMETER:
Parameter Description
ltrim()
The ltrim() function is used to remove white spaces or other predefined characters
form the left side of the string.
SYNTAX:
ltrim(string_name, char_list)
PARAMETER:
Parameter Description
String Required. Specifies the string to check
"\0" - NULL
"\t" - tab
"\n" - new line
"\x0B" - vertical tab
"\r" - carriage return
" " - ordinary white space
EXAMPLE
<?php
$text1=" Hello BCA 3 Sem";
$text2="\t\n Hello BCA 3 Sem";
echo ltrim($text1)."<br>";
echo ltrim($text2);
?>
OUTPUT:
Hello BCA 3 Sem
Hello BCA 3 Sem
rtrim()
The rtrim() function is used to remove the whitespaces and other predefined
characters from the right side of a string.
SYNTAX:
rtrim(string_name, char_list)
PARAMETER:
Parameter Description
string Required. Specifies the string to check
EXAMPLE:
<?php
$text1="Hello BCA 3 Sem ";
$text2="\t\n Hello BCA 3 Sem";
echo rtrim($text1)."<br>";
echo rtrim($text2,'em');
?>
Output:
Hello BCA 3 Sem
Hello BCA 3 S
trim()
The trim() function is used to remove the white spaces and other predefined
characters from the left and right sides of a string.
SYNTAX:
trim(string_name, char_list)
PARAMETER:
Parameter Description
"\0" - NULL
"\t" - tab
"\n" - new line
"\x0B" - vertical tab
"\r" - carriage return
" " - ordinary white space
EXAMPLE:
<?php
$str = "Hello World!";
echo $str . "<br>";
echo trim($str,"Hed!");
?>
OUTPUT
Hello World!
llo Worl
substr ()
The substr() function used to cut a part of a string from a string, starting at a specified
position.
SYNTAX:
substr(string_name, start_pos, length_to_cut)
PARAMETER:
Parameter Description
start_pos Required.
EXAMPLE:
<?php
$str="Welcome to BCA 3 Sem";
echo substr($str,0,5)."<br>";
echo substr($str,5);
?>
Welco
me to BCA 3 Sem
strcmp ()
The strcmp() function is used to compare two strings.
SYNTAX:
strcmp(string1, string2)
PARAMETER:
Parameter Description
strcasecmp ()
The strcasecmp() function is used to compare two case sensitive strings.
SYNTAX:
strcasecmp(string1, string2)
PARAMETER:
Parameter Description
EXAMPLE:
<?php
$str="Atmiya";
$str1="ATMIYA";
echo $result=strcasecmp($str,$str1)."<br>";
$str2="ATMIYA";
$str3="ATMIYA RJT";
echo $result=strcmp($str2,$str3)."<br>";
echo $result=strcmp($str3,$str2)."<br>";
?>
Output
0 -4 4
strpos()
The strpos() function returns the position of the first occurrence of a string inside
another string.
SYNTAX:
strpos(string,find,start)
PARAMETER:
Parameter Description
EXAMPLE:
<?php
$str="Aatmiya";
$str1="ATMIYA";
echo strpos($str,"a",3)."<br>";
echo strpos($str1,"b");
?>
Output
6
strrpos ()
The strrpos() function finds the position of the last occurrence of a string inside
another string.
SYNTAX:
strrpos(string,find,start)
PARAMETER:
Parameter Description
EXAMPLE:
<?php
$str="Aatmiy";
$str1="ATMIYATA";
echo strrpos($str,"at")."<br>";
echo strrpos($str1,"A",6);
?>
Output
\
1
7
strstr ()
The strstr() function searches for the first occurrence of a string inside another string.
This function returns the rest of the string (from the matching point).
This function is case sensitive.
SYNTAX:
strstr(string,search,before_search)
PARAMETER :
Parameter Description
EXAMPLE:
<?php
$str="Aatmiy";
echo strstr($str,"at“);
?>
atmiy
stristr ()
The stristr() function searches for the first occurrence of a string inside another string.
SYNTAX:
stristr(string,search)
PARAMETER:
Parameter Description
EXAMPLE:
<?php
$str="Aatmiy";
echo stristr($str,"At")."<br>";
?>
Output
atmiy
str_replace ()
The str_replace() function replaces some characters with some other characters in a
string.
SYNTAX:
str_replace(find,replace,string,count)
PARAMETER:
Parameter Description
EXAMPLE:
<?php
$str="Atmiya College";
echo str_replace("College","Rajkot",$str)."<br>";
?>
OUTPUT
Atmiya Rajkot
strrev ()
The strrev() function is used to reverse a string.
SYNTAX:
strrev(main_string)
PARAMETER:
Parameter Description
EXAMPLE:
<?php
$str="Atmiya College";
echo strrev($str);
?>
OUTPUT
egelloC ayimtA
echo ()
The echo () function is used to output the given argument. It can output all types of
data and multiple outputs can be made with only one echo () command.
SYNTAX:
echo (arg1, arg2... )
PARAMETER:
Parameter Description
arg1 Required. Specifies the string to display.
Arg2 Optional
EXAMPLE:
<?php
$abc='We are learning PHP';
$xyz='vsc-project.blogspot.com';
echo "$abc at $xyz <br />";
echo $abc;
echo "<br />"; // creating a new line
echo $xyz;
echo "<br />"; // creating a new line
// Displaying arrays
$fruits=array('fruit1'=>'Apple','fruit2'=>'Banana');
print ()
The print () function is used to output the given argument. It can output all types of
data and multiple outputs can be made with only one print () command.
Print() is not actually a real function, it is a language construct like echo. There are
some difference between the two, echo is marginally faster compare to print as echo
does not return any value. Echo can accept multiple parameters without parentheses
but print can accept only one parameter.
SYNTAX:
print(string $val)
PARAMETER:
Parameter Description
$val Required. The input data.
EXAMPLE:
<?php
print 'One line simple string.<br />';
print 'Two line simple
string example<br />';
print 'Tomorrow I \'ll learn PHP global variables.<br />';
print 'This is a bad command : del c:\\*.* <br />'; ?>
Output
One line simple string.
Two line simple string example
Tomorrow I 'll learn PHP global variables.
This is a bad command : del c:\*.*
explode ()
The explode() function breaks a string into an array.
SYNTAX:
explode(separator,string,limit)
PARAMETER:
Parameter Description
Separator Required. Specifies where to break the string
EXAMPLE:
<?php $str = 'one,two,three,four';
// zero limit
echo "<br>";
print_r(explode(',',$str,0));
// positive limit
echo "<br>";
print_r(explode(',',$str,2));
echo "<br>";
// negative limit
print_r(explode(',',$str,-1)); ?>
Output
Array ( [0] => one,two,three,four )
Array ( [0] => one [1] => two,three,four )
Array ( [0] => one [1] => two [2] => three )
implode ()
The implode() function is used to join array elements with a string.
SYNTAX:
implode (string_join, array_name)
PARAMETER:
Parameter Description
string_join Optional.String-join works as a connector between the array
elements. Default value is a empty string (" ").
EXAMPLE:
<?php
$array_name=array('First Name', 'Middle Name', 'Last Name');
$join_string=implode("-", $array_name);
echo $join_string;
echo '<br>';
$join_string=implode(" ", $array_name);
echo $join_string;
?>
Output
First Name-Middle Name-Last Name
First Name Middle Name Last Name
join ()
The join() function is used to join array elements with a string. The join() function is
similar to implode() function.
SYNTAX:
join (string_join, array_name)
PARAMETER:
Parameter Description
EXAMPLE:
<?php
$array_name=array('1','2','3','4','....');
$join_string=join(",", $array_name);
echo $join_string;
echo '<br>';
$array_name=array('A','B','C','D','E');
$join_string=join("-", $array_name);
echo $join_string; ?>
Output
1,2,3,4,.... A-B-C-D-E
md5 ()
The md5() function is used to calculate the md5 hash (the hash as a 32-character
hexadecimal number ) of a string.
SYNTAX:
md5(input_string, raw_output)
PARAMETER:
Parameter Description
input_string Required.The input string.
EXAMPLE:
<?php
$input_string = 'Good Morning';
echo 'Original string : '.$input_string.'<br>';
echo '16 bit binary format : '.md5($input_string, TRUE).'<br>';
echo '32 bit binary format : '.md5($input_string).'<br>'; ?>
Output
Original string : Good Morning
16 bit binary format : r y†” du?Û£¿ân
32 bit binary format : 72a079088694099d64753fdba3bfe26e
md5 ()
The md5() function is used to calculate the md5 hash (the hash as a 32-character
hexadecimal number ) of a string.
SYNTAX:
md5(input_string, raw_output)
PARAMETER:
Parameter Description
input_string Required.The input string.
EXAMPLE:
<?php
$input_string = 'Good Morning';
echo 'Original string : '.$input_string.'<br>';
echo '16 bit binary format : '.md5($input_string, TRUE).'<br>';
echo '32 bit binary format : '.md5($input_string).'<br>';
?>
Output
Original string : Good Morning
16 bit binary format : r y†” du?Û£¿ân
32 bit binary format : 72a079088694099d64753fdba3bfe26e
str_split ()
The str_split() function is used to convert a string to an array.
SYNTAX:
str_split(string_name, split_length)
PARAMETER:
Parameter Description
string_name Required. The string to be split.
EXAMPLE:
<?php
$string_name='vsc-project.blogstop.com';
print_r(str_split($string_name));
echo '<br>';
print_r(str_split($string_name,4));
echo '<br>'; ?>
Output
Array ( [0] => v [1] => s [2] => c [3] => - [4] => p [5] => r [6] => o [7] => j [8] => e [9] => c
[10] => t [11] => . [12] => b [13] => l [14] => o [15] => g [16] => s [17] => t [18] => o [19]
=> p [20] => . [21] => c [22] => o [23] => m )
str_shuffle
Array ( [0]()
=> vsc- [1] => proj [2] => ect. [3] => blog [4] => stop [5] => .com )
The str_shuffle() function randomly shuffles a string.
SYNTAX:
str_shuffle(string_name)
PARAMETER:
Parameter Description
string_name Required. The input string.
EXAMPLE:
<?php
$string_name='vsc-project.blogspot.com';
$shuffled_string=str_shuffle($string_name);
echo $shuffled_string;
?>
Output
b-..roosclcopvoetsctgmpj
strcspn ()
The strcspn() function is used to get the number of characters that occur between the
start of the main string and the first occurrence of any character listed in the second
string.
SYNTAX:
strcspn(main_string, second_string, start_position, string_length)
PARAMETER:
Parameter Description
main_string Required. The initial string.
EXAMPLE:
<?php
echo strcspn('vsc-project.blogspotcom', '.');
?>
Output
11
strpbrk ()
The strpbrk() function searches a string for any of the specified characters. This
function is case-sensitive.
SYNTAX:
strpbrk(string,charlist)
PARAMETER:
Parameter Description
string Required. Specifies the string to search
EXAMPLE:
<?php
echo strpbrk("Hello world!","W");
echo "<br>";
echo strpbrk("Hello world!","w");
?>
Output
world!
substr_compare ()
The substr_compare() function is used to compare two strings from a given starting
position in the main string.
SYNTAX:
substr_compare(main_string, compare_string, star_pos, length, case_insensitivity)
PARAMETER:
Parameter Description
string Required. Specifies the string to search
EXAMPLE:
<?php
echo strpbrk("Hello world!","W");
echo "<br>";
echo strpbrk("Hello world!","w");
?>
Output
world!
substr_count ()
The substr_count() function is used to count the number of times a substring occurs in
a string. Note that substring is case sensitive.
SYNTAX:
substr_count(string1, string2, nstart, nlength)
PARAMETER:
Parameter Description
string1 Required. The string to search in.
EXAMPLE:
<?php
$string1="Welcome to Pradip Vanparia";
echo substr_count($string1,'co')."<br>";
echo substr_count($string1,'ra',4)."<br>";
echo substr_count($string1,'co',4,4)."<br>";
?>
Output
1
1
0
ucfirst ()
The ucfirst() function is used to convert the first character of a string to uppercase.
SYNTAX:
ucfirst(string_name)
PARAMETER:
Parameter Description
string_name Required. The input string.
EXAMPLE:
ucwords ()
The ucwords() function is used to convert the first character of each word in a string
to uppercase.
SYNTAX:
PARAMETER:
Parameter Description
string_name Required. The input string.
EXAMPLE:
<?php
$string_name='pradip vanparia';
$string_name=ucwords($string_name);
echo $string_name;
?>
Output
Pradip Vanparia
ADVANTAGES
o You can forget to put an addslashes() call around submitted variables and not
have your SQL query fail.
o You can skip adding slashes manually altogether to keep your code less cluttered.
DISADVANTAGES
o Any code using SQL written for PHP 3.x.x has to be examined to remove
addSlashes calls.
o Cases where form submissions are sent back to the browser must have the slashes
removed manually with a call to stripslashes().
o If magic quotes are ever turned off for this server, or the code is moved to a server
where magic quotes isn't enabled your scripts will fail. Or worse, not fail
immediately and only exhibit strange behaviour.
o Any string operations on submitted variables, even simple 'if' statements must
take into account the possiblity of slashes warping in the content.
o Magic quotes breeds developer sloppiness. Escaping variables inserted into an
SQL query (in my opinion) is something that a developer should know and think
about. Not just assume everything is dandy.
EXAMPLE
<?php
echo "Altered Text: ".$_POST['question'];
?>
<form method='post'>
Question: <input type='text' name='question'/><br />
<input type='submit'>
</form>
OUTPUT
Altered Text: Sandy said, \"It\'s a beautiful day outside and I like to use \\\'s.\"
o This simple form will display to you what magic quotes is doing. If you were to enter and
submit the string: Sandy said, "It's a beautiful day outside and I like to use \'s." You
would receive the following output.
o Magic quotes did a number on that string, didn't it? Notice that there is a backslash before
all of those risky characters we talked about earlier. After magic quotes:
o A backslash \ becomes \\
o A quote ' becomes \'
o A double-quote " becomes \"
o Now say that you wanted to remove the escaping that magic quotes puts in, you have two
options: disable magic quotes or strip the backslashes magic quotes adds.
<?php
echo "Removed Slashes: ";
// Remove those slashes
if(get_magic_quotes_gpc())
echo stripslashes($_POST['question']);
else
echo $_POST['question'];
?>
<form method='post'>
Question: <input type='text' name='question'/><br />
<input type='submit'>
</form>
2.10 REUSING CODE AND WRITING FUNCTIONS
Including Files
PHP provides two common constructs for including files in web pages: require and
include. They are basically the same with one minor difference. require throws a fatal
error when it fails; whereas, include only gives a warning. If you need the included file
to continue to process the page, you should use require.
It is important to keep in mind that a PHP tag cannot start in a calling file and continue
in an included file. All PHP code in the included file must be nested in PHP tags.
Using require() or include() enables you to load a file into your PHP file.
One more thing to mention here is that there are two variations to require()
and include(): require_once() and include_once() and you might have guessed what
they mean? They mean that the respective files can only be included or required once!
Consider a situation where you have included a file twice without knowing, you will
get an error. So, if you are cautious, you might want to try require() or include()
because they are faster to execute.
<?php
echo 'Hello there, this is a reusable code <br />';
?>
And now consider another file named: main.php
<?php
echo 'This is the main file for testing stuff <br />';
require('reusablefile.php');
echo 'This is where the script ends at this moment <br />';
?>
Now the outcome: Running the main.php file will return the page shown:
PHP require_once()
require_once() statement can be used to include a php file in another one, when you may need to
include the called file more than once. If it is found that the file has already been included,
calling script is going to ignore further inclusions.
If a.php is a php script calling b.php with require_once() statement, and does not find b.php,
a.php stops executes causing a fatal error.
Syntax:
Require_once(‘name of the calling file with path’);
Example
<?php
echo "today is:".date("Y-m-d");
?>
<?php
require_once('x.php');
require_once('x.php');
?>
PHP Include_once()
The include_once() statement can be used to include a php file in another one, when you may
need to include the called file more than once. If it is found that the file has already been
included, calling script is going to ignore further inclusions.
If a.php is a php script calling b.php with include_once() statement, and does not find b.php,
a.php executes with a warning, excluding the part of the code written within b.php.
Syntax:
Include_once(‘name of the called file with path’);
Example:
<?php
echo "today is:".date("Y-m-d");
?>
<?php
include_once('x.php');
include_once('x.php');
?>
The purpose of these PHP configuration directives is to execute a specified file before or after any PHP
script stored on your computer/server.
This is similar to using a require() function at the beginning or end of a PHP script. The
auto_prepend_file directive parses a file before executing any PHP file, so this can be extremely useful if
you have a set of user defined PHP functions which need to be called in all PHP scripts.
Below example explains the scenario, first lets created two functions for addition and
subtraction.
<?php
function add($a,$b)
return ($a+$b);
function subtract($a,$b)
return($a-$b);
}
?>
Save the code in a separate file myfunctions.php. Now edit the php.ini file, this file is located
in /etc/php.ini in Linux, C:\PHP\php.ini in Windows, C:\wamp\bin\php\php.ini in WAMP and
C:\xampp\php\php.ini in XAMPP. Find and edit the following line
If you’re editing a custom php.ini file you should manually add this line. The location you
specify should be an absolute location like /var/www/html/myfunction.php windows users
should use forward slash in their file path C:/wamp/www/myfunction.php
Now all you need to do is to call this function in any PHP script you code. The usage of
auto_append_file directive is also similar; the only difference is the file specified is parsed
AFTER a PHP script executes.
The way in which these configuration directives work might make you think you can use these
for adding a header and footer all pages, if you plan to do so remember that while execution the
files are merely prepended and appended to the PHP file requested hence you should code in
such a way that the header file has the just opening tag for <html>, entire contents of the <head>
tag, the opening tag for <body> then the header content. Then the footer file will contain the
footer content, closing </body> tag and closing </html> tag in that order.
So the main file you code should only have the content that comes after the header contents and
before the footer contents.
So it is best you use the auto_prepend_file and auto_append_file directives for including scripts
that don’t generate an output viewable on the browser like visitor tracking scripts, user
definitions of functions.
2.11 USER FUNCTIONS
Besides the built-in PHP functions, we can create our own functions.
Syntax
function function-name()
statement 1 :
statement 2 :
statement 3 :
......
Syntax
function myfunct()
{
do this;
do that;
Example
<?php
function myfunction()
{
echo “Good Morning”;
}
myfunction();
?>
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 seperate them with a comma.
There are three different ways of passing arguments to a function, arguments by value (the
default), passing by reference, and default argument values.
Example
In PHP values are returned by return statement. The return values must be specified in the
variable. If the statement is called within a function the function is terminated
immediately and passes control back to previous position from which it was called.
Example
By default the function arguments are passed by value. If you want to allow a function to
change its arguments, you must pass the arguments by reference. To pass an argument to
a function as reference, simply add an ampersand (&) character before the variable name.
<?php
function cube(&$x)
$x=$x*$x*$x;
result=5;
cube($result);
echo $result;
?>
Output
125
The following example shows how to use a default parameter. If we call the function setHeight()
without arguments it takes the default value as argument:
Example
<?php
function setHeight($minheight = 50)
{
echo "The height is : $minheight <br>";
}
setHeight(350);
setHeight(); // will use the default value of 50
setHeight(135);
setHeight(80);
?>
Output:
In PHP, variables declared outside of functions are not available by default inside of functions.
The following code illustrates this:
Example
<html>
<head>
<title>Local Variables</title>
</head>
<body>
<?php
$a = 10;
$b = 5;
function incrNumBy()
{
$a += $b;
}
incrNumBy(); //results in two warnings as $a and $b are
//undefined in the function scope
echo $a; //outputs 10 to the browser
?>
</body>
</html>
To make the variables available to the function, they must be declared within the function as
global variables using the global keyword.
Example
<html>
<head>
<title>Global Variables</title>
</head>
<body>
<?php
$a = 10;
$b = 5;
function incrNumBy()
{
global $a,$b;
$a += $b;
}
incrNumBy();
echo $a; //outputs 15 to the browser
?>
</body>
</html>
By default, variables are passed to functions by value, meaning that the function's receiving
variables get copies of the values received rather than pointers to them. If the receiving variables
are modified, the passed variables remain unaffected. The following code illustrates this.
Example
<html>
<head>
<title>By Value</title>
</head>
<body>
<?php
$a = 10;
$b = 5;
function incrNumBy($num,$incr)
{
$num += $incr;
}
incrNumBy($a,$b);
echo $a; //outputs 10 to the browser
?>
</body>
</html>
The above code outputs "10" to the browser. Although $num was incremented by 5, $a was
unaffected by the function call. To pass a variable by reference, put an ampersand (&) before the
parameter in the function definition.
Example
<html>
<head>
<title>By Reference</title>
</head>
<body>
<?php
$a = 10;
$b = 5;
function incrNumBy(&$num,$incr)
{
$num += $incr;
}
incrNumBy($a,$b);
echo $a; //outputs 15 to the browser
?>
</body>
</html>
This time the function outputs "15" because $num references the variable $a itself. So, any
change in $num will affect $a.
Although these tasks are all separate, some are dependent on others. For example, if errors are
found when the form is submitted, it is nice to re-output the form, but the HTML code may be
different from the original form as you will likely want to include error messages and also echo
the values that the user entered. It's very easy to get your code all tangled up resulting in what is
known as spaghetti code. We will now examine one approach for organizing code using
functions and includes making it easier to maintain.
Code Organization
Application Flow
1. When the user first visits, she is presented with a form to fill out.
2. If she fills out the form...
o Correctly
She is presented with another form to confirm her entries.
After confirming her entries, the data will be processed (e.g, entered into a
database or emailed to someone).
o Incorrectly
She is presented with the same form with her entries in tact and
appropriate error messages displayed.
Application Files
Example
ReusingCode/Demos/Includes/init.php
<?php
$showForm = true;
$mgrEntries = array();
$mgrEntries[1]='Nancy Davolio';
$mgrEntries[2]='Andrew Fuller';
$mgrEntries[3]='Janet Leverling';
$mgrEntries[4]='Margaret Peacock';
$mgrEntries[5]='Steven Buchanan';
$mgrEntries[6]='Michael Suyama';
$mgrEntries[7]='Robert King';
$mgrEntries[8]='Laura Callahan';
$mgrEntries[9]='Anne Dodsworth';
$errors = array();
$dbEntries = array( 'FirstName'=>',
'LastName'=>',
'Email'=>',
'Title'=>',
'TitleOfCourtesy'=>',
'Address'=>',
'City'=>',
'Region'=>',
'PostalCode'=>',
'Country'=>',
'HomePhone'=>',
'Extension'=>',
'Notes'=>',
'ReportsTo'=>',
'Password'=>',
'Email'=>',
'BirthMonth'=>1,
'BirthDay'=>1,
'BirthYear'=>date('Y'),
'HireMonth'=>1,
'HireDay'=>1,
'HireYear'=>date('Y'));
$browserEntries = array();
?>
This file sets several variables used throughout the application.
Example
ReusingCode/Demos/AddEmployee.php
<?php
require 'Includes/fnFormValidation.php';
require 'Includes/fnFormPresentation.php';
require 'Includes/fnStrings.php';
require 'Includes/fnDates.php';
require 'Includes/init.php';
?>
<html>
<head>
<title>Add Employee</title>
<style type="text/css">
.Error {color:red; font-size:smaller;}
</style>
</head>
<body>
<?php
require 'Includes/Header.php';
if (array_key_exists('Submitted',$_POST))
{
require 'Includes/ProcessEmployee.php';
}
elseif (array_key_exists('Confirmed',$_POST))
{
require 'Includes/InsertEmployee.php';
}
if ($showForm)
{
require 'Includes/EmployeeForm.php';
}
require 'Includes/Footer.php';
?>
</body>
</html>
The code is relatively easy to read. Things to note:
1. At the very top, we include several files we will need for the application.
2. In the body, we include:
o our header and footer files.
o code that checks which, if either, form was submitted and includes the appropriate
file.
o code that checks whether or not to show the main form. The form will be shown
if:
it has not yet been submitted.
it has been submitted with errors.
Example
ReusingCode/Demos/Includes/fnDates.php
<?php
/********* DATE FUNCTIONS *********/
/*
Function Name: monthAsString
Arguments: $m
Returns:
month as string
*/
function monthAsString($m)
{
$months = array();
$months[] = 'January';
$months[] = 'February';
$months[] = 'March';
$months[] = 'April';
$months[] = 'May';
$months[] = 'June';
$months[] = 'July';
$months[] = 'August';
$months[] = 'September';
$months[] = 'October';
$months[] = 'November';
$months[] = 'December';
return $months[$m-1];
}
?>
This file includes a simple function for getting the name of a month (e.g, February) given the
month number (e.g, 2).
Example
ReusingCode/Demos/Includes/fnStrings.php
<?php
/********** STRING FUNCTIONS *********/
/*
Function Name: browserString
Arguments: $string
Returns:
trimmed and escaped string for browser output
*/
function browserString($string)
{
return nl2br(trim(htmlentities($string)));
}
/*
Function Name: dbString
Arguments: $string
Returns:
trimmed and escaped string for database entry
*/
function dbString($email)
{
if (get_magic_quotes_gpc())
{
return trim ($email);
}
else
{
return addslashes(trim($email));
}
}
?>
This file includes functions for cleaning up strings for browser and database output.
Example
ReusingCode/Demos/Includes/fnFormPresentation.php
<?php
/********* FORM PRESENTATION FUNCTIONS *********/
/*
Function Name: textEntry
Arguments: $display,$name,$entries,$errors,$size?
Returns:
one table row as string
*/
function textEntry($display,$name,$entries,$errors,$size=15)
{
$returnVal = "
<tr>
<td>$display:</td>
<td>
<input type='text' name='$name' size='$size'
value=\"" . browserString($entries[$name]) . "\">";
if (array_key_exists($name,$errors))
{
$returnVal .= '<span class="Error" style="white-space:nowrap">* ' .
$errors[$name] .
'</span>';
}
$returnVal .= "</td>
</tr>";
return $returnVal;
}
/*
Function Name: pwEntry
Arguments: $pw1,$pw2,$errors,$size?
Returns:
table rows as string
*/
function pwEntry($pw1,$pw2,$errors,$size=10)
{
$returnVal = "
<tr>
<td>Password:</td>
<td>
<input type='password' name='$pw1' size='$size'>
</td>
</tr>
<tr>
<td>Repeat Password:</td>
<td>
<input type='password' name='$pw2' size='$size'>
</td>
</tr>";
if (array_key_exists('Password',$errors))
{
$returnVal .= addErrorRow('Password',$errors);
}
return $returnVal;
}
/*
Function Name: textAreaEntry
Arguments: $display,$name,$entries,$errors,$cols?,$rows?
Returns:
table rows as string
*/
function textAreaEntry($display,$name,$entries,$errors,$cols=45,$rows=5)
{
$returnVal = "
<tr>
<td colspan='2'>$display:</td>
</tr>
<tr>
<td colspan='2'>
<textarea name='$name' cols='$cols' rows='$rows'>";
$returnVal .= $entries[$name];
$returnVal .= "</textarea>
</td>
</tr>";
if (array_key_exists($name,$errors))
{
$returnVal .= addErrorRow($name,$errors);
}
return $returnVal;
}
/*
Function Name: radioEntry
Arguments: $display,$name,$entries,$errors,$values
Returns:
table rows as string
*/
function radioEntry($display,$name,$entries,$errors,$values)
{
$returnVal = "
<tr>
<td>$display:</td>
<td>$name</td>
</tr>";
return $returnVal;
}
/*
Function Name: selectEntry
Arguments: $display,$name,$entries,$errors,$selected?
Returns:
table rows as string
*/
function selectEntry($display,$name,$options,$errors,$selected=0)
{
$returnVal = "<tr>
<td>$display:</td>
<td>
<select name='$name'>
<option value='0'>Choose one...</option>";
$returnVal .= "</select>
</td>
</tr>";
return $returnVal;
}
/*
Function Name: selectDateEntry
Arguments: $display,$namePre,$month,$day,$year
Returns:
table rows as string
*/
function selectDateEntry($display,$namePre,$month,$day,$year,$errors)
{
$returnVal = "<tr>
<td>$display:</td>
<td>
<select name='$namePre" . "Month'>";
for ($i=1; $i<=12; $i++)
{
if ($i == $month)
{
$returnVal .= "<option value='$i' selected>";
}
else
{
$returnVal .= "<option value='$i'>";
}
$returnVal .= monthAsString($i) . '</option>';
}
$returnVal .= "</select>
<select name='$namePre" . "Day'>";
for ($i=1; $i<=31; $i++)
{
if ($i == $day)
{
$returnVal .= "<option value='$i' selected>";
}
else
{
$returnVal .= "<option value='$i'>";
}
$returnVal .= "$i</option>";
}
$returnVal .= "</select>
<select name='$namePre" . "Year'>";
for ($i=date('Y'); $i>=1900; $i=$i-1)
{
if ($i == $year)
{
$returnVal .= "<option value='$i' selected>";
}
else
{
$returnVal .= "<option value='$i'>$i</option>";
}
$returnVal .= "$i</option>";
}
$returnVal .= '</select>
</td>
</tr>';
if (array_key_exists($namePre . 'Date',$errors))
{
$returnVal .= addErrorRow($namePre . 'Date',$errors);
}
return $returnVal;
}
/*
Function Name: addErrorRow
Arguments: $name
Returns:
table row as string
*/
function addErrorRow($name,$errors)
{
$errorRow = '<tr><td colspan="2" class="Error">* ' .
$errors[$name] .
'</td></tr>';
return $errorRow;
}
?>
This file contains functions for presenting form entries. Several of these functions are complete,
but there are a couple that need to be finished. This will be part of the next exercise.
Example
ReusingCode/Demos/Includes/fnFormValidation.php
<?php
/********* FORM VALIDATION FUNCTIONS *********/
/*
Function Name: checkLength
Arguments: $text,$min?,$max?,$trim?
Returns:
false if $text has fewer than $min characters
false if $text has more than $max characters
true otherwise
*/
function checkLength($text,$min=1,$max=10000,$trim=true)
{
if ($trim)
{
$text = trim($text);
}
if (strlen($text) < $min || strlen($text) > $max)
{
return false;
}
return true;
}
/*
Function Name: checkEmail
Arguments: $email
Returns:
false if $email has fewer than 6 characters
false if $email does not contain @ symbol
false if $email does not contain a period (.)
false if the last @ symbol comes after the last period (.)
true otherwise
*/
function checkEmail($email)
{
return true;
}
/*
Function Name: checkPassword
Arguments: $pw1,$pw2
Returns:
false if $pw1 has fewer than 6 characters
false if $pw1 has more than 12 characters
false if $pw1 and $pw2 do not match
true otherwise
*/
function checkPassword($pw1,$pw2)
{
return true;
}
?>
This file contains functions for validating form entries. One of these functions is complete, but
there are a couple that needs to be finished. This will also be part of the next exercise.
Example
ReusingCode/Demos/Includes/EmployeeForm.php
<h1 align="center">Add Employee</h1>
<form method="post" action="AddEmployee.php">
<input type="hidden" name="Submitted" value="true">
<table align="center" border="1" width="500">
<?php
echo textEntry('First name','FirstName',$dbEntries,$errors,15);
echo textEntry('Last name','LastName',$dbEntries,$errors,15);
echo textEntry('Email','Email',$dbEntries,$errors,25);
echo textEntry('Title','Title',$dbEntries,$errors,30);
echo radioEntry('Title of Courtesy','TitleOfCourtesy',
$dbEntries,$errors,
array('Dr.','Mr.','Mrs.','Ms.'));
echo selectDateEntry('Birth date','Birth',
$dbEntries['BirthMonth'],
$dbEntries['BirthDay'],
$dbEntries['BirthYear'],
$errors);
echo selectDateEntry('Hire date','Hire',
$dbEntries['HireMonth'],
$dbEntries['HireDay'],
$dbEntries['HireYear'],
$errors);
echo textEntry('Address','Address',$dbEntries,$errors,50);
echo textEntry('City','City',$dbEntries,$errors,30);
echo textEntry('Region','Region',$dbEntries,$errors,2);
echo textEntry('Postal Code','PostalCode',$dbEntries,$errors,10);
echo textEntry('Country','Country',$dbEntries,$errors,5);
echo textEntry('Home phone','HomePhone',$dbEntries,$errors,15);
echo textEntry('Extension','Extension',$dbEntries,$errors,5);
echo textAreaEntry('Notes','Notes',$dbEntries,$errors,50,3);
echo selectEntry('Manager','ReportsTo',$mgrEntries,
$errors,
$dbEntries['ReportsTo']);
echo pwEntry('Password1','Password2',$errors,10);
?>
<tr>
<td colspan="2"><input type="submit" value="Add Employee"></td>
</tr>
</table>
</form>
This file creates the entry form. Notice that it creates entry rows through calls to functions in the
fnFormPresentation.php file. This allows us to easily incorporate error handling and error
messages into the form entries without making the HTML form itself difficult to maintain.
Example
ReusingCode/Demos/Includes/ProcessEmployee.php
<?php
$dbEntries['FirstName'] = dbString($_POST['FirstName']);
$dbEntries['LastName'] = dbString($_POST['LastName']);
$dbEntries['Title'] = ucwords(dbString($_POST['Title']));
$dbEntries['Address'] = dbString($_POST['Address']);
$dbEntries['City'] = dbString($_POST['City']);
$dbEntries['Region'] = dbString($_POST['Region']);
$dbEntries['PostalCode'] = dbString($_POST['PostalCode']);
$dbEntries['Country'] = dbString($_POST['Country']);
$dbEntries['HomePhone'] = dbString($_POST['HomePhone']);
$dbEntries['Extension'] = dbString($_POST['Extension']);
$dbEntries['Notes'] = dbString($_POST['Notes']);
$dbEntries['ReportsTo'] = $_POST['ReportsTo'];
$dbEntries['Password'] = dbString($_POST['Password1']);
$dbEntries['Email'] = dbString($_POST['Email']);
$dbEntries['BirthMonth'] = dbString($_POST['BirthMonth']);
$dbEntries['BirthDay'] = dbString($_POST['BirthDay']);
$dbEntries['BirthYear'] = dbString($_POST['BirthYear']);
$dbEntries['HireMonth'] = dbString($_POST['HireMonth']);
$dbEntries['HireDay'] = dbString($_POST['HireDay']);
$dbEntries['HireYear'] = dbString($_POST['HireYear']);
if (!checkLength($_POST['FirstName']))
{
$errors['FirstName'] = 'First name omitted.';
}
else
{
$browserEntries['FirstName'] = browserString($_POST['FirstName']);
}
if (!checkLength($_POST['LastName']))
{
$errors['LastName'] = 'Last name omitted.';
}
else
{
$browserEntries['LastName'] = browserString($_POST['LastName']);
}
if (!checkLength($_POST['Title']))
{
$errors['Title'] = 'Title omitted.';
}
else
{
$browserEntries['Title'] = ucwords(browserString($_POST['Title']));
}
if ( array_key_exists('TitleOfCourtesy',$_POST) )
{
$browserEntries['TitleOfCourtesy'] =
browserString($_POST['TitleOfCourtesy']);
$dbEntries['TitleOfCourtesy'] = dbString($_POST['TitleOfCourtesy']);
}
else
{
$errors['TitleOfCourtesy'] = 'Title of Courtesy not selected.';
}
if (!checkdate($_POST['BirthMonth'],$_POST['BirthDay'],$_POST['BirthYear']))
{
$errors['BirthDate'] = 'Birth date is not a valid date.';
}
if (!checkdate($_POST['HireMonth'],$_POST['HireDay'],$_POST['HireYear']))
{
$errors['HireDate'] = 'Hire date is not a valid date.';
}
if (!checkLength($_POST['Address'],5,200))
{
$errors['Address'] = 'Address omitted.';
}
else
{
$browserEntries['Address'] = browserString($_POST['Address']);
}
if (!checkLength($_POST['City'],1,100))
{
$errors['City'] = 'City omitted.';
}
else
{
$browserEntries['City'] = browserString($_POST['City']);
}
if (!checkLength($_POST['PostalCode']))
{
$errors['PostalCode'] = 'Postal Code omitted.';
}
else
{
$browserEntries['PostalCode'] = browserString($_POST['PostalCode']);
}
if (!checkLength($_POST['Country']))
{
$errors['Country'] = 'Country omitted.';
}
else
{
$browserEntries['Country'] = browserString($_POST['Country']);
}
if (!checkLength($_POST['HomePhone'],10,15))
{
$errors['HomePhone'] = 'Home phone must be between 10 and 15 characters.';
}
else
{
$browserEntries['HomePhone'] = browserString($_POST['HomePhone']);
}
if (!checkLength($_POST['Extension'],3,5))
{
$errors['Extension'] = 'Extension must be between 3 and 5 characters.';
}
else
{
$browserEntries['Extension'] = browserString($_POST['Extension']);
}
if (!checkLength($_POST['Notes'],0,100))
{
$errors['Notes'] = 'Notes must be fewer than 100 characters:<br>
<span style="color:blue; font-weight:normal">' .
browserString(substr($_POST['Notes'],0,100)) .
'</span><span style="color:red; font-weight:normal;
text-decoration:line-through;">' .
browserString(substr($_POST['Notes'],100)) .
'</span>';
}
else
{
$browserEntries['Notes'] = browserString($_POST['Notes']);
}
if ($_POST['ReportsTo'] == 0)
{
$errors['ReportsTo'] = 'Manager not selected.';
}
else
{
$browserEntries['ReportsTo'] = $_POST['ReportsTo'];
}
if ( !checkPassword($_POST['Password1'],$_POST['Password2']) )
{
$errors['Password'] = 'Passwords do not match or are not the right length.';
}
else
{
$browserEntries['Password'] = browserString($_POST['Password1']);
}
if ( !checkEmail($_POST['Email']) )
{
$errors['Email'] = 'Email is invalid.';
}
else
{
$browserEntries['Email'] = browserString($_POST['Email']);
}
?>
<?php
if (!count($errors))
{
$showForm = false;
?>
<form method="post" action="AddEmployee.php">
<input type="hidden" name="Confirmed" value="true">
<?php
echo '<h2>Confirm Entries</h2>';
echo '<ol>';
foreach ($browserEntries as $key=>$entry)
{
if ($key=='ReportsTo')
{
echo "<li><b>Manager:</b> $mgrEntries[$entry]</li>";
}
else
{
echo "<li><b>$key:</b> $entry</li>";
}
}
echo '</ol>';
This file contains code for processing the form entries. It makes use of functions in the
fnFormValidation.php file for validating entries. If no errors are found, it sets the boolean
$showForm to false, so that the original form will not be displayed and it outputs all the entries
(made browser-safe) to the browser for confirmation.
If errors are found, it adds them to the $errors array, which is passed into the form presentation
functions, so that they can return code for displaying the errors. If there are errors, the boolean
$showForm is left as true, so that the original form is redisplayed.
Lesson Goals
Retrieve and safely display records from a database.
Insert new records into a database.
Update existing records in a database.
mysqli() Overview
New in PHP5 is the mysqli library, which works with MySQL versions 4.1.3 and above and
takes advantage of a new faster connection protocol in MySQL. The mysqli library provides two
interfaces: an object-oriented interface and a procedural interface. The following two scripts use
the two different interfaces to accomplish the same result.
Example
ManagingData/Demos/SimpleQuery-OO.php
<html>
<head>
<title>Simple Query - OO</title>
</head>
<body>
<?php
@$db = new mysqli('localhost','root','pwdpwd','Northwind');
if (mysqli_connect_errno())
{
echo 'Cannot connect to database: ' . mysqli_connect_error();
}
else
{
$query = 'SELECT * FROM Employees';
$result = $db->query($query);
$numResults = $result->num_rows;
Example
ManagingData/Demos/SimpleQuery-Procedural.php
<html>
<head>
<title>Simple Query - Procedural</title>
</head>
<body>
<?php
@$db = mysqli_connect('localhost','root','pwdpwd','Northwind');
if (mysqli_connect_errno())
{
echo 'Cannot connect to database: ' . mysqli_connect_error();
}
else
{
$query = 'SELECT * FROM Employees';
$result = mysqli_query($db,$query);
$numResults = mysqli_num_rows($result);
o Procedural:
$result->free();
$db->close();
o Procedural:
mysqli_free_result($result);
mysqli_close($db);
Query Functions
Object-oriented Procedural Description
Fetch Functions
mysql_connect()
It is used to Open a connection to a MySQL Server.
This function returns the connection on success, or FALSE and an error on failure. You
can hide the error output by adding an '@' in front of the function name.
SYNTAX
mysql_connect([host][, user_name][, password]);
PARAMETER
Name Description
Host Optional. The MySql server. You can use hostname, ip address,
hostname:portname, ip address:portname as server. Default is
localhost:3306.
Username Optional.The username. Default value is defined by
mysql.default_user.
password Optional. The password of the user. Default value is defined by
mysql.default_password.
EXAMPLE
<?php
$continued = mysql_connect("localhost","root","");
if ($continued)
{ echo ("Connection is succeed"); }
else
{ echo ("Connection is fail"); } ?>
Output Connection is succeed
mysql_close()
The mysql_close() function closes a non-persistent MySQL connection.
This function returns TRUE on success, or FALSE on failure.
SYNTAX
mysql_close(connection)
PARAMETER
Parameter Description
EXAMPLE
<?php
$con=mysql_connect('localhost', 'root', '');
if ($con)
{ echo "connected successfully"; }
mysql_close($con);
if ($con)
{ echo "<br />disconnected successfully"; } ?>
Output connected successfully
disconnected successfully
mysql_error()
The mysql_error() function is used to get the error message from the last MySQL
operation.
SYNTAX
mysql_error(connection)
PARAMETER
Parameter Description
Connection Optional. Specifies the MySQL connection. If not specified, the last
connection opened by mysql_connect() or mysql_pconnect() is used.
EXAMPLE
<?php
$con = mysql_connect("localhost", "root", "");
if (!mysql_select_db("tutorials", $con))
{ echo mysql_errno($con) . ": " . mysql_error($con). "<br />"; }
mysql_select_db("tutorials", $con);
if (!mysql_query("select * from test", $con))
{ echo mysql_errno($con) . ": " . mysql_error($con) . "<br />"; }
?>
msyql_errno()
The mysql_errno() function returns the error number of the last MySQL operation.
This function returns 0 (zero) if no error has occurred.
SYNTAX
mysql_errno(connection)
PARAMETER
Parameter Description
Connection Optional. Specifies the MySQL connection. If not specified, the last
connection opened by mysql_connect() or mysql_pconnect() is used.
EXAMPLE
<?php
$con = mysql_connect("localhost", "root", "");
if (!mysql_select_db("tutorials", $con))
{ echo mysql_errno($con) . ": " . mysql_error($con). "<br />"; }
mysql_select_db("tutorials", $con);
if (!mysql_query("select * from test", $con))
{ echo mysql_errno($con) . ": " . mysql_error($con) . "<br />"; } ?>
Output -> 1049: Unknown database 'tutorials'
1046: No database selected
mysql_select_db()
The mysql_select_db() function sets the current active database on the server which is
associated with the specified connection.
SYNTAX:
mysql_select_db(database,connection)
PARAMETER
Parameter Description
EXAMPLE
<?php
$con = mysql_connect("localhost","root","");
$selected_db = mysql_select_db("test");
if (!$selected_db)
{ die ('Database not selected : ' . mysql_error()); }
else
{ echo "Database Selected"; } ?>
Output
Database Selected
mysql_query()
The mysql_query() is used to execute query on the default database.
This function returns the query handle for SELECT queries, TRUE/FALSE for other
queries, or FALSE on failure.
SYNTAX
mysql_query(query,connection)
PARAMETER
Parameter Description
Query Required. Specifies the SQL query to send (should not end with a
semicolon)
Connection Optional. Specifies the MySQL connection. If not specified, the last
connection opened by mysql_connect() or mysql_pconnect() is used.
EXAMPLE
<?php
$con = mysql_connect("localhost","root","");
if (!$con)
{ die('Could not connect: ' . mysql_error()); }
$sql = "SELECT * FROM demo";
mysql_query($sql,$con);
// some code
mysql_close($con); ?>
mysql_fetch_array()
The mysql_fetch_array() is used to retrieve a row of data as an array from a MySQL
result handle.
This function gets a row from the mysql_query() function and returns an array on
success, or FALSE on failure or when there are no more rows.
SYNTAX
mysql_fetch_array(data,array_type)
PARAMETER
Parameter Description
data Required. Specifies which data pointer to use. The data pointer is the
result from the mysql_query() function
array_type Optional. Specifies what kind of array to return.
Possible values:
MYSQL_ASSOC - Associative array
MYSQL_NUM - Numeric array
MYSQL_BOTH - Default.
Both associative and numeric array
EXAMPLE
<?php
$con = mysql_connect("localhost", "root", "") or die("Could not connect: " .
mysql_error());
mysql_select_db("test");
$result = mysql_query("select * from demo");
echo "<table border='1' style='border-collapse: collapse'>";
echo "<th>Id</th><th>Name</th><th>Pincode</th>";
while ($row = mysql_fetch_array($result))
{ echo "<tr>";
echo "<td>".$row['id']."</td>";
echo "<td>".$row['stdname']."</td>";
echo "<td>".$row['pincode']."</td>";
echo "</tr>"; } ?>
Output
mysql_num_rows()
The mysql_num_rows() is used to get the number of rows in a MySQL result handle.
SYNTAX:
mysql_num_rows(data)
PARAMETER
Paramete Description
r
data Required. Specifies which data pointer to use. The data pointer is the
result from the mysql_query() function
EXAMPLE
<?php
$con = mysql_connect("localhost", "root", "");
$selectdb = mysql_select_db("test",$con);
$result = mysql_query("select * from demo");
$number_of_rows = mysql_num_rows($result);
echo "Number of rows fetched are : ". $number_of_rows;
?>
Output
Number of rows fetched are : 2
mysql_affected_rows()
The mysql_affected_rows() function returns the number of affected rows in the previous MySQL
operation.
This function returns the number of affected rows on success, or -1 if the last operation
failed.
SYNTAX
mysql_affected_rows(connection)
PARAMETER
Parameter Description
Connectio Optional. Specifies the MySQL connection. If not specified, the last
n connection opened by mysql_connect() or mysql_pconnect() is used.
EXAMPLE
<?php
$con=mysql_connect('localhost', 'root', '');
mysql_select_db("test")or die("cannot select DB");
mysql_query("insert into demo(id,stdname,pincode) values(1,'html',123456)");
mysql_query("insert into demo(id,stdname,pincode) values(2,'html',123456)");
echo "Inserted records:".mysql_affected_rows();
echo "<br />It shows 1 if the new rows are inserted"; ?>
Output
Inserted records:1
It shows 1 if the new rows are inserted
Other Example
mysql_query("DELETE FROM demo WHERE id='1'");
$rc = mysql_affected_rows();
echo "Records deleted: " . $rc;
Output Records deleted: 1
mysql_fetch_assoc()
The mysql_fetch_assoc() used to retrieve a row of data as an associative array from a
MySQL result handle.
This function gets a row from the mysql_query() function and returns an array on
success, or FALSE on failure or when there are no more rows.
SYNTAX
mysql_fetch_assoc(data)
PARAMETER
Paramete Description
r
data Required. Specifies which data pointer to use. The data pointer is the
result from the mysql_query() function
EXAMPLE
<?php
$con = mysql_connect("localhost", "root", "") or die("Could not connect: " .
mysql_error());
mysql_select_db("test");
$result = mysql_query("select * from demo");
echo "<table border='1' style='border-collapse: collapse'>";
echo "<th>Id</th><th>Name</th><th>Pincode</th>";
while ($row = mysql_fetch_assoc($result))
{
echo"<tr><td>".$row['id']."</td><td>".$row['stdname']."</td><td>".
$row['pincode']."</td></tr>";
}
echo "</table>";
mysql_fetch_field()
The mysql_fetch_field() function is used to get the column information of a field from a
result handle.
o POSSIBLE RETURN VALUES:
name - Field name
table - The table the field belongs to
def - Default value for the field
max_length - Maximum field length
not_null - 1 if the field cannot be NULL
primary_key - 1 if the field is a primary key
unique_key - 1 if the field is a unique key
multiple_key - 1 if the field is a non-unique key
numeric - 1 if the field is numeric
blob - 1 if the field is a BLOB
type - Field type
unsigned - 1 if the field is unsigned
zerofill - 1 if the field is zero-filled
SYNTAX
PARAMETER
Parameter Description
data Required. Specifies which data pointer to use. The data pointer is the
result from the mysql_query() function
field_offse Optional. Specifies which field to start returning. 0 indicates the first
t field. If this parameter is not set, it will retrieve the next field
EXAMPLE
<?php
$con = mysql_connect("localhost", "root", "");
if (!$con)
{ die('Could not connect: ' . mysql_error()); }
$db_selected = mysql_select_db("test",$con);
$sql = "SELECT * from demo";
$result = mysql_query($sql,$con);
while ($property = mysql_fetch_field($result))
{
echo "Field name: " . $property->name . "<br />";
echo "Table name: " . $property->table . "<br />";
echo "Default value: " . $property->def . "<br />";
echo "Max length: " . $property->max_length . "<br />";
echo "Not NULL: " . $property->not_null . "<br />";
echo "Primary Key: " . $property->primary_key . "<br />";
echo "Unique Key: " . $property->unique_key . "<br />";
echo "Mutliple Key: " . $property->multiple_key . "<br />";
echo "Numeric Field: " . $property->numeric . "<br />";
echo "BLOB: " . $property->blob . "<br />";
echo "Field Type: " . $property->type . "<br />";
echo "Unsigned: " . $property->unsigned . "<br />";
echo "Zero-filled: " . $property->zerofill . "<br /><br />"; }
mysql_close($con); ?>
mysql_fetch_object()
The mysql_fetch_object() function returns a row from a recordset as an object.
This function gets a row from the mysql_query() function and returns an object on
success, or FALSE on failure or when there are no more rows.
SYNTAX
mysql_fetch_object(data)
PARAMETER
Paramete Description
r
Data Required. Specifies which data pointer to use. The data pointer is the
result from the mysql_query() function
EXAMPLE
<?php
mysql_connect("localhost", "root", "");
mysql_select_db("test");
$result = mysql_query("select * from demo");
while ($row = mysql_fetch_object($result))
{ echo $row->stdname."<br />"; }
mysql_free_result($result); ?>
Output
project
mysql_fetch_row()
The mysql_fetch_row() function returns a row from a recordset as a numeric array.
This function gets a row from the mysql_query() function and returns an array on
success, or FALSE on failure or when there are no more rows.
SYNTAX
mysql_fetch_row(data)
PARAMETER
Parameter Description
data Required. Specifies which data pointer to use. The data pointer is the
result from the mysql_query() function
EXAMPLE
<?php
$con = mysql_connect("localhost", "root", "");
if (!$con)
{ die('Could not connect: ' . mysql_error()); }
$db_selected = mysql_select_db("test",$con);
$sql = "SELECT * from demo WHERE name='pradip'";
$result = mysql_query($sql,$con);
print_r(mysql_fetch_row($result));
mysql_close($con); ?>
Output
Array ( [0] => 1 [1] => pradip [2] => rajkot )
mysql_insert_id()
The mysql_insert_id() function returns the AUTO_INCREMENT ID generated from the
previous INSERT operation.
This function returns 0 if the previous operation does not generate an
AUTO_INCREMENT ID, or FALSE on MySQL connection failure.
SYNTAX
mysql_insert_id(connection)
PARAMETER
Paramete Description
r
connection Optional. Specifies the MySQL connection. If not specified, the last
connection opened by mysql_connect() or mysql_pconnect() is used.
EXAMPLE
<?php
$con = mysql_connect("localhost", "root", "");
$selectdb = mysql_select_db("test",$con);
mysql_query("INSERT INTO demo(id, name,city) values (3,'vsc-
project','rajkot')");
echo "Last inserted record has id : ". mysql_insert_id();
?>
Output
Last inserted record has id : 3
mysql_num_fields()
The mysql_num_fields() function returns the number of fields in a recordset.
SYNTAX
mysql_num_fields(data)
PARAMETER
Paramete Description
r
data Required. Specifies which data pointer to use. The data pointer is the
result from the mysql_query() function
EXAMPLE
<?php
$con = mysql_connect("localhost", "root", "");
$selectdb = mysql_select_db("test",$con);
$result = mysql_query("select id,name,city from demo where id = '1'");
echo mysql_num_fields($result);
?>
Output
3
mysql_result()
The mysql_result() function returns the value of a field in a recordset.
This function returns the field value on success, or FALSE on failure.
SYNTAX
mysql_result(data,row,field)
PARAMETER
Parameter Description
data Required. Specifies which result handle to use. The data pointer is the
return from the mysql_query() function
row Required. Specifies which row number to get. Row numbers start at 0
field Optional. Specifies which field to get. Can be field offset, field name or
table.fieldname. If this parameter is not defined mysql_result() gets the
first field from the specified row
EXAMPLE
<?php
$con = mysql_connect("localhost", "root", "");
$db_selected = mysql_select_db("test_db", $con);
$sql = "SELECT * from Person";
$result = mysql_query($sql,$con);
echo mysql_result($result,0);
mysql_close($con);
?>
mysql_tablename()
Retrieves the table name from result.
SYNTAX
string mysql_tablename ( resource result, int row)
PARAMETER
Parameter Description
EXAMPLE
<?php
$con = mysql_connect("localhost", "root", "");
$list = mysql_list_tables("test");
$i = 0;
while ($i < mysql_num_rows ($list)) {
$tb_names[$i] = mysql_tablename ($list, $i);
echo $tb_names[$i] . "<BR>";
$i++; } ?>
Output
demo
login
student_master
mysql_list_tables()
Lists the tables in a MySQL database.
SYNTAX
mysql_list_tables(database[, connection]);
PARAMETER
Parameter Description
EXAMPLE
<?php
$dbname = 'test';
if (!mysql_connect('localhost', 'root', ''))
{
echo 'Could not connect to mysql';
exit;
}
$sql = "SHOW TABLES FROM $dbname";
$result = mysql_query($sql);
if (!$result) {
echo "DB Error, could not list tables\n";
echo 'MySQL Error: ' . mysql_error();
exit; }
Output
Table: demo
Table: login
Table: student_master
mysql_list_fields()
Fetches information about the fields in a table.
SYNTAX
mysql_list_fields(database, table[, connection]);
PARAMETER
Parameter Description
mysql_field_type()
The mysql_field_type() function is used to get the type of the specified field in a result.
SYNTAX
mysql_field_type(data,field_offset)
PARAMETER
Parameter Description
Data Required. Specifies which data pointer to use. The data pointer is the
result from the mysql_query() function
field_offset Required. Specifies which field to start on. 0 indicates the first field
EXAMPLE
<?php
$con = mysql_connect("localhost", "root", "");
$selectdb = mysql_select_db("test",$con);
$result = mysql_query("select * from demo");
$fields = mysql_num_fields($result);
$rows = mysql_num_rows($result);
$table_name = mysql_field_table($result, 0);
echo $table_name . "' table has " . $fields . " fields and " . $rows . " record(s)<br />";
echo "<p>Here is the list of the fields:</p>";
for ($i=0; $i < $fields; $i++) {
$type = mysql_field_type($result, $i);
$name = mysql_field_name($result, $i);
$len = mysql_field_len($result, $i);
$flags = mysql_field_flags($result, $i);
echo $type . " " . $name . " " . $len . " " . $flags . "<br /> "; } ?>
Output
demo' table has 3 fields and 3 record(s)
Here is the list of the fields:
int id 10 not_null primary_key auto_increment
string name 20 not_null
mysql_db_name()
The mysql_db_name() function retrieve the database name from a call to the
mysql_list_dbs() function.
SYNTAX
mysql_db_name(result, row, field)
PARAMETER
Paramete Description
r
EXAMPLE
<?php
$con=mysql_connect('localhost', 'root', '');
$db_list = mysql_list_dbs($con);
$i = 0;
$no_of_rows = mysql_num_rows($db_list);
echo "<h2>List of databases</h2>";
while ($i < $no_of_rows)
{
echo mysql_db_name($db_list, $i) . "<br />";
$i++; } ?>
Output
List all database available in your mysql server.
mysql_db_query()
Queries a MySQL database.
SYNTAX
mysql_db_query(database, query[, connection]);
PARAMETER
Paramete Description
r
EXAMPLE
<?php
// Attempt to connect to the default database server
$link = mysql_connect("localhost", "root", "")
or die ("Could not connect");
$sql = 'SELECT * FROM tblState';
// run a 'select' on the 'system' database
$data = mysql_db_query('system', $sql, $link);
mysql_close($link) ; ?>
mysql_data_seek()
The mysql_data_seek() function moves the internal row pointer.
The internal row pointer is the current row position in a result returned by the
mysql_query() function.
This function returns TRUE on success, or FALSE on failure.
SYNTAX
mysql_data_seek(data,row)
PARAMETER
Paramete Description
r
Data Required. Specifies which data pointer to use. The data pointer is the
result from the mysql_query() function
Row Required. Specifies which record to move to. 0 indicates the first record
EXAMPLE
<?php
$connection = mysql_connect("localhost", "root", "");
if (!$connection)
{ die('Could not connect: ' . mysql_error()); }
else
{ $db_selected = mysql_select_db("test",$connection);
$sql = "SELECT * from demo";
2.13.3 Insert Record in mysql using PHP
We can insert record using php, mysql. mysql is used to store the data and php is used to send the
query to mysql database. Below example give the full details about how to insert record in mysql
using php.
Example 1:
registration.php
<?php
echo $pass=rand();
$epass=md5($pass);
$con=mysql_connect("localhost","root","");
mysql_select_db('project',$con);
<body>
<form method="post">
<table align="center" border="1">
<tr>
<td>First Name</td>
<td><input type="text" name="fnm" />
</tr>
<tr>
<td>Last Name</td>
<td><input type="text" name="lnm" />
</tr>
<tr>
<td>EmailId</td>
<td><input type="text" name="emailid" />
</tr>
<tr>
<td><input type="submit" name="submit" value="Submit" /></td>
<td><input type="reset" name="reset" /></td>
</tr>
</table>
</form>
</body>
</html>
database
Example 2:
Insert.php
<html>
<head>
<title>Untitled Document</title>
</head>
<?php
$con=mysql_connect("localhost","root","");
mysql_select_db("demo");
echo $hb=$_POST['txtchk1']." ".$_POST['txtchk2']." ".$_POST['txtchk3'];
mysql_query($sql);
?>
<body>
<form method="post">
<table align="center" border="1">
<tr>
<td>First Name:</td>
<td><input type="text" name="fname"></td>
</tr>
<tr>
<td>City:</td>
<td><input type="text" name="txtcity"></td>
</tr>
<tr>
<td>Pincode:</td>
<td><input type="text" name="pincode"></td>
</tr>
<tr>
<td>Gender:</td>
<td>F:<input type="radio" name="txtgen" value="F">
</select>
</td>
</tr>
<tr>
<td>Address:</td>
<td><textarea name="txtadd"></textarea> </td>
</tr>
<tr>
</tr>
</table>
</form>
</body>
</html>
2.13.4 Delete Record Using php Mysql with Javascript Confirm Box
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Untitled Document</title>
<script language="javascript">
function del_rec(id)
{
window.location="display.php?did="+id;
}
}
</script>
</head>
<body>
<?php
$con=mysql_connect("localhost","root","");
mysql_select_db("test");
if(isset($_GET['did']))
{
mysql_query("delete from stud where id=".$_GET['did']."");
}
$sql="select * from stud";
$nsql=mysql_query($sql);
?>
<table border="1">
<tr>
<td><b>Id</b></td>
<td><b>Name</b></td>
<td><b>Delete</b></td>
</tr>
<?php
while($row=mysql_fetch_array($nsql))
{
?>
<tr>
<td><?php echo $row[0]; ?></td>
<td><?php echo $row[1]; ?></td>
<td><a href="#" onclick="del_rec(<?php echo $row[0]; ?>)">Delete</td>
</tr>
<?php
}
?>
</table>
</body>
</html>
Database
Method 2 to Delete the Record
delete.php
<?php
$con=mysql_connect("localhost","root","");
mysql_select_db("test");
$sql=mysql_query("select * from stud");
if(isset($_REQUEST[did]))
{
mysql_query("delete from stud where id=".$_REQUEST[did]);
?>
<script language="javascript">
window.location="delete.php";
</script>
<?php
}
?>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Untitled Document</title>
</head>
<body>
</body>
</html>
Database
update record in php and mysql
<html>
<head>
</head>
<body>
<?php
$con=mysql_connect("localhost","root","");
mysql_select_db("test");
if(isset($_POST['submit']))
{
$sql="update stud set name='".$_POST['txtnm']."',city='".$_POST['txtct']."' where id=".
$_GET['uid']."";
mysql_query($sql);
?>
<?php
$row=mysql_fetch_array($qsql)
?>
<form method="post">
<table border="1" align="center">
<tr>
<td>Name:</td>
<td><input type="text" name="txtnm" value="<?php echo $row['1']; ?>"></td>
</tr>
<tr>
<td>City:</td>
<td><input type="text" name="txtct" value="<?php echo $row['2']; ?>"></td>
</tr>
<tr>
<td><input type="submit" name="submit" value="Update"></td>
<td><input type="reset" name="reset" value="Cancle"></td>
</tr>
</table>
</form>
</body>
</html>
Main Page:
Update Page
Searching Record
Search.html
<html>
<body>
</body>
</html>
Search.php
<html>
<body>
<?php
$n=$_POST[‘en’];
$cn=mysql_connect(“localhost”) or die(mysql_error());
mysql_select_db(“sybca”, $cn) or die(mysql_error());
If(mysql_num_rows($rs)>=1)
echo “<br>”;
echo “<br>”;
echo “<br>”;
else
mysql_close($cn);
?>
</body>
</html>
2.14 REGULAR EXPRESSIONS
Regular expressions are nothing more than a sequence or pattern of characters it. They
provide the foundation for pattern-matching functionality.
Using regular expression you can search a particular string inside an another string, you
can replace one string by another string and you can split a string into many chunks.
In a regular expression, most characters match only themselves. For instance, if you
search for the regular expression "foo" in the string "John plays football," you get a
match because "foo" occurs in that string. Some characters have special meanings in
regular expressions. For instance, a dollar sign ($) is used to match strings that end with
the given pattern. Similarly, a caret (^) character at the beginning of a regular expression
indicates that it must match the beginning of the string. The characters that match
themselves are called literals. The characters that have special meanings are called
metacharacters.
The dot (.) metacharacter matches any single character except newline (\). So, the pattern
h.t matches hat, hothit, hut, h7t, etc. The vertical pipe (|) metacharacter is used for
alternatives in a regular expression. It behaves much like a logical OR operator and you
should use it if you want to construct a pattern that matches more than one set of
characters. For instance, the pattern Utah|Idaho|Nevada matches strings that contain
"Utah" or "Idaho" or "Nevada". Parentheses give us a way to group sequences. For
example, (Nant|b)ucket matches "Nantucket" or "bucket". Using parentheses to group
together characters for alternation is called grouping.
If you want to match a literal metacharacter in a pattern, you have to escape it with a
backslash.
To specify a set of acceptable characters in your pattern, you can either build a character
class yourself or use a predefined one. A character class lets you represent a bunch of
characters as a single item in a regular expression. You can build your own character
class by enclosing the acceptable characters in square brackets. A character class matches
any one of the characters in the class. For example a character class [abc] matches a, b or
c. To define a range of characters, just put the first and last characters in, separated by
hyphen. For example, to match all alphanumeric characters: [a-zA-Z0-9]. You can also
create a negated character class, which matches any character that is not in the class. To
create a negated character class, begin the character class with ^: [^0-9].
The metacharacters +, *, ?, and {} affect the number of times a pattern should be
matched. + means "Match one or more of the preceding expression", * means "Match
zero or more of the preceding expression", and ? means "Match zero or one of the
preceding expression". Curly braces {} can be used differently. With a single integer, {n}
means "match exactly n occurrences of the preceding expression", with one integer and a
comma, {n,} means "match n or more occurrences of the preceding expression", and with
two comma-separated integers {n,m} means "match the previous character if it occurs at
least n times, but no more than m times".
PHP offers functions specific to two sets of regular expression functions, each
corresponding to a certain type of regular expression. You can use any of them based on
your comfort.
o POSIX EXTENDED
o PERL COMPATIBLE
2.14.4 MODIFIERS:
o i – Case-insensitive
o s – Period matches newline
o m – ^ and $ match lines
o U – Ungreedy matching
o e – Evaluate replacement
o x – Pattern over several lines
Operator Purpose
| For or condition
{n} Is used when the lengths of the digits are known. Where n is an
integer value.
EXAMPLE
[abc] a, b, or c
Function Description
Ereg This function matches the text pattern in a string using a RegEx
pattern.
Eregi This function is similar to ereg(), but ignore the case sensitivity.
ereg_replace This function matches the text pattern in a string using a RegEx
Pattern and replaces it with the given text.
sql_regcase This function create a RegEx from the given string to make a case
insensitive match.
EXAMPLE
Now let us see a simple example to match a US 5 digit zip code from a string
<?php
$zip_pattern = "[0-9]{5}";
$str = "Mission Viejo, CA 92692";
ereg($zip_pattern,$str,$regs);
echo $regs[0];
?>
Output
92692
2.14.7 PERL COMPATIBLE
Perl-style regular expressions are similar to their POSIX counterparts. The POSIX syntax
can be used almost interchangeably with the Perl-style regular expression functions. In
fact, you can use any of the quantifiers introduced in the previous POSIX section.
This type of regular express is developed using the Perl language. The function which is
used for the given regular expression is preg_match() this is perl regular expression.
The symbols are used as the above ones only. It also returns the Boolean value. If the
format is matched, then it returns true value otherwise will return false value.
Symbol Description
\d Any number
\A Beginning of string
\b Word boundary
EXAMPLE
<?php
$pattern = "/^[a-zA-Z0-9._-]+@[a-zA-Z0-9-]+\.[a-zA-Z.]{2,5}$/";
$email = "vsc-project@blogspot.com";
if (preg_match($pattern,$email)) echo "Match";
else echo "Not match";
?>
Output Match
2.14.8 GENERAL FORMAT USING EREG FUNCTION
EMAIL ADDRESS
/^[\w\-\.\+]+\@[a-zA-Z0-9\.\-]+\.[a-zA-z0-9]{2,4}$/;
PINCODE
^[0-9]{5,6}$
EMAIL ADDRESS
^\$+(.|_)?\S*\@(yahoo|gmail|co|in|rediff)\.(con|in)$
PINCODE
^d{5,6}$
if(ereg('^\+91[0-9]{10}$',$_POST["txtmobileno"]))
{
$txtmobileno="";
}
else
{
$txtmobileno="Enter valid mobile no";
}
if(strlen($_POST["txtpass"])>6)
{
$txtpass="";
}
else
{ $txtpass="Password should not be 6 characters"; }
if (ereg("^[^@]{1,64}@[^@]{1,255}$",$_POST["txtemailid"]))
{ $txtemailid=""; }
else
{ $txtemailid="Enter valid emailid"; } } ?>
<form method="post">
*Sing Mark. Field is must required to fill
<table border="1">
<tr>
<td>*Name</td>
<td><input type="text" name="txtnm" /></td>
<td style="color:#FF0000"><?php if(isset($txtnm)){ echo $txtnm; } ?></td>
</tr>
OUTPUT
<tr>
<td>Last Name</td>
<td><input type="text" name="txtlnm" /></td>
</tr>
<tr>
<td>Address</td>
<td><textarea name="txtadd"></textarea></td>
</tr>
<tr>
<td>*DOB(yyyy-dd-mm)
<td><input type="text" name="txtdob" /></td>
<td><?php if(isset($txtdob)) { echo $txtdob; } ?></td>
</tr>
<tr>
<td>*Mobile No:(+91)</td>
<td><input type="text" name="txtmobileno" /></td>
<td><?php if(isset($txtmobileno)){ echo $txtmobileno; } ?></td>
</tr>
<tr>
<td>*Email Id</td>
<td><input type="text" name="txtemailid" /></td>
<td style="color:#FF0000"><?php if(isset($txtemailid)) { echo $txtemailid; } ?></td>
</tr>
<tr>
<td>*Password</td>
<td><input type="password" name="txtpass" /></td>
<td><?php if(isset($txtpass)){ echo $txtpass; } ?></td>
</tr>
<tr>
<td><input type="submit" name="submit" value="Submit" /></td>
<td><input type="reset" name="reset" value="Reset"/></td>
</tr>
</table>
</form>
2.15 SESSION
WHAT IS SESSION IN PHP?
PHP Session is a way to store information in variables that can be used in multiple pages
or across the website during that visit of a user. The php session stored information on
server side unlike cookies, that stores information at user’s computer. Alternatively you
can say PHP session variables scope is global unlike normal variable which scope is
specific to that page or a function.
As your website becomes more complicated, there will be time when you need to store
information to remember a particular visitor actions or data while navigating to other
pages. A basic HTML site does not allow to store information that can be used across
website. Sessions in PHP provides that mechanism.
For instance, in an ecommerce site storing shopping cart items, that has been added to
basket during that visit. Users keep on surfing other pages of website, however selected
items are still shown.
Similarly, storing login in information for a session.The information stored in session
variables is temporary and finishes as sessions ends or dies. For example user has closed
the website.
You simply write the command session_start(); . This command should be placed on top
of the page even before html code. You must have to start the session in order to work
with it.
So what actually happens when a session is started?
1. PHP creates a random unique identifier string of 32 hexadecimal numbers for that
particular session. e.g. 9d5gpk75d2jj973hjkop2fc934s2578 (php session id).
2. To store that unique identifier a cookies is automatically sent to user’s computer. This
cookie is called PHPSESSID.
3. In the specified temporary directory on the server side a files is automatically created
with prefix sess_[unique identifier code].
<?php
session_start(); // starts php session
$_SESSION['UserID']='1234'; // setting variable values during session
$_SESSION['name']='Pradip';
$_SESSION['location']='Rajkot';
print "session variables are assigned value.<br>";
echo "My ID is: " .$_SESSION['UserID']."<br>";
echo "My Name is: " .$_SESSION['name']. "<br>";
echo "My Location is: " .$_SESSION['location']; ?>
Output
session variables are assigned value.
My ID is: 1234
My Name is: Pradip
My Location is: Rajkot
$_SESSION['user']=$_POST['txtuser'];
?>
<script language="javascript">
Output
PHP automatically destroys a session after timeout or user has left the website means
close the browser. You may need to destroy certain variables, which purpose has been
accomplished or a session completely in explicit way.
<?php
session_start();
if(isset($_SESSION[‘UserID’]))
// isset is explained here
unset($_SESSION['UserID']);
unset($_SESSION['name']);
?>
In order to completely destroy a session use following:
<?php
session_start();
session_destroy();
?>
CONFIGURING SESSIONS
o PHP has several configuration directives to control session handling process like session
upload and URL rewriting. These are set with PHP configuration file php.ini.
o PHP SESSION CONFIGURATION DIRECTIVES
SESSION.SAVE_HANDLER
o To set possible handlers to store and retrieve session data. These are
session.save_handler = files | mm | sqlite | user
o Default option is files to handle session data. mm makes RAM to handle session
data. With sqlite option SQLite database is used. Then with user option we can
have custom functions to handle the session.
SESSION.SAVE_PATH
o If the above session.save_handler is set as files, then we need to set the path of
the directory where we want to have session data files. Session.save_path directive is
used to set the path.
o We can also create sub directories to let file storage module to store session files. And
then, we should refer this directory path by specifying its depth. For example,
session.save_path = "N;/path"
o where MODE is an Octal value. The default mode is 600 (allows owner to read
and write).
SESSION.USE_COOKIES
o This directive has 1 or 0 as its value to specify whether cookies are used to store
session id or not.
session.use_cookies = 0 | 1
o If 1 then cookies will be used to store session id. If not, the session id is preserved
by using URL rewriting.
SESSION.COOKIE_SECURE
o It controls whether cookies are sent via secure connections or not. It will be set
with ON | OFF values. The default is OFF.
SESSION.USE_ONLY_COOKIES
o By setting this directive cookies are used as the mandatory storage to preserve
session id. It prevents session hijacking.
SESSION.NAME
o To specify the name of the session. PHPSESSID is the default name.
session.name = PHPSESSID
SESSION.AUTO_START
o We need to start session before using PHP session function. This directive is used
to start session automatically on each page request. So, we need to set
session.auto_start as 1.
session.auto_start = 0 | 1
session.cache_expire = 120
o This directive need not to be set, if session.cache_limiter = nocache.
SESSION.USE_TRANS_SID
o This directive is used to preserve session id by URL rewriting. As URL are shared
among multiple users, maintaining session id in URL is risky. It cause multiple
access with same session_id at a time.
SESSION.HASH_FUNCTION
o This directive is used to choose hash function to generate session id. 0 and 1
represents MD5 and SHA algorithms respectively.
SESSION FUNCTIONS
o session_cache_expire
o Returns current cache expire
o session_cache_limiter
o Get or set the current cache limiter
o session_decode
o Decode session data from a string
o session_encode
o Encodes the current session data as a string
o session_destroy
o Destroys all data registered to a session
o session_get_cookie_params
o Get the session cookie parameters
o session_set_cookie_params
o Set session cookie parameters
o session_id
o Get or set the current session id
o session_name
o Get or set the current session name
o session_register
o Register one or more global variables with the current session
o session_is_registered
o Find whether a global variable is registered
o session_unregister
o Unregister a global variable from the current session
o session_module_name
o Get and/or set the current session module
o session_regenerate_id
o Update the current session id with a newly generated one
o session_save_path
o Get or set the current session file path
o session_set_save_handler
o Set user-level session storage functions
o session_start
o Initialize session data
o session_unset
o Free all session variables currently registered
o session_write_close
o Write session data and end the session
2.16 COOKIE
WHAT IS A COOKIE?
A cookie is a message given to a Web browser by a Web server. The browser stores the
message in a small text file that the server embeds on the user's computer. Each time the
same computer requests a page with a browser, the cookie is sent back to the server too.
There are a wide variety of things you can do with cookies. They are used to store
information about user, visited pages, poll results and etc. The main purpose of cookies is to
identify users and possibly prepare customized Web pages for them.
PHP provided setcookie() function to set a cookie. This function requires upto six arguments
and should be called before <html> tag. For each cookie this function has to be called
separately.
SYNTAX
In the example below, we will create a cookie named "name" and assign the value "pradip" to
it. We also specify that the cookie should expire after one hour and that the cookie is
available for all pages within a Tutorials directory.
EXAMPLE
<?php
setcookie("name", "pradip", time()+3600, "/","", 0);
?>
EXAMPLE
<?php
echo $_COOKIE["name"]. "<br />";
?>
Output
pradip
By default, the cookies are set to be deleted when the browser is closed. We can override that
default by setting a time for the cookie's expiration but there may be occasions when you need to
delete a cookie before the user closes his browser, and before its expiration time arrives. To do so,
you should assure that the expiration date is in the past. The example below demonstrates how to
do it (setting expiration time 1 minute ago):
EXAMPLE
<?php
setcookie("name", "", time()-60);
?>
We have create login page using php and mysql, we have used mysql_num_rows () for
count the match rows. if rows values is 0 then login is not valid and if rows value is 1
then user is valid. How to implement login and logout code in our project and this
example also use session and session destroy.
EXAMPLE
login.php
<?php
session_start();
if(isset($_GET['msg']))
{
echo $_GET['msg'];
}
if(isset($_POST["submit"]))
{
$con=mysql_connect("localhost","root","");
mysql_select_db("project");
$nsql=mysql_num_rows($qsql);
if($nsql>=1)
{
echo $_SESSION['user']=$_POST['txtemail'];
?>
<script language="javascript">
window.location="logout.php";
</script>
<?php
}
if($nsql <=0)
{ echo "Not Valid user";}}
?>
<html><head></head><body>
logout.php
----------------------
<?php
session_start();
if(isset($_SESSION['user']))
{
unset($_SESSION['user']);
$_SESSION['user']="";
?>
<script language="javascript">
//window.location="login.php?msg=You have logout successfully";
</script>
<?php
}
?>
<a href="login.php?msg=You have logout successfully">logout</a>
2.17 SENDING EMAIL WITH PHP
2.17.2 MAIL()
o PHP must be configured correctly in the php.ini file with the details of how your
system sends email. Open php.ini file available in /etc/ directory and find the
section headed [mail function]
o Windows users should ensure that two directives are supplied. The first is called
SMTP that defines your email server address. The second is called sendmail_from
which defines your own email address.
Parameter Description
As soon as the mail function is called PHP will attempt to send the email
then it will return true if successful or false if it is failed.
Multiple recipients can be specified as the first argument to the mail()
function in a comma separated list.
Following example will send an HTML email message to
pradeep.vanparia@gmail.com. You can code this program in such a way
that it should receive all content from the user and then it should send an
email.
EXAMPLE
<html>
<head>
<title>Sending email using PHP</title>
</head>
<body>
<?php
$to = "pradeep.vanparia@gmail.com";
$subject = "This is subject";
$message = "This is simple text message.";
$header = "From:abc@somedomain.com \r\n";
$retval = mail ($to,$subject,$message,$header);
2.17.4 SENDING HTML EMAIL:
o When you send a text message using PHP then all the content will be treated as
simple text. Even if you will include HTML tags in a text message, it will be
displayed as simple text and HTML tags will not be formatted according to
HTML syntax. But PHP provides option to send an HTML message as actual
HTML message.
o While sending an email message you can specify a Mime version, content type
and character set to send an HTML email.
o Following example will send an HTML email message to
pradeep.vanparia@gmail.com copying it to vanparia.pradeep@gmail.com. You
can code this program in such a way that it should recieve all content from the
user and then it should send an email.
<html>
<head>
<title>Sending HTML email using PHP</title>
</head>
<body>
<?php
$to = "pradeep.vanparia@gmail.com";
$subject = "This is subject";
$message = "<b>This is HTML message.</b>";
$message .= "<h1>This is headline.</h1>";
$header = "From:pradeep.vanparia@gmail.com \r\n";
$header = "Cc:vanparia.pradeep@gmail.com \r\n";
$header .= "MIME-Version: 1.0\r\n";
$header .= "Content-type: text/html\r\n";
$retval = mail ($to,$subject,$message,$header);
if( $retval == true )
{
echo "Message sent successfully...";
}
else
{
2.17.5 SHORTCOMINGS OF MAIL()
o Email is a short word for electronic mail. You create texts and send them over a
network of computers. The first emails go back to the 1960s. The invention has
influenced our lives and emails have become a popular means of
communication.
o ADVANTAGES
Emails are easy to use. You can organize your daily correspondence, send
and receive electronic messages and save them on computers.
Emails are fast. They are delivered at once around the world. No other
form of written communication is as fast as an email.
The language used in emails is simple and informal.
When you reply to an email you can attach the original message so that
when you answer the recipient knows what you are talking about. This is
important if you get hundreds of emails a day.
It is possible to send automated emails with a certain text. In such a way it
is possible to tell the sender that you are on vacation. These emails are
called auto responders.
Emails do not use paper. They are environment friendly and save a lot of
trees from being cut down.
Emails can also have pictures in them. You can send birthday cards or
newsletters as emails.
Products can be advertised with emails. Companies can reach a lot of
people and inform them in a short time.
o DISADVANTAGES
Emails may carry viruses. These are small programs that harm your
computer system. They can read out your email address book and send
themselves to a number of people around the world.
Many people send unwanted emails to others. These are called spam
mails. It takes a lot of time to filter out the unwanted emails from those
that are really important.
Emails cannot really be used for official business documents. They may be
lost and you cannot sign them.
Your mailbox may get flooded with emails after a certain time so you
have to empty it from time to time.
2.17.6 PHPMAILER
o Sending E-Mail through PHP can be simple, or it can be very complex depending on
what you want to do. A standard plain-text E-Mail is what most developers resort to
because building the MIME headers for HTML mail can be a difficult process. Those
days have been over for quite some time with the amazing PHPMailer library that is
available for free!.
o Whether you host your own separate server or use a third-party service, Simple Mail
Transfer Protocol (SMTP) is the easiest method to have your web server interact with an
email server. Most of the third-party services have their own unique APIs, but they
typically support SMTP. I would recommend using SMTP at least until you find a service
that you love. After that, you might want to integrate with them more tightly through an
API to take advantage of some more advanced features — or you may want to keep using
SMTP to make it easier to switch to a different service in the future.
o To use SMTP in your PHP code, I recommend using PHPMailer. This third-party library
provides the settings and functions you need to send email using a variety of methods,
including SMTP. You can find an SMTP example in the test_smtp_basic.php file in the
examples folder of the library.
PHPMAILER FEATURES
o Can send emails with multiple TOs, CCs, BCCs and REPLY-TOs
o Redundant SMTP servers
o Multipart/alternative emails for mail clients that do not read HTML email
o Support for 8bit, base64, binary, and quoted-printable encoding
o Uses the same methods as the very popular AspEmail active server (COM)
component
o SMTP authentication
o Word wrap
o Address reset functions
o HTML email
o Tested on multiple SMTP servers: Sendmail, qmail, Postfix, Imail, Exchange,
Mercury, Courier
o Works on any win32 or *nix platform
o Flexible debugging
o Custom mail headers
o Multiple fs, string, and binary attachments (those from database, string, etc)
o Embedded image support
o Next, set up the object to use SMTP and configure it to point to the proper server; I’m
using Postmark in this example:
$mail->IsSMTP();
$mail->SMTPAuth = true;
$mail->Host = "smtp.postmarkapp.com";
$mail->Port = 26;
$mail->Username = "#@#@#@#@-####-@@@@-#####-@#@#@#@#@#@#";
$mail->Password = "#@#@#@#@-####-@@@@-#####-@#@#@#@#@#@#";
o Finally, set the properties for the particular email you want to send:
$mail->SetFrom('name@yourdomain.com', 'Web App');
$mail->Subject = "A Transactional Email From Web App";
$mail->MsgHTML($body);
$mail->AddAddress($address, $name);
o Once everything is set up the way you want it, you call the object’s Send method. If the
Send method returns true, then everything worked. If it returns false, then there was a
problem.
if($mail->Send())
{
echo "Message sent!";
}
else
{
echo "Mailer Error: " . $mail->ErrorInfo;
2.17.7 SENDING A PASSWORD BY EMAIL
EXAMPLE
<?php
require 'class.phpmailer.php';
$mail
In = new
phpPHPMailer;
using rand() function we can send auto generate password to user at their
given email id.
$mail->IsSMTP(); // Set mailer to use SMTP
$mail->Host = 'smtp.mandrillapp.com'; // Specify main and backup server
$mail->Port = 587; // Set the SMTP port
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->Username = 'MANDRILL_USERNAME'; // SMTP username
$mail->Password = 'MANDRILL_APIKEY'; // SMTP password
$mail->SMTPSecure = 'tls'; // Enable encryption, 'ssl' also accepted
$mail->From = 'from@example.com';
$mail->FromName = 'Your From name';
$mail->AddAddress('josh@example.net', 'Josh Adams'); // Add a recipient
$mail->AddAddress('ellen@example.com'); // Name is optional
EXAMPLE
$mail->IsHTML(true); // Set email format to HTML
<html><head><title>Sending Password email using PHP</title>
$mail->Subject = 'Here is the subject';
</head><body>
$mail->Body
<?php = 'This is the HTML message body <strong>in bold!</strong>';
$mail->AltBody $pass=rand(9999);
= 'This is the body in plain text for non-HTML mail clients';
$to = $_POST["txtemail"];
if(!$mail->Send())
$subject {= $_POST["txtnm"];
echo 'Message
$message could not be sent.';
= $_POST["message"]."\n Your Password is:-".rand(1000,9999);
echo 'Mailer Error: ' . $mail->ErrorInfo;
$header = "From:vanparia.pradeep@gmail.com \r\n";
exit; $retval = mail ($to,$subject,$message,$header);
} if( $retval == true )
{
echo 'Message
echohas been sent';
"Message Password sent successfully...";
}
else
{
echo "Message Password could not be sent...";
}
?>
<form method="post">
<table border="1" align="center">
<tr>
2.17.8 SEND ATTACHMENT IN MAIL
EXAMPLE