PHP by mehdizidanebook

VIEWS: 0 PAGES: 93

									                                         PHP & MYSQL

                                             UNIT-1

What is PHP ?

   PHP is a powerful tool for making dynamic and interactive Web pages.
   PHP is the widely-used, free, and efficient alternative to competitors such as Microsoft's
   ASP.
   In our PHP tutorial you will learn about PHP, and how to execute scripts on your server.

What You Should Already Know
Before you continue you should have a basic understanding of the following:
    HTML/XHTML
    JavaScript

What is PHP?
   PHP stands for PHP: Hypertext Preprocessor
   PHP is a server-side scripting language, like ASP
   PHP scripts are executed on the server
   PHP supports many databases (MySQL, MSSQL Server, Informix, Oracle, Sybase, Solid,
      PostgreSQL, Generic ODBC, etc.)
   PHP is an open source software
   PHP is free to download and use

What is a PHP File?
   PHP files can contain text, HTML tags and scripts
   PHP files are returned to the browser as plain HTML
   PHP files have a file extension of ".php", ".php3", or ".phtml"

What is MySQL?
   MySQL is a database server
   MySQL is ideal for both small and large applications
   MySQL supports standard SQL
   MySQL compiles on a number of platforms
   MySQL is free to download and use

PHP + MySQL
   PHP combined with MySQL are cross-platform (you can develop in Windows and serve
      on a Unix platform)

Why PHP?
   PHP runs on different platforms (Windows, Linux, Unix, etc.)
   PHP is compatible with almost all servers used today (Apache, IIS, etc.)
   PHP is FREE to download from the official PHP resource: www.php.net
   PHP is easy to learn and runs efficiently on the server side

Features/Characteristics of PHP
Following are the main features of Hypertext Preprocessor
      Speed of Development

   Because PHP allows you to separate HTML code from scripted elements, you will notice a
   significant decrease in development time on many projects. In many instances, you will be
   able to separate the coding stage of a project from the design and build stages. Not only can
   this make file easier for you as a programmer, but it also can remove obstacles that stand in
   the way of effective and flexible design.

      PHP is Open Source

   To many people, open source simply means free, which is, of course, a benefit in itself. Well-
   maintained open source projects offer users additional benefits. You benefit from an
   accessible and committed community that offers a wealth of experience in the subject.
   Chances are that any problem you encounter in your coding can be answered swiftly and
   easily with a little research. If that fails, a question sent to a mailing list can yield an
   intelligent, authoritative response.

   You also can be sure that bugs will be addressed as they are found, and that new features will
   be made available as the need is defined. You will not have to wait for the next commercial
   release before taking advantage of improvements.

   There is no vested interest in a particular server product or operating system. You are free to
   make choices that suit your needs or those of your clients, secure that your code will run
   whatever you decide.

      Performance

   Because of the powerful Zend engine, PHP shows solid performance compared with other
   server scripting languages, such as ASP, Perl, and Java Servlets, in benchmark test. To
   further improve performance, you can acquire a caching tool (Zend Accelerator) from http://
   www.zend .com/; it stores compiled code in memory, eliminating the over headed of parsing
   and interpreting sources files for every request.

      Portability

   PHP is designed to run on many operating systems and to cooperate with many servers and
   databases. You can build for a Unix environment and shift your work to NT without a
   problem. You can test a project with Personal Web Server and install it on a Unix system
   running on PHP as an Apache Module.


Where to Start?
To get access to a web server with PHP support, you can:
    Install Apache (or IIS) on your own server, install PHP, and MySQL
    Or find a web hosting plan with PHP and MySQL support
   The PHP script is executed on the server, and the plain HTML result is sent back to the
   browser.
                                             UNIT - 2

Basic PHP Syntax
       A PHP script always starts with <?php and ends with ?>. A PHP script can be placed
       anywhere in the document.
       On servers with shorthand-support, you can start a PHP script with <? and end with ?>.
       For maximum compatibility, we recommend that you use the standard form (<?php)
       rather than the shorthand form.

       <?php
       ?>

       Below, we have an example of a simple PHP script that sends the text "Hello World"
       back to the browser:
       <html>
       <body>

       <?php
       echo "Hello World";
       ?>

       </body>
       </html>
       Each code line in PHP must end with a semicolon. The semicolon is a separator and is
       used to distinguish one set of instructions from another.
       There are two basic statements to output text with PHP: echo and print.
       In the example above we have used the echo statement to output the text "Hello World".

Comments in PHP
    In PHP, we use // to make a one-line comment or /* and */ to make a comment block:
    <html>
    <body>

       <?php
       //This is a comment

       /*
       This is
       a comment
       block
       */
       ?>

       </body>
       </html>

PHP Variables

Variables are "containers" for storing information.

PHP variables are used to hold values or expressions.

A variable can have a short name, like x, or a more descriptive name, like carName.
Rules for PHP variable names:

      Variables in PHP starts with a $ sign, followed by the name of the variable
      The variable name must begin with a letter or the underscore character
      A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9,
       and _ )
      A variable name should not contain spaces
      Variable names are case sensitive (y and Y are two different variables)

Creating (Declaring) PHP Variables

PHP has no command for declaring a variable.

A variable is created the moment you first assign a value to it:

$myCar="Volvo";

After the execution of the statement above, the variable myCar will hold the value Volvo.

Tip: If you want to create a variable without assigning it a value, then you assign it the value of
null.

Let's create a variable containing a string, and a variable containing a number:

<?php
$txt="Hello World!";
$x=16;
?>

Note: When you assign a text value to a variable, put quotes around the value.

PHP is a Loosely Typed Language

In PHP, a variable does not need to be declared before adding a value to it.

In the example above, notice that we did not have to tell PHP which data type the variable is.

PHP automatically converts the variable to the correct data type, depending on its value.

In a strongly typed programming language, you have to declare (define) the type and name of the
variable before using it.

PHP Variable Scope

The scope of a variable is the portion of the script in which the variable can be referenced.

PHP has four different variable scopes:

      local
      global
      static
      parameter

Local Scope

A variable declared within a PHP function is local and can only be accessed within that function.
(the variable has local scope):

<?php
$a = 5; // global scope

function myTest()
{
echo $a; // local scope
}

myTest();
?>

The script above will not produce any output because the echo statement refers to the local scope
variable $a, which has not been assigned a value within this scope.

You can have local variables with the same name in different functions, because local variables
are only recognized by the function in which they are declared.

Local variables are deleted as soon as the function is completed.

Global Scope

Global scope refers to any variable that is defined outside of any function.

Global variables can be accessed from any part of the script that is not inside a function.

To access a global variable from within a function, use the global keyword:

<?php
$a = 5;
$b = 10;

function myTest()
{
global $a, $b;
$b = $a + $b;
}

myTest();
echo $b;
?>

The script above will output 15.
PHP also stores all global variables in an array called $GLOBALS[index]. Its index is the name
of the variable. This array is also accessible from within functions and can be used to update
global variables directly.

The example above can be rewritten as this:

<?php
$a = 5;
$b = 10;

function myTest()
{
$GLOBALS['b'] = $GLOBALS['a'] + $GLOBALS['b'];
}

myTest();
echo $b;
?>


Static Scope

When a function is completed, all of its variables are normally deleted. However, sometimes you
want a local variable to not be deleted.

To do this, use the static keyword when you first declare the variable:

static $rememberMe;

Then, each time the function is called, that variable will still have the information it contained
from the last time the function was called.

Note: The variable is still local to the function.

Parameters

A parameter is a local variable whose value is passed to the function by the calling code.

Parameters are declared in a parameter list as part of the function declaration:

function myTest($para1,$para2,...)
{
// function code
}

Parameters are also called arguments. We will discuss them in more detail when we talk about
functions.

String Variables in PHP
A string variable is used to store and manipulate text.

String variables are used for values that contain characters.

In this chapter we are going to look at the most common functions and operators used to
manipulate strings in PHP.

After we create a string we can manipulate it. A string can be used directly in a function or it can
be stored in a variable.

Below, the PHP script assigns the text "Hello World" to a string variable called $txt:

<?php
$txt="Hello World";
echo $txt;
?>

The output of the code above will be:

Hello World

Now, lets try to use some different functions and operators to manipulate the string.

The Concatenation Operator

There is only one string operator in PHP.

The concatenation operator (.) is used to put two string values together.

To concatenate two string variables together, use the concatenation operator:

<?php
$txt1="Hello World!";
$txt2="What a nice day!";
echo $txt1 . " " . $txt2;
?>

The output of the code above will be:

Hello World! What a nice day!

If we look at the code above you see that we used the concatenation operator two times. This is
because we had to insert a third string (a space character), to separate the two strings.

The strlen() function

The strlen() function is used to return the length of a string.

Let's find the length of a string:
<?php
echo strlen("Hello world!");
?>

The output of the code above will be:

12

The length of a string is often used in loops or other functions, when it is important to know
when the string ends. (i.e. in a loop, we would want to stop the loop after the last character in the
string).

The strpos() function

The strpos() function is used to search for a character/text within a string.

If a match is found, this function will return the character position of the first match. If no match
is found, it will return FALSE.

Let's see if we can find the string "world" in our string:

<?php
echo strpos("Hello world!","world");
?>

The output of the code above will be:

6

The position of the string "world" in the example above is 6. The reason that it is 6 (and not 7), is
that the first character position in the string is 0, and not 1.


PHP Operators

The assignment operator = is used to assign values to variables in PHP.

The arithmetic operator + is used to add values together.

Arithmetic Operators

The table below lists the arithmetic operators in PHP:

Operator     Name                 Description                   Example                     Result
x+y          Addition             Sum of x and y                2+2                         4
x-y          Subtraction          Difference of x and y         5-2                         3
x*y          Multiplication       Product of x and y            5*2                         10
x/y          Division             Quotient of x and y           15 / 5                      3
x%y          Modulus              Remainder of x divided by     5%2                         1
                                  y                             10 % 8                          2
                                                                10 % 2                          0
-x           Negation             Opposite of x                 -2
a.b          Concatenation        Concatenate two strings       "Hi" . "Ha"                     HiHa

Assignment Operators

The basic assignment operator in PHP is "=". It means that the left operand gets set to the value
of the expression on the right. That is, the value of "$x = 5" is 5.

Assignment Same as...             Description
                                  The left operand gets set to the value of the expression on the
x=y          x=y
                                  right
x += y       x=x+y                Addition
x -= y       x=x-y                Subtraction
x *= y       x=x*y                Multiplication
x /= y       x=x/y                Division
x %= y       x=x%y                Modulus
a .= b       a=a.b                Concatenate two strings

Incrementing/Decrementing Operators

Operator   Name              Description
++ x       Pre-increment     Increments x by one, then returns x
x ++       Post-increment    Returns x, then increments x by one
-- x       Pre-decrement     Decrements x by one, then returns x
x --       Post-decrement    Returns x, then decrements x by one

Comparison Operators

Comparison operators allow you to compare two values:

Operator     Name                 Description                             Example
x==y         Equal                True if x is equal to y                 5= =8 returns false
                                  True if x is equal to y, and they are
x===y        Identical                                                    5= = ="5" returns false
                                  of same type
x != y       Not equal            True if x is not equal to y             5!=8 returns true
x <> y       Not equal            True if x is not equal to y             5<>8 returns true
                                  True if x is not equal to y, or they
x !== y      Not identical                                                5!=="5" returns true
                                  are not of same type
x>y          Greater than         True if x is greater than y             5>8 returns false
x<y          Less than            True if x is less than y                5<8 returns true
x >= y       Greater than or      True if x is greater than or equal to   5>=8 returns false
           equal to           y
           Less than or equal
x <= y                        True if x is less than or equal to y   5<=8 returns true
           to



Logical Operators

Operator   Name                Description                            Example
                                                                      x=6
x and y    And                 True if both x and y are true          y=3
                                                                      (x < 10 and y > 1) returns true
                                                                      x=61
                               True if either or both x and y are
x or y     Or                                                         y=3
                               true
                                                                      (x==6 or y==5) returns true
                                                                      x=6
                               True if either x or y is true, but not y=3
x xor y    Xor
                               both                                   (x= =6 xor y= =3) returns
                                                                      false
                                                                      x=6
x && y     And                 True if both x and y are true          y=3
                                                                      (x < 10 && y > 1) returns true
                                                                      x=6
                               True if either or both x and y are
x || y     Or                                                         y=3
                               true
                                                                      (x= =5 || y = =5) returns false
                                                                      x=6
!x         Not                 True if x is not true                  y=3
                                                                      !(x = = y) returns true

Array Operators

Operator   Name                Description
x+y        Union               Union of x and y
x==y       Equality            True if x and y have the same key/value pairs
                               True if x and y have the same key/value pairs in the same order
x===y      Identity
                               and of the same types
x != y     Inequality          True if x is not equal to y
x <> y     Inequality          True if x is not equal to y
x!==y      Non-identity        True if x is not identical to y


                                           UNIT - 3
PHP If...Else Statements
Conditional statements are used to perform different actions based on different conditions.

Conditional Statements

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.

In PHP we have the following conditional statements:

      if statement - use this statement to execute some code only if a specified condition is
       true
      if...else statement - use this statement to execute some code if a condition is true and
       another code if the condition is false
      if...elseif....else statement - use this statement to select one of several blocks of code to
       be executed
      switch statement - use this statement to select one of many blocks of code to be
       executed

The if Statement

Use the if statement to execute some code only if a specified condition is true.

Syntax
if (condition) code to be executed if condition is true;

The following example will output "Have a nice weekend!" if the current day is Friday:

<html>
<body>

<?php
$d=date("D");
if ($d=="Fri") echo "Have a nice weekend!";
?>

</body>
</html>

Notice that there is no ..else.. in this syntax. The code is executed only if the specified condition
is true.

The if...else Statement

Use the if....else statement to execute some code if a condition is true and another code if a
condition is false.
Syntax
if (condition)
  code to be executed if condition is true;
else
  code to be executed if condition is false;

Example

The following example will output "Have a nice weekend!" if the current day is Friday,
otherwise it will output "Have a nice day!":

<html>
<body>

<?php
$d=date("D");
if ($d=="Fri")
  echo "Have a nice weekend!";
else
  echo "Have a nice day!";
?>

</body>
</html>

If more than one line should be executed if a condition is true/false, the lines should be enclosed
within curly braces:

<html>
<body>

<?php
$d=date("D");
if ($d=="Fri")
  {
  echo "Hello!<br />";
  echo "Have a nice weekend!";
  echo "See you on Monday!";
  }
?>

</body>
</html>
The if...elseif....else Statement

Use the if....elseif...else statement to select one of several blocks of code to be executed.

Syntax
if (condition)
  code to be executed if condition is true;
elseif (condition)
  code to be executed if condition is true;
else
  code to be executed if condition is false;

Example

The following example will output "Have a nice weekend!" if the current day is Friday, and
"Have a nice Sunday!" if the current day is Sunday. Otherwise it will output "Have a nice day!":

<html>
<body>

<?php
$d=date("D");
if ($d=="Fri")
  echo "Have a nice weekend!";
elseif ($d=="Sun")
  echo "Have a nice Sunday!";
else
  echo "Have a nice day!";
?>

</body>
</html>


PHP Switch Statement

Conditional statements are used to perform different actions based on different conditions.

The PHP Switch Statement

Use the switch statement to select one of many blocks of code to be executed.

Syntax
switch (n)
{
case label1:
  code to be executed if n=label1;
  break;
case label2:
  code to be executed if n=label2;
  break;
default:
  code to be executed if n is different from both label1 and label2;
}

This is how it works: First we have a single expression n (most often a variable), that is
evaluated once. The value of the expression is then compared with the values for each case in the
structure. If there is a match, the block of code associated with that case is executed. Use break
to prevent the code from running into the next case automatically. The default statement is used
if no match is found.

Example
<html>
<body>

<?php
$x=1;
switch ($x)
{
case 1:
  echo "Number 1";
  break;
case 2:
  echo "Number 2";
  break;
case 3:
  echo "Number 3";
  break;
default:
  echo "No number between 1 and 3";
}
?>
</body>
</html>
PHP Looping :
Loops execute a block of code a specified number of times, or while a specified condition is
true.

PHP Loops

Often when you write code, you want the same block of code to run over and over again in a
row. Instead of adding several almost equal lines in a script we can use loops to perform a task
like this.

In PHP, we have the following looping statements:

      while - loops through a block of code while a specified condition is true
      do...while - loops through a block of code once, and then repeats the loop as long as a
       specified condition is true
      for - loops through a block of code a specified number of times
      foreach - loops through a block of code for each element in an array

while Loop

The while loop executes a block of code while a condition is true.

Syntax
while (condition)
 {
 code to be executed;
 }

Example

The example below defines a loop that starts with i=1. The loop will continue to run as long as i
is less than, or equal to 5. Loop is increased by 1 each time the loop runs:

<html>
<body>

<?php
$i=1;
while($i<=5)
 {
 echo "The number is " . $i . "<br />";
 $i++;
 }
?>
</body>
</html>

Output:

The number is 1
The number is 2
The number is 3
The number is 4
The number is 5

do...while Statement

The do...while statement will always execute the block of code once, it will then check the
condition, and repeat the loop while the condition is true.

Syntax
do
 {
 code to be executed;
 }
while (condition);

Example

The example below defines a loop that starts with i=1. It will then increment i with 1, and write
some output. Then the condition is checked, and the loop will continue to run as long as i is less
than, or equal to 5:

<html>
<body>

<?php
$i=1;
do
 {
 $i++;
 echo "The number is " . $i . "<br />";
 }
while ($i<=5);
?>

</body>
</html>
Output:

The number is 2
The number is 3
The number is 4
The number is 5
The number is 6

for Loop

The for loop is used when you know in advance how many times the script should run.

Syntax
for (init; condition; increment)
 {
 code to be executed;
 }

Parameters:

      init: Mostly used to set a counter (but can be any code to be executed once at the
       beginning of the loop)
      condition: Evaluated for each loop iteration. If it evaluates to TRUE, the loop continues.
       If it evaluates to FALSE, the loop ends.
      increment: Mostly used to increment a counter (but can be any code to be executed at
       the end of the iteration)

Note: The init and increment parameters above can be empty or have multiple expressions
(separated by commas).

Example

The example below defines a loop that starts with i=1. The loop will continue to run as long as i
is less than, or equal to 5. i will increase by 1 each time the loop runs:

<html>
<body>

<?php
for ($i=1; $i<=5; $i++)
 {
 echo "The number is " . $i . "<br />";
 }
?>
</body>
</html>

Output:

The number is 1
The number is 2
The number is 3
The number is 4
The number is 5

foreach Loop

The foreach loop is used to loop through arrays.

Syntax
foreach ($array as $value)
 {
 code to be executed;
 }

For every loop iteration, the value of the current array element is assigned to $value (and the
array pointer is moved by one) - so on the next loop iteration, you'll be looking at the next array
value.

Example

The following example demonstrates a loop that will print the values of the given array:

<html>
<body>

<?php
$x=array("one","two","three");
foreach ($x as $value)
 {
 echo $value . "<br />";
 }
?>

</body>
</html>

Output:
one
two
three


PHP Arrays
An array stores multiple values in one single variable.

What is an Array?

A variable is a storage area holding a number or text. The problem is, a variable will hold only
one value.

An array is a special variable, which can store multiple values in one single variable.

If you have a list of items (a list of car names, for example), storing the cars in single variables
could look like this:

$cars1="Saab";
$cars2="Volvo";
$cars3="BMW";

However, what if you want to loop through the cars and find a specific one? And what if you had
not 3 cars, but 300?

The best solution here is to use an array!

An array can hold all your variable values under a single name. And you can access the values
by referring to the array name.

Each element in the array has its own index so that it can be easily accessed.

In PHP, there are three kind of arrays:

       Numeric array - An array with a numeric index
       Associative array - An array where each ID key is associated with a value
       Multidimensional array - An array containing one or more arrays

Numeric Arrays

A numeric array stores each array element with a numeric index.

There are two methods to create a numeric array.

1. In the following example the index are automatically assigned (the index starts at 0):

$cars=array("Saab","Volvo","BMW","Toyota");

2. In the following example we assign the index manually:
$cars[0]="Saab";
$cars[1]="Volvo";
$cars[2]="BMW";
$cars[3]="Toyota";

Example

In the following example you access the variable values by referring to the array name and
index:

<?php
$cars[0]="Saab";
$cars[1]="Volvo";
$cars[2]="BMW";
$cars[3]="Toyota";
echo $cars[0] . " and " . $cars[1] . " are Swedish cars.";
?>

The code above will output:

Saab and Volvo are Swedish cars.

Associative Arrays

An associative array, each ID key is associated with a value.

When storing data about specific named values, a numerical array is not always the best way to
do it.

With associative arrays we can use the values as keys and assign values to them.

Example 1

In this example we use an array to assign ages to the different persons:

$ages = array("Peter"=>32, "Quagmire"=>30, "Joe"=>34);

Example 2

This example is the same as example 1, but shows a different way of creating the array:

$ages['Peter'] = "32";
$ages['Quagmire'] = "30";
$ages['Joe'] = "34";

The ID keys can be used in a script:
<?php
$ages['Peter'] = "32";
$ages['Quagmire'] = "30";
$ages['Joe'] = "34";

echo "Peter is " . $ages['Peter'] . " years old.";
?>

The code above will output:

Peter is 32 years old.

Multidimensional Arrays

In a multidimensional array, each element in the main array can also be an array. And each
element in the sub-array can be an array, and so on.

Example

In this example we create a multidimensional array, with automatically assigned ID keys:

$families = array
 (
 "Griffin"=>array
 (
 "Peter",
 "Lois",
 "Megan"
 ),
 "Quagmire"=>array
 (
 "Glenn"
 ),
 "Brown"=>array
 (
 "Cleveland",
 "Loretta",
 "Junior"
 )
 );

The array above would look like this if written to the output:
Array
(
[Griffin] => Array
  (
  [0] => Peter
  [1] => Lois
  [2] => Megan
  )
[Quagmire] => Array
  (
  [0] => Glenn
  )
[Brown] => Array
  (
  [0] => Cleveland
  [1] => Loretta
  [2] => Junior
  )
)

Example 2

Lets try displaying a single value from the array above:

echo "Is " . $families['Griffin'][2] .
" a part of the Griffin family?";

The code above will output:

Is Megan a part of the Griffin family?


                                            UNIT - 4


PHP Forms and User Input

The PHP $_GET and $_POST variables are used to retrieve information from forms, like user
input.

PHP Form Handling

The most important thing to notice when dealing with HTML forms and PHP is that any form
element in an HTML page will automatically be available to your PHP scripts.
Example

The example below contains an HTML form with two input fields and a submit button:

<html>
<body>
<form action="welcome.php" method="post">
Name: <input type="text" name="fname" />
Age: <input type="text" name="age" />
<input type="submit" />
</form>
</body>
</html>

When a user fills out the form above and clicks on the submit button, the form data is sent to a
PHP file, called "welcome.php":

"welcome.php" looks like this:

<html>
<body>
Welcome <?php echo $_POST["fname"]; ?>!<br />
You are <?php echo $_POST["age"]; ?> years old.
</body>
</html>

Output could be something like this:

Welcome John!
You are 28 years old.

The PHP $_GET and $_POST variables will be explained in the next chapters.

Form Validation

User input should be validated on the browser whenever possible (by client scripts). Browser
validation is faster and reduces the server load.

You should consider server validation if the user input will be inserted into a database. A good
way to validate a form on the server is to post the form to itself, instead of jumping to a different
page. The user will then get the error messages on the same page as the form. This makes it
easier to discover the error.

In PHP, the predefined $_GET variable is used to collect values in a form with method="get".

The $_GET Variable
The predefined $_GET variable is used to collect values in a form with method="get"

Information sent from a form with the GET method is visible to everyone (it will be displayed in
the browser's address bar) and has limits on the amount of information to send.

Example
<form action="welcome.php" method="get">
Name: <input type="text" name="fname" />
Age: <input type="text" name="age" />
<input type="submit" />
</form>

When the user clicks the "Submit" button, the URL sent to the server could look something like
this:

http://www.w3schools.com/welcome.php?fname=Peter&age=37

The "welcome.php" file can now use the $_GET variable to collect form data (the names of the
form fields will automatically be the keys in the $_GET array):

Welcome <?php echo $_GET["fname"]; ?>.<br />
You are <?php echo $_GET["age"]; ?> years old!

When to use method="get"?

When using method="get" in HTML forms, all variable names and values are displayed in the
URL.

Note: This method should not be used when sending passwords or other sensitive information!

However, because the variables are displayed in the URL, it is possible to bookmark the page.
This can be useful in some cases.

Note: The get method is not suitable for very large variable values. It should not be used with
values exceeding 2000 characters.

In PHP, the predefined $_POST variable is used to collect values in a form with method="post".

The $_POST Variable

The predefined $_POST variable is used to collect values from a form sent with method="post".

Information sent from a form with the POST method is invisible to others and has no limits on
the amount of information to send.

Note: However, there is an 8 Mb max size for the POST method, by default (can be changed by
setting the post_max_size in the php.ini file).
Example
<form action="welcome.php" method="post">
Name: <input type="text" name="fname" />
Age: <input type="text" name="age" />
<input type="submit" />
</form>

When the user clicks the "Submit" button, the URL will look like this:

http://www.w3schools.com/welcome.php

The "welcome.php" file can now use the $_POST variable to collect form data (the names of the
form fields will automatically be the keys in the $_POST array):

Welcome <?php echo $_POST["fname"]; ?>!<br />
You are <?php echo $_POST["age"]; ?> years old.

When to use method="post"?

Information sent from a form with the POST method is invisible to others and has no limits on
the amount of information to send.

However, because the variables are not displayed in the URL, it is not possible to bookmark the
page.

The PHP $_REQUEST Variable

The predefined $_REQUEST variable contains the contents of both $_GET, $_POST, and
$_COOKIE.

The $_REQUEST variable can be used to collect form data sent with both the GET and POST
methods.

Note: A cookie, also known as an HTTP cookie, web cookie, or browser cookie, is usually a
small piece of data sent from a website and stored in a user's web browser while a user is
browsing a website. When the user browses the same website in the future, the data stored in the
cookie can be retrieved by the website to notify the website of the user's previous activity.

Example
Welcome <?php echo $_REQUEST["fname"]; ?>!<br />
You are <?php echo $_REQUEST["age"]; ?> years old.
                                             UNIT – 5


PHP Functions
The real power of PHP comes from its functions. In PHP, there are more than 700 built-in
functions.

PHP Built-in Functions

For a complete reference and examples of the built-in functions, please visit:
http://www.w3schools.com/php/default.asp

String Functions

1) chr( )

   The chr() function returns a character from the specified ASCII value.

   Syntax

   chr(ascii)

   Parameter       Description
   Ascii Required. An ASCII value

   Tips and Notes

   Note: The x parameter can be specified in decimal, octal, or hex values. Octal values are
   defined by a leading 0, while hex values are defined by a leading 0x.

   Example

   <?php
   echo chr(52)."<br />";
   echo chr(052)."<br />";
   echo chr(0x52)."<br />";
   ?>

   The output of the code above will be:

   4
   *
   R

2) ord( )
   The ord() function returns the ASCII value of the first character of a string.

   Syntax

   ord(string)
   Parameter Description
   String    Required. The string to get an ASCII value from

   Example

   <?php
   echo ord("h")."<br />";
   echo ord("hello")."<br />";
   ?>

   The output of the code above will be:

   104
   104

3) strtolower( )

   The strtolower() function converts a string to lowercase.
   Syntax
   strtolower(string)

   Parameter Description
   string    Required. Specifies the string to convert

   Example
   <?php
   echo strtolower("Hello WORLD.");
   ?>
   The output of the code above will be:
   hello world.

4) strtoupper( )

   The strtoupper() function converts a string to uppercase.
   Syntax
   strtoupper(string)

   Parameter Description
   string    Required. Specifies the string to convert

   Example
   <?php
   echo strtoupper("Hello WORLD!");
   ?>
   The output of the code above will be:
   HELLO WORLD!
5) strlen( )
   The strlen() function returns the length of a string.
   Syntax
   strlen(string)

   Parameter Description
   string    Required. Specifies the string to check

   Example
   <?php
   echo strlen("Hello world!");
   ?>
   The output of the code above will be:
   12

6) ltrim( )

   The ltrim() function will remove whitespaces or other predefined character from the left side
   of a string.

   Syntax

   ltrim(string,charlist)

   Parameter            Description
   string               Required. Specifies the string to check
   charlist             Optional. Specifies which characters to remove from the string. If omitted,
                        all of the following characters are removed:

                               "\0" - NULL
                               "\t" - tab
                               "\n" - new line
                               "\x0B" - vertical tab
                               "\r" - carriage return
                               " " - ordinary white space


   Example 1

   <html>
   <body>
   <?php
   $str = " Hello World!";
   echo "Without ltrim: " . $str;
   echo "<br />";
   echo "With ltrim: " . ltrim($str);
   ?>
   <body>
   <html>
   The browser output of the code above will be:

   Without ltrim: Hello World!
   With ltrim: Hello World!

   If you select "View source" in the browser window, you will see the following HTML:

   <html>
   <body>
   Without ltrim:    Hello World!<br />With ltrim: Hello World!
   </body>
   </html>

   Example 2

   <?php
   $str = "\r\nHello World!";
   echo "Without ltrim: " . $str;
   echo "<br />";
   echo "With ltrim: " . ltrim($str);
   ?>

   The browser output of the code above will be:

   Without ltrim: Hello World!
   With ltrim: Hello World!

   If you select "View source" in the browser window, you will see the following HTML:

   <html>
   <body>
   Without ltrim:
   Hello World!<br />With ltrim: Hello World!
   </body>
   </html>


7) rtrim( )

   The rtrim() function will remove whitespaces or other predefined character from the right
   side of a string.

   Syntax

   rtrim(string,charlist)


   Parameter            Description
   string               Required. Specifies the string to check
   charlist             Optional. Specifies which characters to remove from the string. If omitted,
                    all of the following characters are removed:

                           "\0" - NULL
                           "\t" - tab
                           "\n" - new line
                           "\x0B" - vertical tab
                           "\r" - carriage return
                           " " - ordinary white space


Example 1

<html>
<body>
<?php
$str = "Hello World! ";
echo "Without rtrim: " . $str;
echo "<br />";
echo "With rtrim: " . rtrim($str);
?>
<body>
<html>

The browser output of the code above will be:

Without rtrim: Hello World!
With rtrim: Hello World!

If you select "View source" in the browser window, you will see the following HTML:

<html>
<body>
Without rtrim: Hello World!     <br />With rtrim: Hello World!
</body>
</html>

Example 2

<?php
$str = "Hello World!\r\n";
echo "Without rtrim: " . $str;
echo "<br />";
echo "With rtrim: " . rtrim($str);
?>

The browser output of the code above will be:

Without rtrim: Hello World!
With rtrim: Hello World!
   If you select "View source" in the browser window, you will see the following HTML:

   <html>
   <body>
   Without rtrim: Hello World!
   <br />With rtrim: Hello World!
   </body>
   </html>


8) substr( )

   The substr() function returns a part of a string.

   Syntax
   substr(string,start,length)

   Parameter            Description
   string               Required. Specifies the string to return a part of
   start                Required. Specifies where to start in the string
                             A positive number - Start at a specified position in the string
                             A negative number - Start at a specified position from the end of the
                                 string
                             0 - Start at the first character in string
   Length               Optional. Specifies the length of the returned string. Default is to the end of
                        the string.
                             A positive number - The length to be returned from the start
                                 parameter
                             Negative number - The length to be returned from the end of the
                                 string

   Tips and Notes
   Note: If start is a negative number and length is less than or equal to start, length becomes 0.

   Example 1
   <?php
   echo substr("Hello world!",6);
   ?>
   The output of the code above will be:
   world!
   Example 2
   <?php
   echo substr("Hello world!",6,5);
   ?>
   The output of the code above will be:
   world


9) strcmp( )
   Definition and Usage
   The strcmp() function compares two strings.
   This function returns:
        0 if the two strings are equal
        <0 if string1 is less than string2
        >0 if string1 is greater than string2
   Syntax
   strcmp(string1,string2)

   Parameter Description
   string1   Required. Specifies the first string to compare
   string2   Required. Specifies the second string to compare

   Tips and Notes
   Note: The strcmp() function is binary safe and case-sensitive.

   Example
   <?php
   echo strcmp("Hello world!","Hello world!");
   ?>
   The output of the code above will be:
   0

10) strcasecmp( )

   The strcasecmp() function compares two strings.
   This function returns:
       0 if the two strings are equal
       <0 if string1 is less than string2
       >0 if string1 is greater than string2

       Syntax
       strcasecmp(string1,string2)

     Parameter Description
     string1   Required. Specifies the first string to compare
     string2   Required. Specifies the second string to compare

        Tips and Notes
        Tip: The strcasecmp() function is binary safe and case-insensitive.
        Example
        <?php
        echo strcasecmp("Hello world!","HELLO WORLD!");
        ?>
        The output of the code above will be:
        0
11) strpos( )
    The strpos( ) function returns the position of the first occurrence of a string inside another
    string.
    If the string is not found, this function returns FALSE.
    Syntax
    strpos(string,find,start)

    Parameter Description
    String    Required. Specifies the string to search
    Find      Required. Specifies the string to find
    Start     Optional. Specifies where to begin the search

    Tips and Notes
    Note: The strpos() function is case-sensitive.

    Example
    <?php
    echo strpos("Hello world!","wo");
    ?>
    The output of the code above will be:
    6

12) strrpos ( )

    The strrpos() function finds the position of the last occurrence of a string inside another
    string.
    This function returns the position on success, otherwise it returns FALSE.

    Syntax
    strrpos(string,find,start)

    Parameter Description
    String    Required. Specifies the string to search
    Find      Required. Specifies the string to find
    Start     Optional. Specifies where to begin the search

    Tips and Notes
    Note: The strrpos() function is case-sensitive.

    Example
    <?php
    echo strrpos("Hello world!","wo");
    ?>
    The output of the code above will be:
    6



13) strripos ( )
    The strripos( ) function finds the position of the last occurrence of a string inside another
    string.
    This function returns the position on success, otherwise it returns FALSE.
    Syntax
    strripos(string,find,start)

    Parameter Description
    String    Required. Specifies the string to search
    Find      Required. Specifies the string to find
    Start     Optional. Specifies where to begin the search

    Tips and Notes
    Note: The strripos() function is case-insensitive.

    Example
    <?php
    echo strripos("Hello world!","WO");
    ?>
    The output of the code above will be:
    6

14) 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), or FALSE, if the string
    to search for is not found.

    Syntax
    strstr(string,search)

    Parameter               Description
    string                  Required. Specifies the string to search
    search                  Required. Specifies the string to search for. If this parameter is a number, it
                            will search for the character matching the ASCII value of the number

    Tips and Notes
    Note: This function is binary safe.
    Note: This function is case-sensitive. For a case-insensitive search, use stristr().

    Example 1
    <?php
    echo strstr("Hello world!","world");
    ?>
    The output of the code above will be:
    world!

    Example 2
    In this example we will search a string for the ASCII value of "o":
    <?php
    echo strstr("Hello world!",111);
    ?>
    The output of the code above will be:
    o world!

15) stristr( )

    The stristr() function searches for the first occurrence of a string inside another string.
    This function returns the rest of the string (from the matching point), or FALSE, if the string
    to search for is not found.
    Syntax
    stristr(string,search)

     Parameter           Description
     string              Required. Specifies the string to search
     search              Required. Specifies the string to search for. If this parameter is a number, it
                         will search for the character matching the ASCII value of the number

    Tips and Notes
    Note: This function is binary safe.
    Note: This function is case-insensitive. For a case-sensitive search, use strstr().

    Example 1

    <?php
    echo stristr("Hello world!","WORLD");
    ?>
    The output of the code above will be:
    world!

    Example 2
    In this example we will search a string for the ASCII value of "o":
    <?php
    echo stristr("Hello world!",111);
    ?>
    The output of the code above will be:
    o world!

16) str_replace( )

    The substr_replace() function replaces a part of a string with another string.
    Syntax
    substr_replace(string,replacement,start,length)

    Parameter           Description
    String              Required. Specifies the string to check
    Replacement         Required. Specifies the string to insert
    Start               Required. Specifies where to start replacing in the string
                              A positive number - Start replacing at the specified position in the
                               string
                            Negative number - Start replacing at the specified position from the
                               end of the string
                            0 - Start replacing at the first character in the string
    Length              Optional. Specifies how many characters should be replaced. Default is the
                        same length as the string.
                            A positive number - The length of string to be replaced
                            A negative number - How many characters should be left at end of
                               string after replacing
                            0 - Insert instead of replace


    Tips and Notes
    Note: If start is a negative number and length is less than or equal to start, length becomes 0.

    Example
    <?php
    echo substr_replace("Hello world","earth",6);
    ?>
    The output of the code above will be:
    Hello earth

17) strrev( )

    The strrev() function reverses a string.
    Syntax
    strrev(string)

    Parameter Description
    String    Required. Specifies the string to reverse

    Example
    <?php
    echo strrev("Hello World!");
    ?>
    The output of the code above will be:
    !dlroW olleH

18) echo( )

    The echo() function outputs one or more strings.

    Syntax
    echo(strings)

    Parameter Description
    strings   Required. One or more strings to be sent to the output

    Tips and Notes
Note: The echo() function is not actually a function, so you are not required to use
parentheses with it. However, if you want to pass more than one parameter to echo(), using
parentheses will generate a parse error.
Tip: The echo() function is slightly faster than print().
Tip: The echo() function has the following shortcut syntax. See example 5.

Example 1
<?php
$str = "Who's Kai Jim?";
echo $str;
echo "<br />";
echo $str."<br />I don't know!";
?>
The output of the code above will be:
Who's Kai Jim?
Who's Kai Jim?
I don't know!

Example 2
<?php
echo "This text
spans multiple
lines.";
?>
The output of the code above will be:
This text spans multiple lines.

Example 3
<?php
echo 'This ','string ','was ','made ','with multiple parameters';
?>
The output of the code above will be:
This string was made with multiple parameters

Example 4
Difference of single and double quotes. Single quotes will print the variable name, not the
value:
<?php
$color = "red";
echo "Roses are $color";
echo "<br />";
echo 'Roses are $color';
?>
The output of the code above will be:
Roses are red
Roses are $color

Example 5
Shortcut syntax:
<html>
<body>
    <?php
    $color = "red";
    ?>
    <p>Roses are <?=$color?></p>
    </body>
    </html>

19) print( )

    The print() function outputs one or more strings.
    Syntax
    print(strings)

    Parameter Description
    Strings   Required. One or more strings to be sent to the output

    Tips and Notes
    Note: The print() function is not actually a function, so you are not required to use
    parentheses with it.

    Tip: The print() function is slightly slower than echo().

    Example 1
    <?php
    $str = "Who's Kai Jim?";
    print $str;
    print "<br />";
    print $str."<br />I don't know!";
    ?>
    The output of the code above will be:
    Who's Kai Jim?
    Who's Kai Jim?
    I don't know!

    Example 2
    <?php
    print "This text
    spans multiple
    lines.";
    ?>
    The output of the code above will be:
    This text spans multiple lines.

    Example 3
    Difference of single and double quotes. Single quotes will print the variable name, not the
    value:
    <?php
    $color = "red";
    print "Roses are $color";
    print "<br />";
   print 'Roses are $color';
   ?>
   The output of the code above will be:
   Roses are red
   Roses are $color

Math Functions

1) abs( )

   The abs() function returns the absolute value of a number.
   Syntax
   abs(x)

   Parameter          Description
   X                  Required. A number. If the number is of type float, the return type is also
                      float, otherwise it is integer

   Example
   <?php
   echo(abs(6.7) . "<br />");
   echo(abs(-3) . "<br />");
   echo(abs(3));
   ?>
   The output of the code above will be:
   6.7
   3
   3

2) ceil( )

   The ceil() function returns the value of a number rounded UPWARDS to the nearest integer.
   Syntax
   ceil(x)

   Parameter Description
   X         Required. A number

   Example
   In the following example we will use the ceil() function on different numbers:
   <?php
   echo(ceil(0.60) . "<br />");
   echo(ceil(0.40) . "<br />");
   echo(ceil(5) . "<br />");
   echo(ceil(5.1) . "<br />");
   echo(ceil(-5.1) . "<br />");
   echo(ceil(-5.9))
   ?>
   The output of the code above will be:
   1
   1
   5
   6
   -5
   -5

3) floor( )

   The floor() function returns the value of a number rounded DOWNWARDS to the nearest
   integer.
   Syntax
   floor(x)

   Parameter Description
   x         Required. A number

   Example
   In this example we will use the floor() function on different numbers:
   <?php
   echo(floor(0.60) . "<br />");
   echo(floor(0.40) . "<br />");
   echo(floor(5) . "<br />");
   echo(floor(5.1) . "<br />");
   echo(floor(-5.1) . "<br />");
   echo(floor(-5.9))
   ?>
   The output of the code above will be:
   0
   0
   5
   5
   -6
   -6

4) round( )

   The round() function rounds a number to the nearest integer.
   Syntax
   round(x,prec)

   Parameter     Description
   x             Required. The number to be round
   prec          Optional. The number of digits after the decimal point

   Example
   In this example we will round different numbers with the round() function:
   <?php
   echo(round(0.60) . "<br />");
  echo(round(0.50) . "<br />");
  echo(round(0.49) . "<br />");
  echo(round(-4.40) . "<br />");
  echo(round(-4.60))
  ?>
  The output of the code above will be:
  1
  1
  0
  -4
  -5

5) fmod( )

  The fmod() function divides x by y and returns the remainder (modulo) of the division.

  Syntax
  fmod(x,y)

  Parameter Description
  x         Required. A number
  y         Required.

  Example
  In the following example we will use the fmod() function to return the remainder of 5/2:
  <?php
  $r = fmod(5,2);
  echo $r
  ?>
  The output of the code above will be:
  1


6) min( )

  The min() function returns the number with the lowest value of two specified numbers.
  Syntax
  min(x,y)

  Parameter Description
  X         Required. A number
  Y         Required. A number

  Example
  In this example we will show how to use min() to return the number with the lowest value of
  two specified numbers:
  <?php
  echo(min(5,7) . "<br />");
  echo(min(-3,5) . "<br />");
  echo(min(-3,-5) . "<br />");
  echo(min(7.25,7.30))
  ?>

  The output of the code above will be:
  5
  -3
  -5
  7.25

7) max( )

  The max() function returns the number with the highest value of two specified numbers.
  Syntax
  max(x,y)

Parameter Description
x         Required. A number
y         Required. A number

  Example
  In this example we will show how to use max() to return the number with the highest value
  of two specified numbers:
  <?php
  echo(max(5,7) . "<br />");
  echo(max(-3,5) . "<br />");
  echo(max(-3,-5) . "<br />");
  echo(max(7.25,7.30))
  ?>
  The output of the code above will be:
  7
  5
  -3
  7.3

8) pow( )

  The pow() function raises the first argument to the power of the second argument, and returns
  the result.
  Syntax
  pow(x,y)

  Parameter Description
  x         Required. Specifies the number to be raised
  y         Required. The power to which to raise the
            number

  Example
   <?php
   echo pow(4,2) . "<br />";
   echo pow(6,2) . "<br />";
   echo pow(-6,2) . "<br />";
   echo pow(-6,-2) . "<br />";
   echo pow(-6,5.5);
   ?>
   The output of the code above will be:
   16
   36
   36
   0.0277777777778
   -1.#IND

9) sqrt( )

   The sqrt() function returns the square root of a number.
   Syntax
   sqrt(x)

       Parameter Description
       X         Required. A number

   Tips and Notes
   Note: The sqrt() function will return -1.#IND if the parameter x is a negative number.

   Example
   In this example we will get the square root of different numbers:
   <?php
   echo(sqrt(0) . "<br />");
   echo(sqrt(1) . "<br />");
   echo(sqrt(9) . "<br />");
   echo(sqrt(0.64) . "<br />");
   echo(sqrt(-9))
   ?>

   The output of the code above will be:
   0
   1
   3
   0.8
   -1.#IND

10)    rand ( )

       The rand() function generates a random integer.
       If this function is called without parameters, it returns a random integer between 0 and
       RAND_MAX.
       If you want a random number between 10 and 100 (inclusive), use rand (10,100).
       Syntax
       rand(min,max)

       Parameter        Description
       min,max          Optional. Specifies the range the random number should lie
                        within

       Tips and Notes
       Note: On some platforms (such as Windows) RAND_MAX is only 32768. So, if you
       require a range larger than 32768, you can specify min and max, or use the mt_rand()
       function instead.
       Note: In PHP 4.2.0 and later, there is no need to seed the random generator with srand().
       This is done automatically.
       Tip: The mt_rand() function generates a better random value than this function!

       Example
       In this example we will return some random numbers:
       <?php
       echo(rand() . "<br />");
       echo(rand() . "<br />");
       echo(rand(10,100))
       ?>
       The output of the code above could be:
       17757
       3794
       97


Date Functions

1) date( )

   The date() function formats a local time/date.
   Syntax
   date(format,timestamp)

   Parameter           Description
   format              Required. Specifies how to return the result:
                           d - The day of the month (from 01 to 31)
                           D - A textual representation of a day (three letters)
                           j - The day of the month without leading zeros (1 to 31)
                           l (lowercase 'L') - A full textual representation of a day
                           N - The ISO-8601 numeric representation of a day (1 for Monday
                              through 7 for Sunday)
                           S - The English ordinal suffix for the day of the month (2 characters
                              st, nd, rd or th. Works well with j)
                           w - A numeric representation of the day (0 for Sunday through 6 for
                              Saturday)
                           z - The day of the year (from 0 through 365)
                           W - The ISO-8601 week number of year (weeks starting on Monday)
                           F - A full textual representation of a month (January through
                          December)
                         m - A numeric representation of a month (from 01 to 12)
                         M - A short textual representation of a month (three letters)
                         n - A numeric representation of a month, without leading zeros (1 to
                          12)
                       t - The number of days in the given month
                       L - Whether it's a leap year (1 if it is a leap year, 0 otherwise)
                       o - The ISO-8601 year number
                       Y - A four digit representation of a year
                       y - A two digit representation of a year
                       a - Lowercase am or pm
                       A - Uppercase AM or PM
                       B - Swatch Internet time (000 to 999)
                       g - 12-hour format of an hour (1 to 12)
                       G - 24-hour format of an hour (0 to 23)
                       h - 12-hour format of an hour (01 to 12)
                       H - 24-hour format of an hour (00 to 23)
                       i - Minutes with leading zeros (00 to 59)
                       s - Seconds, with leading zeros (00 to 59)
                       e - The timezone identifier (Examples: UTC, Atlantic/Azores)
                       I (capital i) - Whether the date is in daylights savings time (1 if
                          Daylight Savings Time, 0 otherwise)
                       O - Difference to Greenwich time (GMT) in hours (Example: +0100)
                       T - Timezone setting of the PHP machine (Examples: EST, MDT)
                       Z - Timezone offset in seconds. The offset west of UTC is negative,
                          and the offset east of UTC is positive (-43200 to 43200)
                       c - The ISO-8601 date (e.g. 2004-02-12T15:19:21+00:00)
                       r - The RFC 2822 formatted date (e.g. Thu, 21 Dec 2000 16:01:07
                          +0200)
                       U - The seconds since the Unix Epoch (January 1 1970 00:00:00
                          GMT)
timestamp          Optional.

Example
<?php
echo("Result with date():<br />");
echo(date("l") . "<br />");
echo(date("l dS \of F Y h:i:s A") . "<br />");
echo("Oct 3,1975 was on a ".date("l", mktime(0,0,0,10,3,1975))."<br />");
echo(date(DATE_RFC822) . "<br />");
echo(date(DATE_ATOM,mktime(0,0,0,10,3,1975)) . "<br /><br />");

echo("Result with gmdate():<br />");
echo(gmdate("l") . "<br />");
echo(gmdate("l dS \of F Y h:i:s A") . "<br />");
echo("Oct 3,1975 was on a ".gmdate("l", mktime(0,0,0,10,3,1975))."<br />");
echo(gmdate(DATE_RFC822) . "<br />");
echo(gmdate(DATE_ATOM,mktime(0,0,0,10,3,1975)) . "<br />");
?>
The output of the code above could be something like this:
   Result with date():
   Tuesday
   Tuesday 24th of January 2006 02:41:22 PM
   Oct 3,1975 was on a Friday
   Tue, 24 Jan 2006 14:41:22 CET
   1975-10-03T00:00:00+0100

   Result with gmdate():
   Tuesday
   Tuesday 24th of January 2006 01:41:22 PM
   Oct 3,1975 was on a Thursday
   Tue, 24 Jan 2006 13:41:22 GMT
   1975-10-02T23:00:00+0000

2) getdate ( )

   The getdate() function returns an array that contains date and time information for a Unix
   timestamp.
   The returning array contains ten elements with relevant information needed when formatting
   a date string:
        [seconds] - seconds
        [minutes] - minutes
        [hours] - hours
        [mday] - day of the month
        [wday] - day of the week
        [year] - year
        [yday] - day of the year
        [weekday] - name of the weekday
        [month] - name of the month
   Syntax
   getdate(timestamp)

   Parameter Description
   Timestamp Optional. Specifies the time in Unix time format

   Example 1
   <?php
   print_r(getdate());
   ?>
   The output of the code above could be:
   Array
   (
   [seconds] => 45
   [minutes] => 52
   [hours] => 14
   [mday] => 24
   [wday] => 2
   [mon] => 1
   [year] => 2006
   [yday] => 23
   [weekday] => Tuesday
   [month] => January
   [0] => 1138110765
   )
   Example 2
   <?php
   $my_t=getdate(date("U"));
   print("$my_t[weekday], $my_t[month] $my_t[mday], $my_t[year]");
   ?>
   The output of the code above could be:
   Wednesday, January 25, 2006

3) setdate( )

4) checkdate ( )

   The checkdate() function returns true if the specified date is valid, and false otherwise.
   A date is valid if:
       month is between 1 and 12 inclusive
       day is within the allowed number of days for the particular month
       year is between 1 and 32767 inclusive
   Syntax
   checkdate(month,day,year)

   Parameter Description
   month     Required. Specifies the month
   day       Required. Specifies the day
   year      Required. Specifies the year

   Example
   <?php
   var_dump(checkdate(12,31,2000));
   var_dump(checkdate(2,29,2003));
   var_dump(checkdate(2,29,2004));
   ?>
   The output of the code above will be:
   bool(true)
   bool(false)
   bool(true)

5) time( )

   The time() function returns the current time as a Unix timestamp (the number of seconds
   since January 1 1970 00:00:00 GMT).
   Syntax
   time(void)

   Parameter Description
   void      Optional.
   Tips and Notes
   Note: Calling this function is identical to calling mktime() with no parameters, or calling
   date("U").

   Example
   <?php
   $t=time();
   echo($t . "<br />");
   echo(date("D F d Y",$t));
   ?>
   The output of the code above could be:
   1138618081
   Mon January 30 2006

6) mktime( )

   The mktime() function returns the Unix timestamp for a date.
   This timestamp contains the number of seconds between the Unix Epoch (January 1 1970
   00:00:00 GMT) and the time specified.
   Syntax
   mktime(hour,minute,second,month,day,year,is_dst)

   Parameter           Description
   Hour                Optional. Specifies the hour
   Minute              Optional. Specifies the minute
   Second              Optional. Specifies the second
   Month               Optional. Specifies the numerical month
   Day                 Optional. Specifies the day
   Year                Optional. Specifies the year. The valid range for year is on some systems
                       between 1901 and 2038. However this limitation is overcome in PHP 5
   is_dst              Optional. Set this parameter to 1 if the time is during daylight savings time
                       (DST), 0 if it is not, or -1 (the default) if it is unknown. If it's unknown, PHP
                       tries to find out itself (which may cause unexpected results). Note: This
                       parameter became deprecated in PHP 5. The new timezone handling features
                       should be used instead.

   Tips and Notes
   Note: If the arguments are invalid, the function returns false (PHP versions before 5.1 returns
   -1).

   Example
   The mktime() function is useful for doing date arithmetic and validation. It will automatically
   calculate the correct value for out-of-range input:
   <?php
   echo(date("M-d-Y",mktime(0,0,0,12,36,2001))."<br />");
   echo(date("M-d-Y",mktime(0,0,0,14,1,2001))."<br />");
   echo(date("M-d-Y",mktime(0,0,0,1,1,2001))."<br />");
    echo(date("M-d-Y",mktime(0,0,0,1,1,99))."<br />");
    ?>
    The output of the code above would be:
    Jan-05-2002
    Feb-01-2002
    Jan-01-2001
    Jan-01-1999

Array Functions

1) count( )

    The count() function counts the elements of an array, or the properties of an object.
    Syntax
    count(array,mode)

    Parameter            Description
    Array                Required. Specifies the array or object to count.
    Mode                 Optional. Specifies the mode of the function. Possible values:
                             0 - Default. Does not detect multidimensional arrays (arrays within
                                arrays)
                             1 - Detects multidimensional arrays
                         Note: This parameter was added in PHP 4.2
    Tips and Notes
    Note: This function may return 0 if a variable isn't set, but it may also return 0 if a variable
    contains an empty array. The isset() function can be used to test if a variable is set.

    Example
    <?php
    $people = array("Peter", "Joe", "Glenn", "Cleveland");
    $result = count($people);

    echo $result;
    ?>
    The output of the code above will be:
    4

2) list( )

    The list() function is used to assign values to a list of variables in one operation.
    Syntax
    list(var1,var2...)
    Parameter Description
    var1          Required. The first variable to assign a value to
    var2          Optional. More variables to assign values to

    Tips and Notes
    Note: This function only works on numerical arrays.
    Example 1
   <?php
   $my_array = array("Dog","Cat","Horse");

   list($a, $b, $c) = $my_array;
   echo "I have several animals, a $a, a $b and a $c.";
   ?>
   The output of the code above will be:
   I have several animals, a Dog, a Cat and a Horse.

   Example 2
   <?php
   $my_array = array("Dog","Cat","Horse");

   list($a, , $c) = $my_array;
   echo "Here I only use the $a and $c variables.";
   ?>
   The output of the code above will be:
   Here I only use the Dog and Horse variables.

3) in_array( )

   The in_array() function searches an array for a specific value.
   This function returns TRUE if the value is found in the array, or FALSE otherwise.
   Syntax
   in_array(search,array,type)

   Parameter           Description
   search              Required. Specifies the what to search for
   array               Required. Specifies the array to search
   type                Optional. If this parameter is set, the in_array() function searches for the
                       search-string and specific type in the array
   Tips and Notes
   Note: If the search parameter is a string and the type parameter is set to TRUE, the search is
   case-sensitive.

   Example 1
   <?php
   $people = array("Peter", "Joe", "Glenn", "Cleveland");

   if (in_array("Glenn",$people))
     {
     echo "Match found";
     }
   else
     {
     echo "Match not found";
     }
   ?>
   The output of the code above will be:
   Match found
   Example 2
   <?php
   $people = array("Peter", "Joe", "Glenn", "Cleveland", 23);

   if (in_array("23",$people, TRUE))
     {
     echo "Match found<br />";
     }
   else
     {
     echo "Match not found<br />";
     }
   if (in_array("Glenn",$people, TRUE))
     {
     echo "Match found<br />";
     }
   else
     {
     echo "Match not found<br />";
     }

   if (in_array(23,$people, TRUE))
     {
     echo "Match found<br />";
     }
   else
     {
     echo "Match not found<br />";
     }
   ?>
   The output of the code above will be:
   Match not found Match found Match found

4) current( )

   The current() function returns the value of the current element in an array.
   Syntax
   current(array)

   Parameter Description
   array     Required. Specifies the array to use

   Tips and Notes
   Note: This function returns FALSE on empty elements or elements with no value.
   Tip: This function does not move the arrays internal pointer. To do this, use the next() and
   prev() functions.
   Example 1
   <?php
   $people = array("Peter", "Joe", "Glenn", "Cleveland");
   echo current($people) . "<br />";
   ?>
   The output of the code above will be:
   Peter

5) next( )

   The next() function moves the internal pointer to, and outputs, the next element in the array.
   This function returns the value of the next element in the array on success, or FALSE if there
   are no more elements.
   Syntax
   next(array)

   Parameter Description
   array     Required. Specifies the array to use

   Tips and Notes
   Note: This function returns FALSE on empty elements or elements with no value.

   Example
   <?php
   $people = array("Peter", "Joe", "Glenn", "Cleveland");

   echo current($people) . "<br />";
   echo next($people);
   ?>
   The output of the code above will be:
   Peter
   Joe

6) prev( )

   The prev() function moves the internal pointer to, and outputs, the previous element in the
   array.
   This function returns the value of the previous element in the array on success, or FALSE if
   there are no more elements.
   Syntax
   prev(array)

   Parameter Description
   array     Required. Specifies the array to use

   Tips and Notes
   Note: This function returns FALSE on empty elements or elements with no value.

   Example
   <?php
   $people = array("Peter", "Joe", "Glenn", "Cleveland");
   echo current($people) . "<br />";
   echo next($people) . "<br />";
   echo prev($people);
   ?>
   The output of the code above will be:
   Peter
   Joe
   Peter

7) end( )

   The end() function moves the internal pointer to, and outputs, the last element in the array.
   This function returns the value of the last element in the array on success.
   Syntax
   end(array)

   Parameter Description
   array     Required. Specifies the array to use

   Example
   <?php
   $people = array("Peter", "Joe", "Glenn", "Cleveland");

   echo current($people) . "<br />";
   echo end($people);
   ?>
   The output of the code above will be:
   Peter
   Cleveland

8) each( )

   The each() function returns the current element key and value, and moves the internal pointer
   forward.
   This element key an value is returned in an array with four elements. Two elements (1 and
   Value) for the element value, and two elements (0 and Key) for the element key.
   This function returns FALSE if there are no more array elements.
   Syntax
   each(array)

   Parameter Description
   Array       Required. Specifies the array to use
   Tips and Notes
   Note: This function returns FALSE on empty elements or elements with no value.

   Example 1
   <?php
   $people = array("Peter", "Joe", "Glenn", "Cleveland");
   print_r (each($people));
   ?>
   The output of the code above will be:
   Array ( [1] => Peter [value] => Peter [0] => 0 [key] => 0 )

   Example 2
   Same example as above, but with a loop to output the whole array:
   <?php
   $people = array("Peter", "Joe", "Glenn", "Cleveland");

   reset($people);

   while (list($key, $val) = each($people))
    {
    echo "$key => $val<br />";
    }
   ?>
   The output of the code above will be:
   0 => Peter
   1 => Joe
   2 => Glenn
   3 => Cleveland

9) sort( )

   The sort() function sorts an array by the values.
   This function assigns new keys for the elements in the array. Existing keys will be removed.
   This function returns TRUE on success, or FALSE on failure.
   Syntax
   sort(array,sorttype)

   Parameter           Description
   Array               Required. Specifies the array to sort
   Sorttype            Optional. Specifies how to sort the array values. Possible values:
                           SORT_REGULAR - Default. Treat values as they are (don't change
                              types)
                           SORT_NUMERIC - Treat values numerically
                           SORT_STRING - Treat values as strings
                           SORT_LOCALE_STRING - Treat values as strings, based on local
                              settings

   Example
   <?php
   $my_array = array("a" => "Dog", "b" => "Cat", "c" => "Horse");

   sort($my_array);
   print_r($my_array);
   ?>
   The output of the code above will be:
   Array
   (
   [0] => Cat
    [1] => Dog
    [2] => Horse
    )

10) rsort( )


    The rsort() function sorts an array by the values in reverse order.
    This function assigns new keys for the elements in the array. Existing keys will be removed.
    This function returns TRUE on success, or FALSE on failure.
    Syntax
    rsort(array,sorttype)

    Parameter           Description
    array               Required. Specifies the array to sort
    sorttype            Optional. Specifies how to sort the array values. Possible values:
                            SORT_REGULAR - Default. Treat values as they are (don't change
                               types)
                            SORT_NUMERIC - Treat values numerically
                            SORT_STRING - Treat values as strings
                            SORT_LOCALE_STRING - Treat values as strings, based on local
                               settings
    Example
    <?php
    $my_array = array("a" => "Dog", "b" => "Cat", "c" => "Horse");

    rsort($my_array);
    print_r($my_array);
    ?>
    The output of the code above will be:
    Array
    (
    [0] => Horse
    [1] => Dog
    [2] => Cat
    )

11) asort( )

    The asort() function sorts an array by the values. The values keep their original keys.
    This function returns TRUE on success, or FALSE on failure.
    Syntax
    asort(array,sorttype)

    Parameter           Description
    array               Required. Specifying an array
    sorttype            Optional. Specifies how to sort the array values. Possible values:
                            SORT_REGULAR - Default. Treat values as they are (don't change
                               types)
                             SORT_NUMERIC - Treat values numerically
                             SORT_STRING - Treat values as strings
                             SORT_LOCALE_STRING - Treat values as strings, based on local
                              settings

   Example
   <?php
   $my_array = array("a" => "Dog", "b" => "Cat", "c" => "Horse");

   asort($my_array);
   print_r($my_array);
   ?>
   The output of the code above will be:
   Array
   (
   [b] => Cat
   [a] => Dog
   [c] => Horse
   )

12) array_merge( )

   The array_merge() function merges one or more arrays into one array.
   Syntax
   array_merge(array1,array2,array3...)

   Parameter Description
   array1    Required. Specifies an array
   array2    Optional. Specifies an array
   array3    Optional. Specifies an array

   Tips and Notes
   Tip: You can assign one array to the function, or as many as you like.
   Note: If two or more array elements have the same key, the last one overrides the others.
   Note: If you assign only one array to the array_merge() function, and the keys are integers,
   the function returns a new array with integer keys starting at 0 and increases by 1 for each
   value. (See example 2)

   Example 1
   <?php
   $a1=array("a"=>"Horse","b"=>"Dog");
   $a2=array("c"=>"Cow","b"=>"Cat");
   print_r(array_merge($a1,$a2));
   ?>
   The output of the code above will be:
   Array ( [a] => Horse [b] => Cat [c] => Cow )

   Example 2
   Using only one array parameter.
   <?php
   $a=array(3=>"Horse",4=>"Dog");
   print_r(array_merge($a));
   ?>
   The output of the code above will be:
   Array ( [0] => Horse [1] => Dog )

13) array_reverse( )

   The array_reverse() function returns an array in the reverse order.
   Syntax
   array_reverse(array,preserve)

   Parameter           Description
   array               Required. Specifies an array
   preserve            Optional. Possible values:
                           true
                           false
                       Specifies if the function should preserve the array's keys or not.

   Example
   <?php
   $a=array("a"=>"Dog","b"=>"Cat","c"=>"Horse");
   print_r(array_reverse($a));
   ?>
   The output of the code above will be:
   Array ( [c] => Horse [b] => Cat [a] => Dog )


File Handling Functions

1) fopen( )

   The fopen() function opens a file or URL.
   If fopen() fails, it returns FALSE and an error on failure. You can hide the error output by
   adding an '@' in front of the function name.
   Syntax
   fopen(filename,mode,include_path,context)

   Parameter              Description
   filename               Required. Specifies the file or URL to open
   mode                   Required. Specifies the type of access you require to the file/stream.
                          Possible values:
                              "r" (Read only. Starts at the beginning of the file)
                              "r+" (Read/Write. Starts at the beginning of the file)
                              "w" (Write only. Opens and clears the contents of file; or creates a
                                 new file if it doesn't exist)
                              "w+" (Read/Write. Opens and clears the contents of file; or creates a
                                 new file if it doesn't exist)
                               "a" (Write only. Opens and writes to the end of the file or creates a
                                new file if it doesn't exist)
                             "a+" (Read/Write. Preserves file content by writing to the end of the
                                file)
                             "x" (Write only. Creates a new file. Returns FALSE and an error if
                                file already exists)
                             "x+" (Read/Write. Creates a new file. Returns FALSE and an error if
                                file already exists)
   include_path         Optional. Set this parameter to '1' if you want to search for the file in the
                        include_path (in php.ini) as well
   context              Optional. Specifies the context of the file handle. Context is a set of options
                        that can modify the behavior of a stream
   Tips and Notes
   Note: When writing to a text file, be sure to use the correct line-ending character! Unix
   systems use \n, Windows systems use \r\n, and Macintosh systems use \r as the line ending
   character. Windows offers a translation flag ('t') which will translate \n to \r\n when working
   with the file. You can also use 'b' to force binary mode. To use these flags, specify either 'b'
   or 't' as the last character of the mode parameter.

   Example
   <?php
   $file = fopen("test.txt","r");
   $file = fopen("/home/test/test.txt","r");
   $file = fopen("/home/test/test.gif","wb");
   $file = fopen("http://www.example.com/","r");
   $file = fopen("ftp://user:password@example.com/test.txt","w");
   ?>

2) fread( )

   The fread() reads from an open file.
   The function will stop at the end of the file or when it reaches the specified length, whichever
   comes first.
   This function returns the read string, or FALSE on failure.
   Syntax
   fread(file,length)

   Parameter       Description
   File            Required. Specifies the open file to read from
   length          Required. Specifies the maximum number of bytes to read

   Tips and Notes
   Tip: This function is binary-safe (meaning that both binary data, like images, and character
   data can be written with this function).

   Example 1
   Read 10 bytes from file:
   <?php
   $file = fopen("test.txt","r");
   fread($file,"10");
   fclose($file);
   ?>

   Example 2
   Read entire file:
   <?php
   $file = fopen("test.txt","r");
   fread($file,filesize("test.txt"));
   fclose($file);
   ?>

3) fwrite( )

   The fwrite() writes to an open file.
   The function will stop at the end of the file or when it reaches the specified length, whichever
   comes first.
   This function returns the number of bytes written, or FALSE on failure.
   Syntax
   fwrite(file,string,length)

   Parameter       Description
   File            Required. Specifies the open file to write to
   string          Required. Specifies the string to write to the open file
   length          Optional. Specifies the maximum number of bytes to write

   Tips and Notes
   Tip: This function is binary-safe (meaning that both binary data, like images, and character
   data can be written with this function).

   Example
   <?php
   $file = fopen("test.txt","w");
   echo fwrite($file,"Hello World. Testing!");
   fclose($file);
   ?>
   The output of the code above will be:
   21

4) fclose( )

   The fclose() function closes an open file.
   This function returns TRUE on success or FALSE on failure.
   Syntax
   fclose(file)

   Parameter Description
   File      Required. Specifies the file to close
   Example
   <?php
   $file = fopen("test.txt","r");
   //some code to be executed
   fclose($file);
   ?>

5) file_exists( )

   The file_exists() function checks whether or not a file or directory exists.
   This function returns TRUE if the file or directory exists, otherwise it returns FALSE.
   Syntax
   file_exists(path)

   Parameter Description
   Path      Required. Specifies the path to check

   Example
   <?php
   echo file_exists("test.txt");
   ?>
   The output of the code above will be:
   1

6) is_readable( )

   The is_readable() function checks whether the specified file is readable.
   This function returns TRUE if the file is readable.
   Syntax
   is_readable(file)

   Parameter Description
   File      Required. Specifies the file to check

   Tips and Notes
   Note: The result of this function are cached. Use clearstatcache() to clear the cache.

   Example
   <?php
   $file = "test.txt";
   if(is_readable($file))
     {
     echo ("$file is readable");
     }
   else
     {
     echo ("$file is not readable");
     }
   ?>
   The output of the code above could be:
   test.txt is readable

7) is_writable( )

   The is_writable() function checks whether the specified file is writeable.
   This function returns TRUE if the file is writeable.
   Syntax
   is_writable(file)

   Parameter Description
   file      Required. Specifies the file to check

   Tips and Notes
   Note: The result of this function are cached. Use clearstatcache() to clear the cache.

   Example
   <?php
   $file = "test.txt";
   if(is_writable($file))
     {
     echo ("$file is writeable");
     }
   else
     {
     echo ("$file is not writeable");
     }
   ?>
   The output of the code above could be:
   test.txt is writeable

8) fgets( )

   The fgets() function returns a line from an open file.
   The fgets() function stops returning on a new line, at the specified length, or at EOF,
   whichever comes first.
   This function returns FALSE on failure.
   Syntax
   fgets(file,length)

   Parameter          Description
   file               Required. Specifies the file to read from
   length             Optional. Specifies the number of bytes to read. Default is 1024 bytes.

   Example 1
   <?php
   $file = fopen("test.txt","r");
   echo fgets($file);
   fclose($file);
   ?>
    The output of the code above will be:
    Hello, this is a test file.

9) file( )

    The file() reads a file into an array.
    Each array element contains a line from the file, with newline still attached.
    Syntax
    file(path,include_path,context)

    Parameter              Description
    path                   Required. Specifies the file to read
    include_path           Optional. Set this parameter to '1' if you want to search for the file in the
                           include_path (in php.ini) as well
    context                Optional. Specifies the context of the file handle. Context is a set of options
                           that can modify the behavior of a stream. Can be skipped by using NULL.
    Tips and Notes
    Tip: This function became binary-safe in PHP 4.3. (meaning that both binary data, like
    images, and character data can be written with this function).

    Example
    <?php
    print_r(file("test.txt"));
    ?>
    The output of the code above will be:
    Array
    (
    [0] => Hello World. Testing testing!
    [1] => Another day, another line.
    [2] => If the array picks up this line,
    [3] => then is it a pickup line?
    )

10) file_get_contents( )

    The file_get_contents() reads a file into a string.
    This function is the preferred way to read the contents of a file into a string. Because it will
    use memory mapping techniques, if this is supported by the server, to enhance performance.
    Syntax
    file_get_contents(path,include_path,context,start,max_length)

    Parameter              Description
    path                   Required. Specifies the file to read
    include_path           Optional. Set this parameter to '1' if you want to search for the file in the
                           include_path (in php.ini) as well
    context                Optional. Specifies the context of the file handle. Context is a set of options
                           that can modify the behavior of a stream. Can be skipped by using NULL.
    start                  Optional. Specifies where in the file to start reading. This parameter was
                           added in PHP 5.1
   max_length              Optional. Specifies how many bytes to read. This parameter was added in
                           PHP 5.1
   Tips and Notes
   Tip: This function is binary-safe (meaning that both binary data, like images, and character
   data can be written with this function).

   Example
   <?php
   echo file_get_contents("test.txt");
   ?>
   The output of the code above will be:
   This is a test file with test text.

11) file_put_contents( )

   The file_put_contents() writes a string to a file.
   This function follows these rules when accessing a file:
       1. If FILE_USE_INCLUDE_PATH is set, check the include path for a copy of
            *filename*
       2. Create the file if it does not exist
       3. Open the file
       4. Lock the file if LOCK_EX is set
       5. If FILE_APPEND is set, move to the end of the file. Otherwise, clear the file content
       6. Write the data into the file
       7. Close the file and release any locks
   This function returns the number of character written into the file on success, or FALSE on
   failure.
   Syntax
   file_put_contents(file,data,mode,context)

   Parameter               Description
   file                    Required. Specifies the file to write to. If the file does not exist, this function
                           will create one
   data                    Required. The data to write to the file. Can be a string, an array or a data
                           stream
   mode                    Optional. Specifies how to open/write to the file. Possible values:
                                FILE_USE_INCLUDE_PATH
                                FILE_APPEND
                                LOCK_EX
   context                 Optional. Specifies the context of the file handle. Context is a set of options
                           that can modify the behavior of a stream.
   Tips and Notes
   Note: Use FILE_APPEND to avoid deleting the existing content of the file.

   Example
   <?php
   echo file_put_contents("test.txt","Hello World. Testing!");
   ?>
   The output of the code above will be:
    21

12) ftell( )

    The ftell() function returns the current position in an open file.
    Returns the current file pointer position, or FALSE on failure.
    Syntax
    ftell(file)

    Parameter Description
    File      Required. Specifies the open file to check

    Example
    <?php
    $file = fopen("test.txt","r");

    // print current position
    echo ftell($file);

    // change current position
    fseek($file,"15");

    // print current position again
    echo "<br />" . ftell($file);

    fclose($file);
    ?>
    The output of the code above will be:
    0
    15

13) fseek( )

    The fseek() function seeks in an open file.
    This function moves the file pointer from its current position to a new position, forward or
    backward, specified by the number of bytes.
    This function returns 0 on success, or -1 on failure. Seeking past EOF will not generate an
    error.
    Syntax
    fseek(file,offset,whence)

    Parameter            Description
    File                 Required. Specifies the open file to seek in
    offset               Required. Specifies the new position (measured in bytes from the beginning
                         of the file)
    whence               Optional. (added in PHP 4). Possible values:
                              SEEK_SET - Set position equal to offset. Default
                              SEEK_CUR - Set position to current location plus offset
                              SEEK_END - Set position to EOF plus offset (to move to a position
                                before EOF, the offset must be a negative value)

   Tips and Notes
   Tip: Find the current position by using ftell()!

   Example
   <?php
   $file = fopen("test.txt","r");
   // read first line
   fgets($file);
   // move back to beginning of file
   fseek($file,0);
   ?>

14) rewind( )

   The rewind() function "rewinds" the position of the file pointer to the beginning of the file.
   This function returns TRUE on success, or FALSE on failure.
   Syntax
   rewind(file)

   Parameter Description
   file      Required. Specifies the open file

   Example
   <?php
   $file = fopen("test.txt","r");

   //Change position of file pointer
   fseek($file,"15");

   //Set file pointer to 0
   rewind($file);

   fclose($file);
   ?>

15) copy( )

   The copy() function copies a file.
   This function returns TRUE on success and FALSE on failure.
   Syntax
   copy(file,to_file)

   Parameter Description
   file      Required. Specifies the file to copy
   to_file   Required. Specifies the file to copy to

   Tips and Notes
   Note: If the destination file already exists, it will be overwritten.

   Example
   <?php
   echo copy("source.txt","target.txt");
   ?>
   The output of the code above will be:
   1

16) unlink( )

   The unlink() function deletes a file.
   This function returns TRUE on success, or FALSE on failure.
   Syntax
   unlink(filename,context)

   Parameter            Description
   filename             Required. Specifies the file to delete
   context              Optional. Specifies the context of the file handle. Context is a set of options
                        that can modify the behavior of a stream

   Example
   <?php
   $file = "test.txt";
   if (!unlink($file))
     {
     echo ("Error deleting $file");
     }
   else
     {
     echo ("Deleted $file");
     }
   ?>

17) rename( )

   The rename() function renames a file or directory.
   This function returns TRUE on success, or FALSE on failure.
   Syntax
   rename(oldname,newname,context)

   Parameter            Description
   oldname              Required. Specifies the file or directory to be renamed
   newname              Required. Specifies the new name of the file or directory
   context              Optional. Specifies the context of the file handle. Context is a set of options
                        that can modify the behavior of a stream

   Example
   <?php
   rename("images","pictures");
   ?>

Miscellaneous Functions

1) define( )

   The define() function defines a constant.
   Constants are much like variables, except for the following differences:
        A constant's value cannot be changed after it is set
        Constant names do not need a leading dollar sign ($)
        Constants can be accessed regardless of scope
        Constant values can only be strings and numbers
   Syntax
   define(name,value,case_insensitive)

   Parameter           Description
   name                Required. Specifies the name of the constant
   value               Required. Specifies the value of the constant
   case_insensitive    Optional. Specifies whether the constant name should be case-insensitive. If
                       set to TRUE, the constant will be case-insensitive. Default is FALSE (case-
                       sensitive)
       Example 1
       Define a case-sensitive constant:
       <?php
       define("GREETING","Hello you! How are you today?");
       echo constant("GREETING");
       ?>
       The output of the code above will be:
       Hello you! How are you today?

       Example 2
       Define a case-insensitive constant:
       <?php
       define("GREETING","Hello you! How are you today?",TRUE);
       echo constant("greeting");
       ?>
       The output of the code above will be:
       Hello you! How are you today?




2) constant( )

   The constant() function returns the value of a constant.
   Syntax
   constant(constant)
   Parameter Description
   constant     Required. Specifies the name of the constant to
                check
   Tips and Notes
   Note: This function also works with class constants.

   Example
   <?php
   //define a constant
   define("GREETING","Hello you! How are you today?");

   echo constant("GREETING");
   ?>
   The output of the code above will be:
   Hello you! How are you today?

3) include( ) & require( )

   In PHP, you can insert the content of one PHP file into another PHP file before the server
   executes it.
   The include and require statements are used to insert useful codes written in other files, in the
   flow of execution.
   Include and require are identical, except upon failure:

           require will produce a fatal error (E_COMPILE_ERROR) and stop the script
           include will only produce a warning (E_WARNING) and the script will continue

   So, if you want the execution to go on and show users the output, even if the include file is
   missing, use include. Otherwise, in case of FrameWork, CMS (Content Management
   System) or a complex PHP application coding, always use require to include a key file to the
   flow of execution. This will help avoid compromising your application's security and
   integrity, just in-case one key file is accidentally missing.
   Including files saves a lot of work. This means that you can create a standard header, footer,
   or menu file for all your web pages. Then, when the header needs to be updated, you can
   only update the header include file.

   Syntax

   include 'filename';
   or
   require 'filename';

   Basic Example

   Assume that you have a standard header file, called "header.php". To include the header file
   in a page, use include/require:

   <html>
   <body>
<?php include 'header.php'; ?>
<h1>Welcome to my home page!</h1>
<p>Some text.</p>
</body>
</html>

Example 2

Assume we have a standard menu file that should be used on all pages.
"menu.php":

<a href="/default.php">Home</a>
<a href="/tutorials.php">Tutorials</a>
<a href="/references.php">References</a>
<a href="/examples.php">Examples</a>
<a href="/about.php">About Us</a>
<a href="/contact.php">Contact Us</a>

All pages in the Web site should include this menu file. Here is how it can be done:

<html>
<body>
<div class="leftmenu">
<?php include 'menu.php'; ?>
</div>
<h1>Welcome to my home page.</h1>
<p>Some text.</p>
</body>
</html>

Example 3

Assume we have an include file with some variables defined ("vars.php"):

<?php
$color='red';
$car='BMW';
?>

Then the variables can be used in the calling file:

<html>
<body>
<h1>Welcome to my home page.</h1>
<?php include 'vars.php';
   echo "I have a $color $car"; // I have e red BMW
   ?>
   </body>
   </html>

4) header( )

   The header() function sends a raw HTTP header to a client.
   It is important to notice that header() must be called before any actual output is sent (In PHP
   4 and later, you can use output buffering to solve this problem):
   <html>
   <?php
   // This results in an error.
   // The output above is before the header() call
   header('Location: http://www.example.com/');
   ?>
   Syntax
   header(string,replace,http_response_code)
   Parameter              Description
   string                 Required. Specifies the header string to send
   replace                Optional. Indicates whether the header should replace previous or add a
                          second header. Default is TRUE (will replace). FALSE (allows multiple
                          headers of the same type)
   http_response_code Optional. Forces the HTTP response code to the specified value (available in
                          PHP 4.3 and higher)

   Tips and Notes
   Note: Since PHP 4.4 this function prevents more than one header to be sent at once. This is a
   protection against header injection attacks.

   Example 1
   Prevent page caching:
   <?php
   // Date in the past
   header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
   header("Cache-Control: no-cache");
   header("Pragma: no-cache");
   ?>

   <html>
   <body>

   ...
   ...
   Note: There are options that users may set to change the browser's default caching settings.
   By sending the headers above, you should override any of those settings and force the
   browser to not cache!

   Example 2
   Let the user be prompted to save a generated PDF file (Content-Disposition header is used to
   supply a recommended filename and force the browser to display the save dialog box):
   <?php
   header("Content-type:application/pdf");

   // It will be called downloaded.pdf
   header("Content-Disposition:attachment;filename='downloaded.pdf'");

   // The PDF source is in original.pdf
   readfile("original.pdf");
   ?>

   <html>
   <body>
   ...
   ...
   Note: There is a bug in Microsoft IE 5.5 that prevents this from working. The bug can be
   resolved by upgrading to Service Pack 2 or later.

5) die( )

   The die() function prints a message and exits the current script.
   This function is an alias of the exit() function.
   Syntax
   die(message)

   Parameter           Description
   message             Required. Specifies the message or status number to write before exiting the
                       script. The status number will not be written to the output.

   Example
   <?php
   $site = "http://www.w3schools.com/";
   fopen($site,"r")
   or die("Unable to connect to $site");
   ?>

   PHP User Defined Functions

   This chapter will show you how to create your own functions.
   To keep the script from being executed when the page loads, you can put it into a function.
   A function will be executed by a call to the function.
   You may call a function from anywhere within a page.

   Create a PHP Function

   A function will be executed by a call to the function.
   Syntax
   function functionName()
   {
   code to be executed;
   }

   PHP function guidelines:

          Give the function a name that reflects what the function does
          The function name can start with a letter or underscore (not a number)

   Example

   A simple function that writes name when it is called:

   <html>
   <body>
   <?php
   function writeName()
   {
   echo "Kai Jim Refsnes";
   }
   echo "My name is ";
   writeName();
   ?>
   </body>
   </html>

   Output:
   My name is Kai Jim Refsnes

PHP Functions - Adding parameters

To add more functionality to a function, we can add parameters. A parameter is just like a
variable.

Parameters are specified after the function name, inside the parentheses.

Example 1

The following example will write different first names, but equal last name:

<html>
<body>

<?php
function writeName($fname)
{
echo $fname . " Refsnes.<br />";
}

echo "My name is ";
writeName("Kai Jim");
echo "My friend’s name is ";
writeName("Hege");
echo "My student’s name is ";
writeName("Stale");
?>
</body>
</html>

Output:

My name is Kai Jim Refsnes.
My sister's name is Hege Refsnes.
My brother's name is Stale Refsnes.

Example 2

The following function has two parameters:

<html>
<body>

<?php
function writeName($fname,$punctuation)
{
echo $fname . " Refsnes" . $punctuation . "<br />";
}

echo "My name is ";
writeName("Kai Jim",".");
echo "My sister's name is ";
writeName("Hege","!");
echo "My brother's name is ";
writeName("Ståle","?");
?>

</body>
</html>
Output:

My name is Kai Jim Refsnes.
My sister's name is Hege Refsnes!
My brother's name is Ståle Refsnes?

PHP Functions - Return values

To let a function return a value, use the return statement.

Example
<html>
<body>
<?php
function add($x,$y)
{
$total=$x+$y;
return $total;
}
echo "1 + 16 = " . add(1,16);
?>
</body>
</html>

Output:
1 + 16 = 17

                                              UNIT – 6

PHP Session

A PHP session variable is used to store information about, or change settings for a user session.
Session variables hold information about one single user, and are available to all pages in one
application.

PHP Session Variables
When you are working with an application, you open it, do some changes and then you close it.
This is much like a Session. The computer knows who you are. It knows when you start the
application and when you end. But on the internet there is one problem: the web server does not
know who you are and what you do because the HTTP address doesn't maintain state.
A PHP session solves this problem by allowing you to store user information on the server for
later use (i.e. username, shopping items, etc). However, session information is temporary and
will be deleted after the user has left the website. If you need a permanent storage you may want
to store the data in a database.
Sessions work by creating a unique id (UID) for each visitor and store variables based on this
UID. The UID is either stored in a cookie or is propagated in the URL.
Starting a PHP Session
Before you can store user information in your PHP session, you must first start up the session.
Note: The session_start() function must appear BEFORE the <html> tag:

<?php session_start(); ?>
<html>
<body>
</body>
</html>
The code above will register the user's session with the server, allow you to start saving user
information, and assign a UID for that user's session.

Storing a Session Variable
The correct way to store and retrieve session variables is to use the PHP $_SESSION variable:
<?php
session_start();
// store session data
$_SESSION['views']=1;
?>

<html>
<body>
<?php
//retrieve session data
echo "Pageviews=". $_SESSION['views'];
?>
</body>
</html>
Output:

Pageviews=1
In the example below, we create a simple page-views counter. The isset() function checks if the
"views" variable has already been set. If "views" has been set, we can increment our counter. If
"views" doesn't exist, we create a "views" variable, and set it to 1:
<?php
session_start();

if(isset($_SESSION['views']))
$_SESSION['views']=$_SESSION['views']+1;
else
$_SESSION['views']=1;
echo "Views=". $_SESSION['views'];
?>

Destroying a Session/Unregistering and deleting session variable
If you wish to delete some session data, you can use the unset() or the session_destroy() function.
The unset() function is used to free the specified session variable:
<?php
unset($_SESSION['views']);
?>
You can also completely destroy the session by calling the session_destroy() function:
<?php
session_destroy();
?>
Note: session_destroy() will reset your session and you will lose all your stored session data.

PHP Cookie

A cookie is often used to identify a user.

What is a Cookie?

A cookie is often used to identify a user. A cookie is a small file that the server embeds on the
user's computer. Each time the same computer requests a page with a browser, it will send the
cookie too. With PHP, you can both create and retrieve cookie values.

The main difference between cookies and sessions is that cookies are stored in the user's
browser, and sessions are not. This difference determines what each is best used for.

A cookie can keep information in the user's browser until deleted. If a person has a login and
password, this can be set as a cookie in their browser so they do not have to re-login to your
website every time they visit. You can store almost anything in a browser cookie. The trouble is
that a user can block cookies or delete them at any time. If, for example, your website's shopping
cart utilized cookies, and a person had their browser set to block them, then they could not shop
at your website.

How to Create a Cookie?

The setcookie() function is used to set a cookie.
Note: The setcookie() function must appear BEFORE the <html> tag.

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

Example 1

In the example below, we will create a cookie named "user" and assign the value "Alex Porter"
to it. We also specify that the cookie should expire after one hour:

<?php
setcookie("user", "Alex Porter", time()+3600);
?>
<html>
.....

Note: The value of the cookie is automatically URLencoded when sending the cookie, and
automatically decoded when received (to prevent URLencoding, use setrawcookie() instead).
Example 2

You can also set the expiration time of the cookie in another way. It may be easier than using
seconds.

<?php
$expire=time()+60*60*24*30;
setcookie("user", "Alex Porter", $expire);
?>

<html>
.....

In the example above the expiration time is set to a month (60 sec * 60 min * 24 hours * 30
days).

How to Retrieve a Cookie Value?

The PHP $_COOKIE variable is used to retrieve a cookie value.
In the example below, we retrieve the value of the cookie named "user" and display it on a page:

<?php
// Print a cookie
echo $_COOKIE["user"];

// A way to view all cookies
print_r($_COOKIE);
?>

In the following example we use the isset() function to find out if a cookie has been set:

<html>
<body>

<?php
if (isset($_COOKIE["user"]))
  echo "Welcome " . $_COOKIE["user"] . "!<br />";
else
  echo "Welcome guest!<br />";
?>

</body>
</html>

How to Delete a Cookie?

When deleting a cookie you should assure that the expiration date is in the past.
Delete example:

<?php
// set the expiration date to one hour ago
setcookie("user", "", time()-3600);
?>

What if a Browser Does NOT Support Cookies?

If your application deals with browsers that do not support cookies, you will have to use other
methods to pass information from one page to another in your application. One method is to pass
the data through forms (forms and user input are described earlier in this tutorial).
The form below passes the user input to "welcome.php" when the user clicks on the "Submit"
button:

<html>
<body>

<form action="welcome.php" method="post">
Name: <input type="text" name="name" />
Age: <input type="text" name="age" />
<input type="submit" />
</form>
</body>
</html>

Retrieve the values in the "welcome.php" file like this:

<html>
<body>
Welcome <?php echo $_POST["name"]; ?>.<br />
You are <?php echo $_POST["age"]; ?> years old.
</body>
</html>
                                         UNIT – 8
mySql
MySQL is the most popular open-source database system.

What is MySQL?
MySQL is a database.
The data in MySQL is stored in database objects called tables.
A table is a collection of related data entries and it consists of columns and rows.
Databases are useful when storing information categorically. A company may have a database
with the following tables: "Employees", "Products", "Customers" and "Orders".
Database Tables

A database most often contains one or more tables. Each table is identified by a name (e.g.
"Customers" or "Orders"). Tables contain records (rows) with data.
Below is an example of a table called "Persons":

LastName FirstName Address          City
Hansen      Ola       Timoteivn 10 Sandnes
Svendson Tove         Borgvn 23     Sandnes
Pettersen Kari        Storgt 20     Stavanger

The table above contains three records (one for each person) and four columns (LastName,
FirstName, Address, and City).

Queries

A query is a question or a request.
With MySQL, we can query a database for specific information and have a recordset returned.
Look at the following query:

SELECT LastName FROM Persons

The query above selects all the data in the "LastName" column from the "Persons" table, and will
return a recordset like this:

LastName
Hansen
Svendson
Pettersen

Download MySQL Database

If you don't have a PHP server with a MySQL Database, you can download MySQL for free
here: http://www.mysql.com/downloads/

Facts About MySQL Database

One great thing about MySQL is that it can be scaled down to support embedded database
applications. Perhaps it is because of this reputation that many people believe that MySQL can
only handle small to medium-sized systems.
The truth is that MySQL is the de-facto standard database for web sites that support huge
volumes of both data and end users (like Friendster, Yahoo, Google).


PHP MySQL Connect to a Database

The free MySQL database is very often used with PHP.
Create a Connection to a MySQL Database

Before you can access data in a database, you must create a connection to the database.
In PHP, this is done with the mysql_connect() function.

Syntax
mysql_connect(servername,username,password);

Parameter           Description
servername          Optional. Specifies the server to connect to. Default value is
                    "localhost:3306"
username            Optional. Specifies the username to log in with. Default value is the name of
                    the user that owns the server process
password            Optional. Specifies the password to log in with. Default is ""

Note: There are more available parameters, but the ones listed above are the most important.
Visit our full PHP MySQL Reference for more details.

Example

In the following example we store the connection in a variable ($con) for later use in the script.
The "die" part will be executed if the connection fails:

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

// some code
?>

Closing a Connection

The connection will be closed automatically when the script ends. To close the connection
before, use the mysql_close() function:

<?php
$con = mysql_connect("localhost","peter","abc123");
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }
// some code

mysql_close($con);
?>
Create Database and Tables

A database holds one or multiple tables.

Create a Database

The CREATE DATABASE statement is used to create a database in MySQL.

Syntax
CREATE DATABASE database_name
To learn more about SQL, please visit our SQL tutorial.

To get PHP to execute the statement above we must use the mysql_query() function. This
function is used to send a query or command to a MySQL connection.

Example

The following example creates a database called "my_db":

<?php
$con = mysql_connect("localhost","peter","abc123");
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }
if (mysql_query("CREATE DATABASE my_db",$con))
  {
  echo "Database created";
  }
else
  {
  echo "Error creating database: " . mysql_error();
  }
mysql_close($con);
?>

Create a Table

The CREATE TABLE statement is used to create a table in MySQL.
Syntax
CREATE TABLE table_name
(
column_name1 data_type,
column_name2 data_type,
column_name3 data_type,
....
)

We must add the CREATE TABLE statement to the mysql_query() function to execute the
command.

Example

The following example creates a table named "Persons", with three columns. The column names
will be "FirstName", "LastName" and "Age":

<?php
$con = mysql_connect("localhost","peter","abc123");
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }
// Create database
if (mysql_query("CREATE DATABASE my_db",$con))
  {
  echo "Database created";
  }
else
  {
  echo "Error creating database: " . mysql_error();
  }
// Create table
mysql_select_db("my_db", $con);
$sql = "CREATE TABLE Persons
(
FirstName varchar(15),
LastName varchar(15),
Age int
)";
// Execute query
mysql_query($sql,$con);
mysql_close($con);
?>

Important: A database must be selected before a table can be created. The database is selected
with the mysql_select_db() function.
Note: When you create a database field of type varchar, you must specify the maximum length
of the field, e.g. varchar(15).
The data type specifies what type of data the column can hold. For a complete reference of all
the data types available in MySQL, go to our complete Data Types reference.

Primary Keys and Auto Increment Fields

Each table should have a primary key field.
A primary key is used to uniquely identify the rows in a table. Each primary key value must be
unique within the table. Furthermore, the primary key field cannot be null because the database
engine requires a value to locate the record.
The following example sets the personID field as the primary key field. The primary key field is
often an ID number, and is often used with the AUTO_INCREMENT setting.
AUTO_INCREMENT automatically increases the value of the field by 1 each time a new record
is added. To ensure that the primary key field cannot be null, we must add the NOT NULL
setting to the field.

Example
$sql = "CREATE TABLE Persons
(
personID int NOT NULL AUTO_INCREMENT,
PRIMARY KEY(personID),
FirstName varchar(15),
LastName varchar(15),
Age int
)";

mysql_query($sql,$con);


Insert

The INSERT INTO statement is used to insert new records in a table.

Insert Data Into a Database Table

The INSERT INTO statement is used to add new records to a database table.

Syntax

It is possible to write the INSERT INTO statement in two forms.
The first form doesn't specify the column names where the data will be inserted, only their
values:
INSERT INTO table_name
VALUES (value1, value2, value3,...)

The second form specifies both the column names and the values to be inserted:

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

To get PHP to execute the statements above we must use the mysql_query() function. This
function is used to send a query or command to a MySQL connection.

Example

In the previous chapter we created a table named "Persons", with three columns; "Firstname",
"Lastname" and "Age". We will use the same table in this example. The following example adds
two new records to the "Persons" table:

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

mysql_select_db("my_db", $con);
mysql_query("INSERT INTO Persons (FirstName, LastName, Age)
VALUES ('Peter', 'Griffin',35)");
mysql_query("INSERT INTO Persons (FirstName, LastName, Age)
VALUES ('Glenn', 'Quagmire',33)");
mysql_close($con);
?>

Insert Data From a Form Into a Database

Now we will create an HTML form that can be used to add new records to the "Persons" table.
Here is the HTML form:

<html>
<body>
<form action="insert.php" method="post">
Firstname: <input type="text" name="firstname" />
Lastname: <input type="text" name="lastname" />
Age: <input type="text" name="age" />
<input type="submit" />
</form>
</body>
</html>

When a user clicks the submit button in the HTML form in the example above, the form data is
sent to "insert.php".
The "insert.php" file connects to a database, and retrieves the values from the form with the PHP
$_POST variables.
Then, the mysql_query() function executes the INSERT INTO statement, and a new record will
be added to the "Persons" table.
Here is the "insert.php" page:

<?php
$con = mysql_connect("localhost","peter","abc123");
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }
mysql_select_db("my_db", $con);
$sql="INSERT INTO Persons (FirstName, LastName, Age)
VALUES
('$_POST[firstname]','$_POST[lastname]','$_POST[age]')";
if (!mysql_query($sql,$con))
  {
  die('Error: ' . mysql_error());
  }
echo "1 record added";
mysql_close($con);
?>
Select

The SELECT statement is used to select data from a database.

Select Data From a Database Table

The SELECT statement is used to select data from a database.

Syntax
SELECT column_name(s)
FROM table_name

To learn more about SQL, please visit our SQL tutorial.
To get PHP to execute the statement above we must use the mysql_query() function. This
function is used to send a query or command to a MySQL connection.
Example

The following example selects all the data stored in the "Persons" table (The * character selects
all the data in the table):

<?php
$con = mysql_connect("localhost","peter","abc123");
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }
mysql_select_db("my_db", $con);
$result = mysql_query("SELECT * FROM Persons");
while($row = mysql_fetch_array($result))
  {
  echo $row['FirstName'] . " " . $row['LastName'];
  echo "<br />";
  }
mysql_close($con);
?>

The example above stores the data returned by the mysql_query() function in the $result
variable.
Next, we use the mysql_fetch_array() function to return the first row from the recordset as an
array. Each call to mysql_fetch_array() returns the next row in the recordset. The while loop
loops through all the records in the recordset. To print the value of each row, we use the PHP
$row variable ($row['FirstName'] and $row['LastName']).
The output of the code above will be:

Peter Griffin
Glenn Quagmire

Display the Result in an HTML Table

The following example selects the same data as the example above, but will display the data in
an HTML table:

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

mysql_select_db("my_db", $con);
$result = mysql_query("SELECT * FROM Persons");
echo "<table border='1'>
<tr>
<th>Firstname</th>
<th>Lastname</th>
</tr>";
while($row = mysql_fetch_array($result))
 {
 echo "<tr>";
 echo "<td>" . $row['FirstName'] . "</td>";
 echo "<td>" . $row['LastName'] . "</td>";
 echo "</tr>";
 }
echo "</table>";
mysql_close($con);
?>

The output of the code above will be:

Firstname Lastname
Glenn      Quagmire
Peter      Griffin


The Where Clause

The WHERE clause is used to filter records.

The WHERE clause is used to extract only those records that fulfill a specified criterion.

Syntax
SELECT column_name(s)
FROM table_name
WHERE column_name operator value

To get PHP to execute the statement above we must use the mysql_query() function. This
function is used to send a query or command to a MySQL connection.

Example

The following example selects all rows from the "Persons" table where "FirstName='Peter'":

<?php
$con = mysql_connect("localhost","peter","abc123");
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }
mysql_select_db("my_db", $con);
$result = mysql_query("SELECT * FROM Persons
WHERE FirstName='Peter'");
while($row = mysql_fetch_array($result))
  {
  echo $row['FirstName'] . " " . $row['LastName'];
  echo "<br />";
  }
?>

The output of the code above will be:

Peter Griffin

Order By Keyword

The ORDER BY keyword is used to sort the data in a recordset.
The ORDER BY keyword is used to sort the data in a recordset.
The ORDER BY keyword sort the records in ascending order by default.
If you want to sort the records in a descending order, you can use the DESC keyword.

Syntax
SELECT column_name(s)
FROM table_name
ORDER BY column_name(s) ASC|DESC

To learn more about SQL, please visit our SQL tutorial.

Example

The following example selects all the data stored in the "Persons" table, and sorts the result by
the "Age" column:

<?php
$con = mysql_connect("localhost","peter","abc123");
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }
mysql_select_db("my_db", $con);
$result = mysql_query("SELECT * FROM Persons ORDER BY age");
while($row = mysql_fetch_array($result))
 {
 echo $row['FirstName'];
 echo " " . $row['LastName'];
 echo " " . $row['Age'];
 echo "<br />";
 }
mysql_close($con);
?>

The output of the code above will be:

Glenn Quagmire 33
Peter Griffin 35

Order by Two Columns

It is also possible to order by more than one column. When ordering by more than one column,
the second column is only used if the values in the first column are equal:

SELECT column_name(s)
FROM table_name
ORDER BY column1, column2


PHP MySQL Update

The UPDATE statement is used to modify data in a table.

Update Data In a Database

The UPDATE statement is used to update existing records in a table.

Syntax
UPDATE table_name
SET column1=value, column2=value2,...
WHERE some_column=some_value

Note: Notice the WHERE clause in the UPDATE syntax. The WHERE clause specifies which
record or records that should be updated. If you omit the WHERE clause, all records will be
updated!
To get PHP to execute the statement above we must use the mysql_query() function. This
function is used to send a query or command to a MySQL connection.
Example

Earlier in the tutorial we created a table named "Persons". Here is how it looks:

FirstName LastName Age
Peter      Griffin     35
Glenn      Quagmire 33

The following example updates some data in the "Persons" table:

<?php
$con = mysql_connect("localhost","peter","abc123");
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }
mysql_select_db("my_db", $con);
mysql_query("UPDATE Persons SET Age=36
WHERE FirstName='Peter' AND LastName='Griffin'");
mysql_close($con);
?>

After the update, the "Persons" table will look like this:

FirstName LastName Age
Peter      Griffin     36
Glenn      Quagmire 33


PHP MySQL Delete

The DELETE statement is used to delete records in a table.

Delete Data In a Database

The DELETE FROM statement is used to delete records from a database table.

Syntax
DELETE FROM table_name
WHERE some_column = some_value
Note: Notice the WHERE clause in the DELETE syntax. The WHERE clause specifies which record
or records that should be deleted. If you omit the WHERE clause, all records will be deleted!
To get PHP to execute the statement above we must use the mysql_query() function. This
function is used to send a query or command to a MySQL connection.

Example

Look at the following "Persons" table:

FirstName LastName Age
Peter       Griffin     35
Glenn       Quagmire 33

The following example deletes all the records in the "Persons" table where LastName='Griffin':

<?php
$con = mysql_connect("localhost","peter","abc123");
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }
mysql_select_db("my_db", $con);
mysql_query("DELETE FROM Persons WHERE LastName='Griffin'");
mysql_close($con);
?>

After the deletion, the table will look like this:

FirstName LastName Age
Glenn       Quagmire 33

Database ODBC
ODBC is an Application Programming Interface (API) that allows you to connect to a data
source (e.g. an MS Access database).

Create an ODBC Connection

With an ODBC connection, you can connect to any database, on any computer in your network,
as long as an ODBC connection is available.
Here is how to create an ODBC connection to a MS Access Database:

    1.   Open the Administrative Tools icon in your Control Panel.
    2.   Double-click on the Data Sources (ODBC) icon inside.
    3.   Choose the System DSN tab.
    4.   Click on Add in the System DSN tab.
    5.   Select the Microsoft Access Driver. Click Finish.
    6.   In the next screen, click Select to locate the database.
   7. Give the database a Data Source Name (DSN).
   8. Click OK.

Note that this configuration has to be done on the computer where your web site is located. If
you are running Internet Information Server (IIS) on your own computer, the instructions above
will work, but if your web site is located on a remote server, you have to have physical access to
that server, or ask your web host to to set up a DSN for you to use.

Connecting to an ODBC

The odbc_connect() function is used to connect to an ODBC data source. The function takes four
parameters: the data source name, username, password, and an optional cursor type.
The odbc_exec() function is used to execute an SQL statement.

Example

The following example creates a connection to a DSN called northwind, with no username and
no password. It then creates an SQL and executes it:

$conn=odbc_connect('northwind','','');
$sql="SELECT * FROM customers";
$rs=odbc_exec($conn,$sql);

Retrieving Records

The odbc_fetch_row() function is used to return records from the result-set. This function returns
true if it is able to return rows, otherwise false.
The function takes two parameters: the ODBC result identifier and an optional row number:

odbc_fetch_row($rs)

Retrieving Fields from a Record

The odbc_result() function is used to read fields from a record. This function takes two
parameters: the ODBC result identifier and a field number or name.
The code line below returns the value of the first field from the record:

$compname=odbc_result($rs,1);

The code line below returns the value of a field called "CompanyName":

$compname=odbc_result($rs,"CompanyName");

Closing an ODBC Connection

The odbc_close() function is used to close an ODBC connection.

odbc_close($conn);
An ODBC Example

The following example shows how to first create a database connection, then a result-set, and
then display the data in an HTML table.

<html>
<body>
<?php
$conn=odbc_connect('northwind','','');
if (!$conn)
  {exit("Connection Failed: " . $conn);}
$sql="SELECT * FROM customers";
$rs=odbc_exec($conn,$sql);
if (!$rs)
  {exit("Error in SQL");}
echo "<table><tr>";
echo "<th>Companyname</th>";
echo "<th>Contactname</th></tr>";
while (odbc_fetch_row($rs))
  {
  $compname=odbc_result($rs,"CompanyName");
  $conname=odbc_result($rs,"ContactName");
  echo "<tr><td>$compname</td>";
  echo "<td>$conname</td></tr>";
  }
odbc_close($conn);
echo "</table>";
?>
</body>
</html>

								
To top