While Loop (VBscript)

|


The VBScript While Loop executes code while a condition is true.

Example:


< type="text/vbscript">
Dim numb
numb = 0
While numb <= 8

    document.write("Number Is: " & numb & vbCRLF )

numb = numb + 1
Wend
document.write("End of While!")
< /script >

This results is:

Number Is: 0
Number Is: 1
Number Is: 2
Number Is: 3
Number Is: 4
Number Is: 5
Number Is: 6
Number Is: 7
Number Is: 8
End of While!

  1. We started by declaring a variable called "numb" and setting it to 0
  2. We then opened a while loop and inserted our condition. Our condition checks if the current value of the numb variable is less than or equal to 8.
  3. This is followed by code to execute while the condition is true. In this case, we are simply, outputting the current value of numb, preceded by some text.
  4. We then increment the value by 1.
  5. When the browser reaches the closing curly brace, if the condition is still true, it goes back to the first curly brace and executes the code again. By now, the numb variable has been incremented by 1. If the condition is not true (i.e. the variable is greater than 8), it exits from the loop, and continues on with the rest of the code

For Next Loop (VBscript)

|

For...Next Loop
VBScript uses the For…Next structure for creating incremental loops. There are a few keyword variations that allow some flexibility in how the loop is executed.

Syntax:
For variable = intStart To intEnd [Step intIncrement]
' Code to be repeated
Next

A basic For…Next statement is used to repeat a section of code a definite number of times. The following code will count to 5 and print each number.

Exampel:
For x = 1 To 5
WScript.Echo x
Next

The For statement requires that you supply a counter variable such as “x.” You must also supply its starting and ending value. The Next statement will increment the counter variable and repeat the enclosed code until it is no longer within the specified range, resulting in an output like the following:
1
2
3
4
5

The For statement also accepts the Step keyword which can be used to change the increment value. You may supply a negative number to cause the counter to decrement. The following example will list all even numbers from 10 to 0.

Example:
For x = 10 To 0 Step -2
Wscript.Echo x
Next

Make sure that your starting value is less than your ending value when incrementing and greater than it when decrementing in order to prevent errors. The second output looks like this:
10
8
6
4
2
0
For Each…Next loop
Another variation of this loop is the For Each…Next loop. This Each keyword will iterate through each element in a dictionary object, array, or collection.

arrWords = Array("Red", "Green", "Blue", "Black", "White")
For Each strWord In arrWords
WScript.Echo strWord
Next

Using the For Each statement, we iterated through each element without having to specify the number explicitly. The first variable in this statement must be a reference to the array element followed by the In keyword and a variable representing the array. The resulting output makes this very evident.
Red
Green
Blue
Black
White

This same output can be generated using a simple For loop, however, the code is much more complex.

For i = 0 To UBound(arrWords)
strWord = arrWords(i)
Wscript.Echo strWord
Next

In this example, we had to programmatically determine the number of elements in the array and then make a reference to each of them. The For Each syntax is a much cleaner, quicker approach.

Conditional Statements (VBscript)

|

VBScript allows you to control how your scripts process data through the use of conditional and looping statements. By using conditional statements you can develop scripts that evaluate data and use criteria to determine what tasks to perform. Looping statements allow you to repetitively execute lines of a script. Each offers benefits to the script developer in the process of creating more complex and functional web pages.
Very often when you write code, you want to perform different actions for different decisions. You can use conditional statements in your code to do this.

if statement :
if statement is used when you want to execute a set of code when a condition is true.

if...then...else statement :
if…then…else statement is used when you want to select one of two sets of lines to execute.

if...then...elseif statement :
if...then...elseif statement is used when you want to select one of many sets of lines to execute.

select case statement :
select case statement is used when you want to select one of many sets of lines to execute

If....Then
If you want to execute only one statement when a condition is true, you can write the code on one line:

if i>0 Then msgbox "Positive Number"

If you want to execute more than one statement when a condition is true, you must put each statement on separate lines and end the statement with the keyword "End If":

if i>0 Then
msgbox " Positive Number"
i = i+1
end If

If....Then….Else
If you want to execute a statement if a condition is true and execute another statement if the condition is not true, you must add the "Else" keyword:

if i>0 then
msgbox "Positive Number"
else
msgbox "Negative Number"
end If

The first block of code will be executed if the condition is true, and the other block will be executed otherwise.

If....Then.....Elseif
You can use the if...then...elseif statement if you want to select one of many blocks of code to execute

if percentage>=80 then
msgbox "Your Grade is A."
elseif percentage>=70 then
msgbox "Your Grade is B."
elseif percentage>=60 then
msgbox "Your Grade is C."
else
msgbox "Your Grade is D."
end If

Select Case
The Select Case statement provides an alternative to the If..Then..Else statement, providing additional control and readability when evaluating complex conditions. It is well suited for situations where there are a number of possible conditions for the value being checked. Like the If statement the Select Case structure checks a condition, and based upon that condition being true, executes a series of statements.

Example
select case payment
case "Cash"
msgbox "You are going to pay cash"
case "Visa"
msgbox "You are going to pay with visa"
case "AmEx"
msgbox "You are going to pay with American Express"
case Else
msgbox "Unknown method of payment"
end select

This is how it works: First we have a single expression (most often a variable), that is evaluated once. The value of the expression is then compared with the values for each Case in the structure. If there is a match, the block of code associated with that Case is executed.

VBScript Procedures

|

We have two kinds of procedures: The Sub procedure and the Function procedure.

Sub procedure
A sub procedure is a series of statements, enclosed by the Sub and End Sub statements. It
can perform actions, but does not return a value. It can take arguments that are passed to it by a calling procedure. Sub procedures without arguments, must include an empty set of parentheses ()

Example:
Sub mysub()
some statement(s)
End Sub

Example:
Sub mysub(arg1,arg2)
Statement(s)
End Sub

Function procedure
A function procedure is a series of statements, enclosed by the Function and End Function statements. It can perform actions and can return a value. Function procedures can take arguments that are passed to it by a calling procedure. Without arguments, must include an empty set of parentheses (). They returns a value by assigning a value to its name.

Example
Function myfunction()
statement(s)
myfunction=some value
End Function

Example
Function myfunction(arg1,arg2)
Statement(s)
myfunction=some value
End Function

Calling a Sub or Function Procedure
Function name is used to call a function procedure. When you call a Function in your code, you do like this
Var_name = proc_name()

Here you call a Function called " proc_name", the Function returns a value that will be stored in the variable " Var_name".

Calling a sub procedure you can use the following statement.
Call Proc_name(arguments)
Or, you can omit the Call statement
Proc_name arguments

Arrays (VBscript)

|

The VBScript language provides support for arrays. You declare an array using the Dim statement, just as you did with variables:

Dim States(50)

The statement above creates an array with 51 elements. Why 51? Because VBScript arrays are zero-based, meaning that the first array element is indexed 0 and the last is the number specified when declaring the array.

You assign values to the elements of an array just as you would a variable, but with an additional reference (the index) to the element in which it will be stored:
States(5) = "California"
States(6) = "New York"

Arrays can have multiple dimensions-VBScript supports up to 60. Declaring a two dimensional array for storing 51 states and their capitals could be done as follows:

Dim StateInfo(50,1)
To store values into this array you would then reference both dimensions.

StateInfo(18,0) = "Michigan"
StateInfo(18,1) = "Lansing"

VBScript also provides support for arrays whose size may need to change as the script is executing. These arrays are referred to as dynamic arrays. A dynamic array is declared without specifying the number of elements it will contain:

Dim Customers()

The ReDim statement is then used to change the size of the array from within the script:
ReDim Customers(100)

There is no limit to the number of times an array can be re-dimensioned during the execution of a script. To preserve the contents of an array when you are re-dimensioning, use the Preserve keyword:
ReDim Preserve Customers(100)

Working With Variables

|

A variable is a named location in computer memory that you can use for storage of data during the execution of your scripts. You can use variables to:

  • Store input from the user gathered via your web page
  • Save data returned from functions
  • Hold results from calculations

An Introduction to Variables
Let's look at a simple VBScript example to clarify the use of variables.

Sub testVariables_OnClick
Dim Name
Name = InputBox("Enter your name: ")
MsgBox "The name you entered is " & Name
End Sub

The first line of this example defines a sub procedure associated with the click event of a command button named testVariables.
On second line we declare a variable named Name. We are going to use this variable to store the name of the user when it is entered. The third line uses the InputBox function to first prompt for, and then return, the user's name. You will see more of the InputBox function later in this tutorial. The name it returns is stored in the Name variable.
The fourth line uses the MsgBox function to display the user's name. Finally, the sub procedure completes on line five.

Exactly how, and where, variables are stored is not important. What you use them for, and how you use them is important.

Declaring Variables

There are two methods for declaring variables in VBScript, explicitly and implicitly. You usually declare variables explicitly with the Dim statement:

Dim Name

This statement declares the variable Name. You can also declare multiple variables on one line as shown below, although it is preferable to declare each variable separately.

Variables can be declared implicitly by simply using the variable name within your script. This practice is not recommended. It leads to code that is prone to errors and more difficult to debug.

You can force VBScript to require all variables to be explicitly declared by including the statement Option Explicit at the start of every script. Any variable that is not explicitly declared will then generate an error.

Variable Naming Rules

  • They must begin with an alphabetic character
  • They cannot contain embedded periods
  • They must be unique within the same scope. There is more on scopes later in this lesson
  • They must be no longer than 255 characters

Variants and Subtypes
VBScript has a single data type called a variant. Variants have the ability to store different types of data. The types of data that a variant can store are referred to as subtypes. The table below describes the subtypes supported by VBScript.


Subtype

Description of Uses for Each Subtype

Byte

Integer numbers between 0 to 255

Boolean

True and False

Currency

Monetary values

Date

Date and time

Double

Extremely large numbers with decimal points

Empty

The value that a variant holds before being used

Error

An error number

Integer

Large integers between -32,768 and 32,767

Long

Extremely large integers (-2,147,483,648 and 2,147,483,647)

Object

Objects

Null

No valid data

Single

Large numbers with decimal points

String

Character strings

Assigning Values
You assign a value to a variable by using the following format:

Syntax:
Variable_name = value

Examples:
Name = "Rahul"
Age=50

Scope of Variables

The scope of a variable dictates where it can be used in your script. A variable's scope is determined by where it is declared. If it is declared within a procedure, it is referred to as a procedure-level variable and can only be used within that procedure. If it is declared outside of any procedure, it is a script-level variable and can be used throughout the script.
The example below demonstrates both script-level and procedure-level variables.

<>
Dim counter
Sub cmdButton_onClick
Dim temp
End Sub
< /SCRIPT >

The variable counter is a script-level variable and can be utilized throughout the script. The variable temp exists only within the cmdButton_onClick sub-procedure.

Operators (JavaScript)

|

Operators are symbols that are used with variables to allow us to perform certain functions, such as adding, subtracting and etc. The table below lists the operators available in JavaScript and describes its function (assuming the two variables x and y that have been declared and initialized with a value)

JavaScript Arithmetic Operators
Arithmetic operators are used to perform arithmetic between variables and/or values.
Given that y=5, the table below explains the arithmetic operators:


Operator

Description

Example

Result

+

Addition

x=y+2

x=7

-

Subtraction

x=y-2

x=3

*

Multiplication

x=y*2

x=10

/

Division

x=y/2

x=2.5

%

Modulus (division remainder)

x=y%2

x=1

++

Increment

x=++y

x=6

--

Decrement

x=--y

x=4

JavaScript Assignment 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:


Operator

Example

Same As

Result

=

x=y

x=5

+=

x+=y

x=x+y

x=15

-=

x-=y

x=x-y

x=5

*=

x*=y

x=x*y

x=50

/=

x/=y

x=x/y

x=2

%=

x%=y

x=x%y

x=0


Comparison Operators
Comparison operators are used in logical statements to determine equality or difference between variables or values.
Given that x=5, the table below explains the comparison operators:


Operator

Description

Example

==

is equal to

x==8 is false

===

is exactly equal to (value and type)

x===5 is true
x==="5" is false

!=

is not equal

x!=8 is true

>

is greater than

x>8 is false

<

is less than

x<8>

>=

is greater than or equal to

x>=8 is false

<=

is less than or equal to

x<=8 is true

Logical 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:


Operator

Description

Example

&&

and

(x <> 1) is true

||

or

(x==5 || y==5) is false

!

not

!(x==y) is true

Learn JavaScript

|

JavaScript is a scripting language widely used for client-side web development. It was the originating dialect of the ECMAScript standard. It is a dynamic, weakly typed, prototype-based language with first-class functions. JavaScript was influenced by many languages and was designed to look like Java, but be easier for non-programmers to work with.

"JavaScript" is a trademark of Sun Microsystems. It was used under license for technology invented and implemented by Netscape Communications and current entities such as the Mozilla Foundation.

Although best known for its use in websites (as client-side JavaScript), JavaScript is also used to enable scripting access to objects embedded in other applications (see below).

JavaScript, despite the name, is essentially unrelated to the Java programming language, although both have the common C syntax, and JavaScript copies many Java names and naming conventions. The language's name is the result of a co-marketing deal between Netscape and Sun, in exchange for Netscape bundling Sun's Java runtime with their then-dominant browser. The key design principles within JavaScript are inherited from the self and Scheme programming languages.

What's the difference between JavaScript and Java?


Actually, the 2 languages have almost nothing in common except for the name. Although Java is technically an interpreted programming language, it is coded in a similar fashion to C++, with separate header and class files, compiled together prior to execution. It is powerfull enough to write major applications and insert them in a web page as a special object called an "applet." Java has been generating a lot of excitement because of its unique ability to run the same program on IBM, Mac, and UNIX computers. Java is not considered an easy-to-use language for non-programmers.

JavaScript is much simpler to use than Java. With JavaScript, if I want check a form for errors; I just type an if-then statement at the top of my page. No compiling, no applets, just a simple sequence.

Important Links

|

My Training Hub
Security Climate Web Directory
Doharugbyfc
ADD URL :: Submit URL
Root Fl Directory
Free Directory
ZoocK Directory
Quality Web Directory
SudNET Web Directory
RibCast Directory
Quality Web Directory
Femeba Directory
ETN Free Web Directory
Ablaze Directory
SoundSolutionSam1
My Directory Live
Net Collector
jSum Directory
LINK ADD URL Seo Friendly Web Directory
Winapple Directory
Huahua General Web Directory
Web directory
Free web directory
eSiq Directory
Welcome to Katerart.com, a website Directory.
Directory Bin
All Links Directory
MiriBlack Web Directory
Submit URL Directory!

Portland ORE Homes
Zydamax Web Directory
Banyapa Directory
2006cigr-Directory Site
SEO Executive
PR5 Directories
ChinaFixer - Free Internet Directory
Free Web Directory
3MSS Directory Submission
Directory Travel
Business Directory
Pittsburgh Art Review Web Directory
Anaximander Directory
Free Web Directory
Free Web Directory - Add Your Link
Desarrolo Link Directory
Free Web Directory
Desarrolo Link Directory
Free Web Directory - Add Your Link
The Little Web Directory

KK-CLUB
Soft4Each Web Directory
Free web directory - Netwerker
Quality Web Directory
Ynjjdg - Submit Your Site
Net Knowledge
Clock Tower Studio - General Directory
DevoteClub - Submit Your Site
Web Directory - Top Sites
Faba Directory
Cagtermal
Skoobe Link Directory
RcrEducation - Submit Your Site
Free Web Directory
Webdee.org FREE Directory
Arakne-Links Directory
< href="'http://www.directorystorm.com/'"> Directory Storm< /a >
Web Directory
Linkroo - A better place for Backlinks | SEO Directory
Submit site - web site promotion - Directory
Indian Songs, Pakistani Songs, Bollywood Songs
Urozope.org Web Directory
MagDalyns Online
1 A Directory
Bbbfit- Submit Your Site
Sportsman's Depot is the leading provider of Hunting, Fishing, Camping and outdoor accessories online! We offer an array of sporting supplies to fit your every need, with the best prices on the web. You can find every top brand at the lowest prices at Sportsman's Depot
West Web directory
Always and Forever 14
Bryancampen - Submit Your Site
Free Image Hosting A1 Family Friendly Directory with Deeplinks
Free SEO Friendly Directory
Search Engine Friendly Directory
Cfkap Web Directory
NI Resource Directory
Search engine friendly directory

Search Engine Friendly Directory
HRCE Web Directory
E-Mediate.org
HRCE Web Directory
YasamayaDeger - Submit Your Site
Wah Directory
Safadairy - Submit Your Site
URL Web Directory
Quality Web Directory
Yelk.net - Search for sites by their descriptions. Try it!
Business Sites on the Net
DigiDagi Directory
Web Directory - All Sites Sorted
PR General Web Directory
ApleinTubes Directory
Munoa- Submit Your Site
Project Empowerment Web Directory
JHUCR Free Directory
Sentrega Directory
Piseries Link Directory
Web Directory
Mozizona - Submit Your Site
Golf Tournament Registry
Ft8 Web Directory
Deep Links Directory
WishDC.org Web Directory
Vietnam-Hub
PZSA Directory
Cfstudio - Submit Your Site
Chaqra Directory
< href="'http://www.okaysites.com/'"> Okay Sites< /a >
wybnb.com
WebDiro Directory
Free Web Directory - Deep Links OK!
ZN Directory
Gmdm Web Directory
AZ Links Directory
HolidayDig Free Directory
Gain Web
Technoworld - Submit Your Site
Increase Directory
Msgat - Submit Your Site
WishDC.org Web Directory
VipDig Free Directory
Human Edited Web Directory
Quality Web Directory
Submit url
Tuckinfo Directory-Submit Link
1 A Directory
Siz Tech Web Directory
Project Empowerment Web Directory
Bbbfit- Submit Your Site
Web Directory
Web Directory
Web Directory
Site Name
Web Master Directory
MaverickMoon - Submit Your Site
COUNTERDEAL.COM
Thales Directory
12 years old quailty web directory
Popular Directory Pop-Net.org
Thai Web Directory
Temnoticia
Jointmc - Submit Your Site
ByMattKing - Submit Your Site
GG Web Directory
Jjhou general directory
Neks - Submit Your Site
Quality Web Directory
Ldmstudio Directory
Quality Web Directory
Blogs Directory
DirectoryVault Free Web Directory
Aqard - Submit Your Site
Human edited web directory Web Hot Link general online internet web directory
Msgat - Submit Your Site
CMDG
Human edited web directory Web Hot Link general online internet web directory
Scablevel - Submit Your Site
DirectoryVault Free Web Directory
Pattis Wagons Directory
Sostro - Submit Your Site
Web Directory
Site Name
Alldeny - Submit Your Site
Lefolio - Submit Your Site
My Green Corner
Friendly Seo Directory
Metextile - Submit Your Site
ivisu.org
Buy Domain Names
Skype Media Web Directory
H-PF - Free Directories
Free Website Directory
Directory Link
Web Directory

Update and Delete Statements(MYSQL)

|

Update statement is used to modify the data in a database table. The general syntax is as under.

Syntax:


UPDATE tablename SET columnname = newvalue WHERE columnname = value

Example:

Table Name(empinfo)

FirstNameLastName EmailDOB
Steve
Martinsmart.steve@studiesinn.com08-04-1988
DavidFernandasdavidfernandas@studiesinn.com04-16-1977
AjayRathorajayrathor@studiesinn.com08-24-1986

< ? php $con = mysql_connect ("localhost:3306","adam","123456"); if (!$con) { die ('Could not connect: ' . mysql_error());

}

mysql_select_db("mydb", $con);
$result = mysql_query("Update empinfo Set DOB=’07-05-1988’ where FirstName=’Steve’");
mysql_close($con);
?>

FirstNameLastNameEmailDOB
SteveMartinsmart.steve@studiesinn.com07-05-1988
DavidFernandasdavidfernandas@studiesinn.com04-16-1977
AjayRathorajayrathor@studiesinn.com08-24-1986




Delete Statement:

DELETE FROM statement is used to delete rows from a database table. The general syntax is as under.

Syntax:


DELETE FROM tablename WHERE columnname = value

Example:


Table Name(
empinfo)
FirstName LastName EmailDOB
Steve Martin smart.steve@studiesinn.com 08-04-1988
David Fernandas davidfernandas@studiesinn.com 04-16-1977
Ajay Rathor ajayrathor@studiesinn.com 08-24-1986

< ? php $con = mysql_connect("localhost:3306","adam","123456"); if (!$con) { die('Could not connect: ' . mysql_error());

}

mysql_select_db("mydb", $con);
$result = mysql_query("Delete From empinfo where FirstName=’Steve’");
mysql_close($con);
?>
FirstNameLastName EmailDOB
DavidFernandasdavidfernandas@studiesinn.com 04-16-1977
AjayRathorajayrathor@studiesinn.com08-24-1986

Order By (MYSQL)

|

We use Order By Keyword to sort the records in a recordset. The general syntax is as under.

Syntax:

SELECT columnname(s) FROM tablename ORDER BY columnname SortOrder

Example:
Table Name(
empinfo)

FirstName LastName Email DOB
SteveMartinsmart.steve@studiesinn.com08-04-1988
DavidFernandasdavidfernandas@studiesinn.com04-16-1977
AjayRathorajayrathor@studiesinn.com08-24-1986

$con = mysql_connect("localhost:3306","adam","123456");
if (!$con)
{
die('Could not connect: ' . mysql_error());

}

mysql_select_db("mydb", $con);
$result = mysql_query("SELECT * FROM empinfo order by FirstName asc");
while($row = mysql_fetch_array($result))
{
echo $row['FirstName'] . " " . $row['LastName'] . “ “ $row[‘DOB];
echo "<>";
}
mysql_close($con);
?>

The Output will be
Ajay Rathor 08-24-1986
David Fernandas 04-16-1977
Steve Martin 08-04-1988

Where Clause(MYSQL)

|

In Select Query we use WHERE clause to select only data that matches a specified criteria.

Syntax:

SELECT column(s) FROM tablename WHERE column operator value

Example:

Table Name(empinfo):

FirstNameLastName Email DOB
SteveMartinsmart.steve@studiesinn.com08-04-1988
David Fernandasdavidfernandas@studiesinn.com 04-16-1977
AjayRathorajayrathor@studiesinn.com08-24-1986

$con = mysql_connect("localhost:3306","adam","123456");
if (!$con)
{
die('Could not connect: ' . mysql_error());

}

mysql_select_db("mydb", $con);
$result = mysql_query("SELECT * FROM empinfo where FirstName=’David’");
while($row = mysql_fetch_array($result))
{
echo $row['FirstName'] . " " . $row['LastName'] . “ “ $row[‘DOB’];
echo "
";
}
mysql_close($con);
?>

Output will be.

David Fernandas 04-16-1977

Operator that can be used in where clause are as under

= Equal

!= Not equal

> Greater than

< Less than

>= Greater than or equal

<= Less than or equal

BETWEEN Between an inclusive range

LIKE Search for a pattern

Select Statement (MYSQL)

|

The select query is used to retrieve records from a database.

SELECT Retrieves fields from one or more tables.
FROM Tables containing the fields.
WHERE Criteria to restrict the records returned.
GROUP BY Determines how the records should be grouped.
HAVING Used with GROUP BY to specify the criteria for the grouped records.
ORDER BYCriteria for ordering the records.
LIMITLimit the number of records returned.

Syntax:

SELECT column_name(s)
FROM table_name

< ? php

$con = mysql_connect ("localhost:3306","adam","123456");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("mydb", $con);
$result = mysql_query("SELECT * FROM empinfo");
while ($row = mysql_fetch_array($result))
{
echo $row['FirstName'] . " " . $row['LastName'] . “ “ $row[‘Age’];
echo "<>";
}
mysql_close($con);
?>

Returned data from mysql_query() function will be stored in the result variable. msql_fetch_array() function is used to return the first row from the recordset as an array. The while loop loops through all the records in the recordset and retrieve all the records from the recordset.

Following function can be used in the select statement.

Function Description
AVG() Returns the average value in a group of records.
COUNT() Returns the number of records in a group of records
MAX()Returns the largest value in a group of records.
MIN()Returns the lowest value in a group of records
SUM()Returns the sum of a field.

Display the Result in an HTML Table

}
mysql_select_db ("mydb", $con);

result = mysql_query ("SELECT * FROM empinfo");

echo "< border="'1'" align="’center’">

<>

<><> Firstname < / b >

<><>Lastname< / b >

<><>Age< / b >< / td >

< / tr >";
while($row = mysql_fetch_array($result))
{
echo "<>";
echo "<>" . $row['FirstName'] . "< / td >";

echo "<>" . $row['LastName'] . "< /td >";

echo "<>" . $row['Age'] . "< / td >";

echo "< / tr >";

}
echo "< / table >";


mysql_close($con);

?>

Insert Data into the Table (MYSQL)

|

The INSERT INTO SQL statement impregnates our table with data. Here is a general form of INSERT.

INSERT INTO table_name (column1, column2....) VALUES (value1, value2,....)

MYSQL Data Types

|

Numeric Data Types:

TINYINT( )-128 to 127 normal 0 to 255 UNSIGNED.
SMALLINT( )-32768 to 32767 normal 0 to 65535 UNSIGNED.
MEDIUMINT( )-8388608 to 8388607 normal 0 to 16777215 UNSIGNED.
INT( )-2147483648 to 2147483647 normal 0 to 4294967295 UNSIGNED.
BIGINT( )-9223372036854775808 to 9223372036854775807 normal 0 to 18446744073709551615 UNSIGNED.
FLOATA small number with a floating decimal point.
DOUBLE( , )A large number with a floating decimal point.
DECIMAL( , )A DOUBLE stored as a string, allowing for a fixed decimal point.

Date Data Types:

DATEYYYY-MM-DD.
DATETIMEYYYY-MM-DD H:MM:SS.
TIMESTAMPYYYYMMDDHHMMSS.
TIMEHH:MM:SS.

MISC Types

ENUM ( )ENUMERATION means that each column may have one of specified possible values.
SETSET is similar to ENUM. However, SET can have up to 64 list items and it can store more than one choice


TEXT TYPES


CHAR( )Fixed section from 0 to 255 characters long.
VARCHAR( )Variable section from 0 to 255 characters long.
TINYTEXTString with a maximum length of 255 characters.
TEXTString with a maximum length of 65535 characters.
BLOBString with a maximum length of 65535 characters.
MEDIUMTEXT
String with a maximum length of 16777215 characters.
MEDIUMBLOBString with a maximum length of 16777215 characters.
LONGTEXTString with a maximum length of 294967295 characters.
LONGBLOB
String with a maximum length of 4294967295 characters.

Connecting to MYSQL DataBase

|

In order to pull information from a MySQL database to your php pages, you need to connect to the database first.

Syntax:

mysql_connect(servername,username,password);
servername: It specifies the server to connect to. Default value is "localhost:3306"
username: It specifies the username to log in with. Default value is the name of the user that owns the server process
password: It specifies the password to login. Default is ""
Note:
To execute the SQL statements we must use the mysql_query() function. This function is used to send a query or command to a MySQL connection.

Example:

$server = "localhost";
$user = "";
$pass = "";
$db = "mydb";

$conn = mysql_connect("$host", "$user", "$pass") or die ("Unable to connect.");
mysql_select_db("$db", $conn);
?>

Create a Database


PHP also provide a function to create MySQL database, mysql_create_db().
$con = mysql_connect("localhost:3306","adam","123456");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
$query = "CREATE DATABASE mydb";
$result = mysql_query($query,$con);
?>

PHP Data Base

|

A database is a collection of data that is stored independently of the manner in which you collect it or may wish to retrieve it. It is organized for efficient storage and retrieval, based on the nature of the data, rather than the collection or retrieval methods.


What is MySQL:

MySQL is an open source relational database management system (RDBMS)that uses Structured Query Language (SQL), the most popular language for adding, accessing, and processing data in a database. It is a Database Management System which is available for both Linux and Windows.

In a database, there are tables. Database tables contain rows, columns, and cells. Tables are used to organize and group your data by common characteristics or principles.


Database Query is a form generator and query manager that works with any database. Database Query automatically creates forms for selecting, updating, inserting, or deleting data in MySQL, Oracle, DB2, or any other database. With MySQL, we can query a database for specific information and have a recordset returned.

PHP Error Handling

|

Error handling is the process of changing the control flow of a program in response to error conditions. Error conditions can be caused by a variety of factors - programmer error, corrupt input data, software requirements deficiencies and in many other conditions.

A web application needs to be able to gracefully handle all of these potential problems - recovering from them where possible and exiting gracefully when the error is fatal.

We will show different error handling methods:

1. Simple "die()" statements

2. Custom errors and error triggers

3. Error reporting


Simple die() statement:



if(!file_exists("myfile.txt"))

{

die("File not found");

}

else

{

$file=fopen("myfile.txt","r");

}

?>

If the file does not exist you get an error message like this:

File not found

Custom errors and error triggers

You can create a custom error handler in PHP to replace the standard output to the browser. First you set up the error handler to replace the normal one, and set the ini values.

ini_set('display_errors', 'Off');

ini_set('log_errors', 'On');

define('ERROR_LOG_PATH', 'error_log.txt');

set_error_handler("custom_err_handler");

The custom function is defined we must then create it. The function takes 4 arguments.

1. $num: level of the error raised
2. $str: contains the error message
3. $file: filename that the error was raised in
4. $line: line number the error was raised at

function custom_err_handler($num, $str, $file, $line) {

print "Error Handler Called!";

$err = "";

$err .= "PHP Error\n";

$err .= "Number: [" . $num . "]\n";

$err .= "String: [" . $str . "]\n";

$err .= "File: [" . $file . "]\n";

$err .= "Line: [" . $line . "]\n\n";

error_log($err, 3, ERROR_LOG_PATH);

}

function Errfunction()
{


trigger_error("errror message");

}

Now call the Errfunction()

myFunction();

PHP EMail

|

mail() function is used to send emails from inside a script in php. The Syntax of mail() function is as under.mail(to,subject,message,headers,parameters)



ParameterDescription
toRequired. Specifies the receivers email
subjectRequired. Specifies the subject of the email
messageRequired. Contain the message to be sent. Each line should be separated with a Line Fed (\n). Lines should not exceed 70 characters
headersOptional. Specifies additional headers, like From, Cc, and Bcc. The additional headers should be separated with a CRLF (\r\n)
parametersOptional. Specifies an additional parameter to the sendmail program.




$to = 'noname@testing.com';

$subject = 'E-mail subject';

$message = 'E-mail message';

$headers = 'From: webmaster@studiesinn.com' . "\r\n" .

'Reply-To: webmaster@ webmaster.com' . "\r\n" .

'X-Mailer: PHP/' . phpversion();

mail($to, $subject, $message, $headers);

?>

PHP Files

|

PHP is a very useful language for working with files. Although it may not be as robust as other languages, such as PERL, when it comes to parsing files, PHP still provides great power and flexibility when it comes to working with text files.

Opening a File:

Before you can use PHP to read a file, you must first open it. To open a file, you use the fopen() function.

$file_handler = fopen($file, $mode)

You must assign the function to a variable, as above. This is referred to as a file pointer. You use the file pointer to reference the open file throughout your script.

The fopen() function takes two arguments:

* $file is the name (and path, if required) of the file.

* $mode is one of a list of available modes:

1. r— Open the file as read-only. You cannot write anything to the file. Reading begins at the beginning of the file.

2. r+ — Open the file for reading and writing. Reading and writing begin at the beginning of the file. You will delete existing contents if you write to the file without first moving the internal pointer to the end of the file.

3. w— Open the file for write-only. You cannot read data from the file. Writing begins at the beginning of the file. You will again delete contents if you write to the file without first moving the pointer to the end of the file. If the file specified by the $fie argument does not exist, then PHP attempts to create the file. Make sure your permissions are set correctly!


4. w+ — As above, but the file may also be read.

5. a— This mode is the same as the 'w' mode, with the exception that the internal pointer is placed at the end of the file. Existing contents will not be overwritten unless you rewind the internal pointer to the beginning of the file.


6. a+ — As above, but the file may also be read.
Additionally, if the file is a binary file, you must include a "b" in the mode if your OS is Windows. This chapter only deals with ASCII text files, so you will not require the "b: mode in the following example. If you do need to open a binary file, an example is below:

$file_handle = fopen($filename, "rb+")
Note the differences between the "w" and "a" modes. Using "w" to open a file effectively deletes the contents of the file, while using the "a" mode retains the contents of the file and allows you to append additional data to the end of the file.

Once you have the file opened, you can then read from or write to the file.

Reading a File:


There are multiple functions available to read from a file.

You can read data from the file using the fread() function:

$file_contents = fread($file_pointer, $length_to_read);

You must assign the value of fread() to a variable, which will contain the data that has been read. The fread() function takes two arguments:

1. $file_pointer is the file pointer to which you assigned the value from the fopen() function.

2. $length is the amount of bytes that you wish to read.

When using fread() to read a file, you can read in the entire file. To do this, you need to know the byte-size of the file. You can easily find the total byte-size of a file using the filesize() function:

$bytes = filesize($filename);

The following script demonstrates how to open a short text file and display its contents:

$file = "/path/to/text.txt";

$filepointer = fopen($file, "r");

$contents = fread($filepointer, filesize($file));

echo "

" . htmlentities($contents) . "
";

Closing a File:

When you have finished reading from or writing to a file that has been opened using the fopen() function, you should always close it using the fclose() function:

fclose($filepointer);

Closing the file allows you to clean up any memory that was used to open it and also prevents possible file corruption that sometimes (rarely) occurs when a file is left open.

PHP Cookies

|

A cookie is a small bit of information stored on a viewer's computer by his or her web browser by request from a web page. The information is constantly passed in HTTP headers between the browser and web server; the browser sends the current cookie as part of its request to the server and the server sends updates to the data back to the user as part of its response. In addition to the information it stores, each cookie has a set of attributes: an expiration date, a valid domain, a valid domain path and an optional security flag. These attributes help ensure the browser sends the correct cookie when a request is made to a server.



Syntax:

setcookie(name, value, expire, path, domain);

Example:


setcookie("c_name", "Adam", time()+60);

?>

Retrieve a Cookie:

The $_COOKIE variable is used to retrieve a cookie.



echo $_COOKIE["user"];
?>

PHP Fourms

|

Forms are the most fundamental method of interaction for your users. Users must use a form to enter information into a site. Think about it, every bulletin board, shopping cart, feedback form, and poll is a type of form. Without forms, the Web is nothing more than a publishing medium for those who can FTP Web pages up to a server.



GET & POST Methods:

There are two methods that you can use when creating a form in HTML. They are post and get, as in:



< action="”saveinfo.php”" method="post">

or:

< action="”saveinfo.php”" method="get">


If you don't specify a method, then the Web server assumes that you are using the get method. So what's the deal? They do the same thing right? Well, almost. You may have noticed that the URL looks a lot longer after you submit a form that uses the get method. For example, you may see something like:
http://www.krazy4mobile.com/form.php?name=fred&age=20&comments=This+site+rocks


That's because the get method puts the contents of the form right in the URL. There are a few disadvantages to this. First, depending on your Web server's operating system and software, there is a limit to how much data you can send through a form using the get method. On many systems, this limit is 256 characters. Also, the individual get queries may be stored in your Web server logs. If you are using space on a shared server, then other people may be able to decipher data sent from your forms that use the get method.
The post method was created to correct the inadequacies of the get method. The information sent using the post method is not visible in the URL, and form data cannot be deciphered by looking in the Web server logs. There also isn't such a small limit on the amount of data that can be sent from a form. Again, it depends on your server, but you probably won't ever hit the limit of sending data using the post method for a text-based form.

I use the post method for my scripts unless I need to debug something. When you need to debug something on a form, it is easy enough to switch to the get method (by changing the action line in your script) and then check the URL after you submit your buggy form. You can usually pick up typos and such with a quick look.


< action="display.php" method="get">

Name: < type="text" name="name">

Age: < type="text" name="age">

< type="submit">

< / form >



When you click the "Submit" button on the form the URL sent could look something like this:

http://www.krazy4mobile.com/display.php?name=adam&age=22

On display.php page you can retrieve the value by using the following code

Welcome .


You are years old!

The $_REQUEST Variable:

The PHP $_REQUEST variable can be used as the replacement of $_GET, $_POST, and $_COOKIE. The $_REQUEST variable can be used to get the result from form data sent with both the GET and POST methods.

Example:

< action="display.php" method="post">

Enter your name: < type="text" name="name">

Enter your age: < type="text" name="age">

< type="submit">

< /form >

When you click the Submit button on the form, following URL will be sent.

http://www.krazy4mobile.com/display.php

On display.php page you can retrieve the value as

Welcome < ?php echo $_POST["name"]; ?> .
YOU are < ?php echo $_POST["age"]; ?> . years old!

PHP Functions

|

In addition to PHP's built-in functions, you can create your own functions. Remember that if you want to use variables that exist outside of the function, then you must declare them as global variables or assign them as arguments to the function itself.

function check_age($age) {

if ($age > 21) {

return 1;

} else {

return 0;

}

}

//usage:

if(check_age($age)) {

echo "You may enter!";

} else {

echo "Access Not Allowed!";

exit();

}

The function would be called from within your script at the appropriate time, using the following syntax:

$age = 10;

check_age($age);


Example:

function simpletable($text) {

print("

");

print("");

print("
$text
");

}

phpinfo( )

phpinfo() is a very useful function that allows you to see what version of PHP is running on your Web server, as well as all of the specific settings that are enabled in that version.



phpinfo();

?>

PHP Loops

|

Loops are used to repeat statement or block of statement more than one time. The idea of a loop is to do something over and over again until the task has been completed


In PHP we have the following looping statements:

For Loop:

For loops are useful constructions to loop through a finite set of data, such as data in an array.
Syntax:

for ( initialization; conditional statement; increment/decrement){

statement(s);

}

1. Initialization—You can pass in an already assigned variable or assign a value to the variable in the for statement.

2. The condition required to continue the for loop— The statements are executed until the given condition goes false.

3. Statement to modify the counter on each pass of the loop.



Example:


for ($i=1; $i<=10; $i++)

{

echo "Hello World
";


}

?>

Foreach Loop:

Foreach loops allow you to quickly traverse through an array.

$array = array("name" => "Jet", "occupation" => "Bounty Hunter" );

foreach ($array as $val) {

echo "

$val";



}

Prints out:

Jet



Bounty Hunter



You can also use foreach loops to get the key of the values in the array:

foreach ($array as $key => $val) {

echo "

$key : $val";



}


Prints out:

name : Jet



occupation : Bounty Hunter


While Loop:

While loops are another useful construct to loop through data. While loops continue to loop until the expression in the while loop evaluates to false. A common use of the while loop is to return the rows in an array from a result set. The while loop continues to execute until all of the rows have been returned from the result set.

Syntax:

while (condition){

statement(s);


Example:



$i=1;

while($i<=9)

{

echo "The number is " . $i . "
";


$i++;

}

?>

Do-While Loop:

Do while loops are another useful loop construct. Do while loops work exactly the same as normal while loops, except that the script evaluates the while expression after the loop has completed, instead of before the loop executes, as in a normal while loop.

The important difference between a do while loop and a normal while loop is that a do while loop is always executed at least once. A normal while loop may not be executed at all, depending on the expression. The following do while loop is executed one time, printing out $i to the screen:

$i = 0;

do {

print $i;

} while ($i>0);

Whereas the following is not executed at all:

$i = 0;

while($i > 0) {

print $i;

}
Arrays:

An array is a data structure that stores one or more values in a single value. PHP supports both numerical arrays (array items are indexed by their numerical order) as well as associative arrays (array items are indexed by named keys).
Example:

$a = array(1, 2, 3, 4);

//$a[0] = 1

//$a[1] = 2

//$a[2] = 3

//$a[3] = 4

$b = array("name"=>"Fred", "age" => 30);

//$b['name'] = "Fred"

//$b['age'] = 30

}

PHP Control Structure

|

If ... Else Statement

One of the most common PHP language constructs that you will encounter is the if…then statement. The if…then statement allows you to evaluate an expression and then, depending if it is true or not, take a course of action. For example:


$x = 1;
if($x) {

echo "True!";
}

Since $x = 1, then PHP interprets it in the context of the if statement to be a boolean type. Since 1 = true, the if statements prints out the message. Literally you can read it as "If True, then print out "True!".
Another example, but this time with an "else" clause:

$a = 5;
$b = "10";

if($a > $b) {
echo "$a is greater than $b";

} else {
echo "$a is not greater than $b";

}


PHP doesn't care that $a is an integer and $b is a string. It recognizes that $b also makes a pretty good integer as well. It then evaluates the expression, "If $a is greater than $b then print out that $a is greater than $b; if not (else) then print out $a is not greater than $b." It's also important to note that you don't say, "$a is less than $b," since it is possible that $a could be equal to $b. If that is the case, then the second part of the expression, the else statement, is the part that runs.

Note the use of brackets to enclose the actions. Also note the lack of semicolons where the brackets are used.
One final example is the if…elseif…else statement:

if($a == $b) {
// do something

} elseif ($a > $b) {
// do something else

} elseif($a < $b) {
// do yet something else

} else {
// if nothing else we do this...

}

Switch Statement:


The Switch statement is used to perform one of several different actions based on one of several different conditions. Switch statements allow for additional evaluations of the data, even though one of the cases may have been met. Switch statements can also save you from typing many if…elseif…elseif… statements.

Syntax:

switch (expression)

{

case label1:

Statement(s);

break;

case label2:

Statement(s);

break;

default:

Statement(s);

}


Example:

$a = "100";
switch($a) {

case(10):
echo "The value is 10";

break;
case (100):

echo "The value is 100
";

case (1000):

echo "The value is 1000";
break;

default:
echo "

Wrong Input"

}

switch statements have four basic parts:

1. The switch— The switch identifies what value or expression is going to be evaluated in each of the cases. In the example above, you tell the switch statement that you are going to evaluate the variable $a in the subsequent cases.

2. The case— The case statement evaluates the variable you passed from the switch command. You can use case() the same way you'd use an if statement. If the case holds true, then everything after the case statement is executed, until the parser encounters a break command, at which point execution stops and the switch is exited.

3. Breakpoints— Defined by the break command, exit the parser from the switch. Breakpoints are normally put after statements executed when a case() is met.

4. Default— The default is a special kind of case. It is executed if none of the other case statements in the switch have been executed.

PHP Operators

|

Operators are used to manipulate or perform operations on variables and values. There are many operators used in PHP, we

have separated them into the following categories.


# Assignment Operators

# Arithmetic Operators

# Comparison Operators

# Logical Operators


Assignment operators are used to set a variable equal to a value or set a variable to another variable's value. ‘=’ is


used for assignment operator.
Example:


$var = 23;

$var2 = $var;



OperatorExampleIs The Same As
=a=ba=b
+=a+=ba=a+b
-=a-=ba=a-b
*=a*=ba=a*b
/=a/=ba=a/b
.= a.=ba=a.b
%=a%=ba=a%b



Arithmetic Operators:


OperatorFunction
+Addition
-Subtraction
*Multiplication
/Division
%Modulus (division remainder)
++Increment
--Decrement



OperatorFunction ExampleResult
== Equal To$x == $yfalse
!= Not Equal To$x != $ytrue
< Less Than$x < $y true
>Greater Than$x > $y false
<= Less Than or Equal To$x <= $y true
>= Greater Than or Equal To$x >= $y false


Logical Operators:



OperatorFunctionExample
&&andx=8 y=4
(x <> 1) returns true
||or x=12
y=8
(x>=5 || y<=5) returns true
!notx=6
y=3
!(x==y) returns true