الأربعاء، 16 مارس 2011

Include File

Include takes a file name and simply inserts that file's contents into the script that issued the include command.

An Include Example
Say we wanted to create a common menu file that all our pages will use. A common practice for naming files that are to be included is to use the ".php" extension. Since we want to create a common menu let's save it as "menu.php".
menu.php Code:

<html>
<body>
<a href="http://www.example.com/index.php">Home</a> -
<a href="http://www.example.com/about.php">About Us</a> -
<a href="http://www.example.com/links.php">Links</a> -
<a href="http://www.example.com/contact.php">Contact Us</a> <br />


Save the above file as "menu.php". Now create a new file, "index.php" in the same directory as "menu.php". Here we will take advantage of the include command to add our common menu.
index.php Code:

<?php include("menu.php"); ?>
<p>This is my home page that uses a common menu to save me time when I add
new pages to my website!</p>
</body>
</html>


Display:
Home - About Us - Links - Contact Us

This is my home page that uses a common menu to save me time when I add new pages to my website!

PHP include() Function

The include() function takes all the content in a specified file and includes it in the current file.

If an error occurs, the include() function generates a warning, but the script will continue execution

PHP require() Function

The require() function is identical to include(), except that it handles errors differently.
If an error occurs, the include() function generates a warning, but the script will continue execution. The require() generates a fatal error, and the script will stop.

It is recommended to use the require() function instead of include(), because scripts should not continue after an error.

الثلاثاء، 15 مارس 2011

Form

One of the best features of PHP is possibility to respond to user queries or data submitted from HTML forms. You can process information gathered by an HTML form and use PHP code to make decisions based off this information to create dynamic web pages.

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 click 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.

What these parameters do?
Action: The action parameter tells to the browser what script/site must be called when the visitor pressed the submit button. In our case the browser will load the welcome.php file which will process the submitted information.
Method: The method parameters tells to the browser in which form to send the user submitted data to the web-server. The parameter value is either POST or GET.

The $_GET Function

The built-in $_GET function is used to collect values from a form sent 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.snookerworld.ae/welcome.php?fname=Peter&age=37 

The "welcome.php" file can now use the $_GET function 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.

The $_POST Function

The built-in $_POST function 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.snookerworld.ae/welcome.php  

The "welcome.php" file can now use the $_POST function 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 Function

The PHP built-in $_REQUEST function contains the contents of both $_GET, $_POST, and $_COOKIE.
The $_REQUEST function can be used to collect form data sent with both the GET and POST methods.

Example

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

 

Functions

A function is a block of code which can be called from any point in a script after it has been declared. It is basically a compartmentalized PHP script designed to accomplish a single task. Furthermore, code contained within functions is ignored until the function is called from another part in the script. Functions are useful because they contribute to rapid, reliable, error-reducing coding, and increase legibility by tiding up complicated code sequences.
It is good programming practice to use functions to modularize your code and to better provide reuse. To declare a function, you simply type:
<?php
   function function_name(param_1, ... , param_n)
   {
      statement_1;
      statement_2;
      ...
      statement_m;

      return return_value;
   }
?>

We can optionally pass parameters to the functions to be known as local variable, and we can also return a result with the "return value" statement. This produces the ending of the function returning a value.

Creating a simple function
Let's create two functions that will print the string "PHP Functions" five times, but the first one will not contain parameters, and the second one will. A function parameter is nothing more than a piece of data that the function requires to execute. In above example also included code to call the function.
 <?php
function firstFunction()
{
    for($i = 0; $i != 5; $i++)
        echo "<P>PHP Functions!</P>";
 }

//let's add parameters to that function
function secondFunction($num, $msg)
{
    for($i = 0; $i != $num; $i++)
        echo "<P>". $msg ."</P>";
}

echo "This is before the functions is called<br>";

echo "The first function output is:"
  firstFuction(5,"This is a function with parameters");

echo "The second function output is:";
  secondFuction(5,"This is a function with parameters");
 
echo "This is after the function has been called<br>";
?>

Next example creates a function that will calculate arithmetic mean and return a result with the "return value" statement: 
<?php
   
function aritmetic_mean($a, $b)
{
   $result = ( $a + $b ) / 2;
   return $result;
}

//print the the results of calculation   
echo aritmetic_mean(4,6),"<br>";
echo aritmetica_mean(3242,524543),"<br>";    
?>

Variable Scope and Lifetime
It's important to note that if you define a variable within a function, that variable is only available within that function; it cannot be referenced in another function or in the main body of your program code.  This is known as a variable's scope.  The scope of a variable defined within a function is  local to that function.
If a function needs to use a variable that is defined in the main body of the program, it must reference it using the "global" keyword, like this:
 <?php
function AddingNumbers ( )
{
   global $sum = 2 + 2
}

$sum = 0
Addnumbers ( )
echo "2 + 2 = ".$sum
?>
While the scope of a variable defined in a function is local to that function, a variable defined in the main body of code has a global scope.  The "global" keyword tells PHP to look for a variable that has been defined outside the function.
And what about lifetime for a variable?  A variable defined within a PHP program script exists only while that script is running.  When the script ends, the variable ceases to exist.  This seems pretty obvious!  Now apply it to a function:  a variable defined within a function exists only while that function is being processed; when the function ends, the variable ceases to exist.

الاثنين، 14 مارس 2011

Arrays

Arrays are special data types. Despite of other normal variables an array can store more than one value.

Creating an array
There are more ways to create an array in PHP. Maybe the most easiest way to create our color list array is the following:

Code:
$colorList = array("red","green","blue","black","white");

Other sollution is to initialise array elements one-by-one as follows:
Code:
$colorList[0] = "red";
$colorList[1] = "green";
$colorList[2] = "blue";
$colorList[3] = "black";
$colorList[4] = "white"; 

If you don't want to bother about numbering - I will explain it later - you can create your array as this:
Code:
$colorList[] = "red";
$colorList[] = "green";
$colorList[] = "blue";
$colorList[] = "black";
$colorList[] = "white"; 


Display the array content
If you want only display one element of the array then you can just write the following code:
Code: 
echo $colorList[0];

This code will display the text "red". However you may want to display all elements in the array. You can write a loop and display them like this:
Code: 
for ($i=0;$i<=4;$i++)
{   echo $colorList[$i];}

It is quite easy. However it is not the best sollution as the number of element is hard coded. There is a much better way to display all elements of an array. You can use a foreach loop as this:
Code: 
foreach ($colorList as $value)
{   echo $value;}

If you want to display array content for debugging purposes then you can use 2 built in PHP functions. These are the print_r and var_dump. These functions displays tha array as key-value pairs. Besides this var_dump also displays variable informations. You can use them as follows:
Code:
print_r($colorList);echo "";
var_dump($colorList);

Associative arrays
Our colorList array can be defined as associative array like this:
Code:
$colorList = array("apple"=>"red",
                   "grass"=>"green",
                   "sky"=>"blue",
                   "night"=>"black",
                   "wall"=>"white");

You have to remember that array keys are case-sensitive, but type insensitive. It means that 'a' differs from 'A' but '1' is the same as 1.
So, the array above can be defined (created) one-by-one elements like this:
Code:
$colorList["apple"] = "red";
$colorList["grass"] = "green";
$colorList["sky"]   = "blue";
$colorList["night"] = "black";
$colorList["wall"]  = "white";

And you can display the content similar to the normal array, but here you need to use the string value instead of the number.
Code: 
echo "The sky is ".$colorList["sky"]    ." and the grass is ".$colorList["grass"];

You can mix your array and use numbers and strings in the same list like this:
Code: 
$colorList["apple"] = "red";
$colorList[5]       = "green";
$colorList["sky"]   = "blue";
$colorList["night"] = "black";
$colorList[22]      = "white";  

Multidimensional arrays

As each element value of the array can be any type it means that it can be other array as well. If an array element value is an other array then this is a multidimensional array. Of course the internal array values can be arrays as well and so on. You can define 10 dimensional (or more) array if you want.

Creating a multidimensional array is as almost simple as the normal array. Let's see an example:


Code: 

$myLists['colors'] = array("apple"=>"red",
                           "grass"=>"green",
                           "sky"=>"blue",
                           "night"=>"black",
                           "wall"=>"white");
                       $myLists['cars'] = array("BMW"=>"M6",
                         "Mercedes"=>"E 270 CDI",
                         "Lexus"=>"IS 220d",
                         "Mazda"=>"6",
                         "Toyota"=>"Avensis");

To acces and display an element in the multidimensional array you just extend the key list as follows:
Code: 

echo $myLists['cars']['Toyota'];

Array functions
During programming it can be neccessary to manipulate arrays. Do do this PHP has some usefull built in functions.

Get the length of the array, or with other words how many elements are in the array. To get this information you can use the sizeof function. It tells you how big is the actual data. You can use it like this:
Code: 

echo sizeof($colorList);

Sometimes you want to remove an element from the array. In this case you can use the unset function like this:
Code:

unset($colorList["sky"]);

To check whether an array has a requested element you can use the isset function as follows:
Code: 

if (isset($colorList["grass"])) echo "OK";

And last you sometimes want to sort your array for eaxmple to display its content in alphabetical order. To do this you have more possibilities. There are more built in array sorting functions in PHP. The most known are sort and asort. The difference between them is that sort renumbers the keys so you will lost the key values. So if you need the key names (associative arrays) use the asort function.
You can use them as follows:
Code:

asort($colorList);
sort($colorList);

Both of the functions sorts values in ascending order. If you want to sort them descending use the corresponding rsort and arsort functions.  

If & while & for Statements

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:

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

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

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

 

The if...elseif....else Statement

Syntax

<?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!";
?>

_______________________________________________________________

The while Loop

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

Syntax

 while (condition)
  {
  code to be executed;
  }

Example

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

The number is 1
The number is 2
The number is 3
The number is 4
The number is 5 
The do...while Statement

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

Output:

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

_______________________________________________________________

The 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;
  } 

Example

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

Output:

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

The foreach Loop

The foreach loop is used to loop through arrays.

Syntax

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

 

Example

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

Output:

one
two
three

PHP Operators

The operators used in PHP.

Arithmetic Operators
Operator Description Example Result
+ Addition x=2
x+2
4
- Subtraction x=2
5-x
3
* Multiplication x=4
x*5
20
/ Division 15/5
5/2
3
2.5
% Modulus (division remainder) 5%2
10%8
10%2
1
2
0
++ Increment x=5
x++
x=6
-- Decrement x=5
x--
x=4

Assignment Operators
Operator Example Is The Same As
= x=y x=y
+= x+=y x=x+y
-= x-=y x=x-y
*= x*=y x=x*y
/= x/=y x=x/y
.= x.=y x=x.y
%= x%=y x=x%y

Comparison Operators
Operator Description Example
== is equal to 5==8 returns false
!= is not equal 5!=8 returns true
<> is not equal 5<>8 returns true
> is greater than 5>8 returns false
< is less than 5<8 returns true
>= is greater than or equal to 5>=8 returns false
<= is less than or equal to 5<=8 returns true

Logical Operators
Operator Description Example
&& and x=6
y=3 (x < 10 && y > 1) returns true
|| or x=6
y=3 (x==5 || y==5) returns false
! not x=6
y=3 !(x==y) returns true

الأربعاء، 9 مارس 2011

String Variables

A string variable is used to store and manipulate text.

String Variables in PHP

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 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 character within a string.
If a match is found, this function will return the 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 our string is position 6. The reason that it is 6 (and not 7), is that the first position in the string is 0, and not 1.

PHP - Variables

PHP - Variables

A variable is a means of storing a value, such as text string "Hello World!" or the integer value 4. A variable can then be reused throughout your code, instead of having to type out the actual value over and over again. In PHP you define a variable with the following form:
  • $variable_name = Value;
If you forget that dollar sign at the beginning, it will not work. This is a common mistake for new PHP programmers!
Note: Also, variable names are case-sensitive, so use the exact same capitalization when using a variable. The variables $a_number and $A_number are different variables in PHP's eyes.

A Quick Variable Example

Say that we wanted to store the values that we talked about in the above paragraph. How would we go about doing this? We would first want to make a variable name and then set that equal to the value we want. See our example below for the correct way to do this.

PHP Code:

<?php
$hello = "Hello World!";
$a_number = 4;
$anotherNumber = 8;
?>
Note for programmers: PHP does not require variables to be declared before being initialized.

PHP Variable Naming Conventions

There are a few rules that you need to follow when choosing a name for your PHP variables.
  • PHP variables must start with a letter or underscore "_".
  • PHP variables may only be comprised of alpha-numeric characters and underscores. a-z, A-Z, 0-9, or _ .
  • Variables with more than one word should be separated with underscores. $my_variable
  • Variables with more than one word can also be distinguished with capitalization. $myVariable

PHP Introduction

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, 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