Nov 7, 2011

PHP Basic



Basic PHP


PHP, which stands for "Hypertext Preprocessor "Is a high-level scripting language embedded in HTML pages. Most of its syntax is similar to C, Java and Perl. The goal of this language is to allow developers to write web pages, dynamic pages quickly and easy.
Example. A basic page
<html>  
  <head>  
  <title> PHP </ title>  
  </ Head>  
  <body>  
        <? Php  echo "This an Example With the PHP !";?> 
   </ Body>  
  </ html> 
Using PHP means never having to write a program with lots of commands to output HTML, but to write HTML code to a certain part of code in PHP embedded in the same file will produce the output. The PHP code is enclosed in special tags start and end <? ​​Php .... ?> That allow us to enter and exit the PHP.
What distinguishes PHP JavaScript technology, which runs on the client machine is that the code is executed on the server. If you have a script similar to the example on our server, the client would receive the results of running on that server, without any ability to determine what code generated the output received. A server configured with these characteristics is to process all your HTML files containing PHP scripts.

PHP Application
At the most basic level, PHP can process information from the forms, generate dynamic page content, or send and receive cookies.
Perhaps the most powerful and remarkable feature of PHP is its support for a large number of databases. Write a web interface for a database is a simple task with PHP. The following databases are currently supported:
Adabas DIngresOracle (OCI8 and OCI7)
dBaseInterBasePostgreSQL
EmpressFrontBaseSolid
FilePromSQLSybase
IBM DB2MySQLVelocis
InformixODBCUnix dbm



History of PHP

PHP was conceived in the autumn of 1994 by Rasmus Lerdof. Early versions were distributed to the public not used in their web pages to maintain control over who consulted their curriculum. The first publicly available version in early 1995 was known as "Tools for personal web pages" (Personal Home Page Tools). Consisted of a very simple parser that only understood a few macros and a number of common utilities on the website then, a guestbook, a counter and other small things. The parser was rewritten in mid-1995 and was named PHP / FI Version 2. FI came from another program that Rasmus had written which forms processed data. So I combined the "Tools for personal web pages," the "Forms Interpreter," he added mSQL support and PHP / FI was born. PHP / FI grew at high speed and people started contributing code.
It is difficult to give exact statistics, but it is estimated that by late 1996 PHP / FI was in use at least 15,000 websites around the world. In mid-1997 this number had grown to over 50,000. In mid 1997 the project underwent a profound change, ceased to be a personal project of Rasmus, whom they had helped a group of users and became a group project much more organized.The parser was rewritten from scratch by Zeev Suraski and Andi Gutmans and this new parser laid the foundation for PHP version 3.0. Large amount of code for PHP / FI was ported to numerous other PHP3 and was written completely new.
Today, both PHP / FI, PHP3 and PHP4 are distributed in a wide range of products such as the web server "C2's Stronghold" and Redhat Linux. A conservative estimate based on statistics from NetCraft (see also Netcraft Survey on Web servers ) is that more than 1,000,000 servers around the world use PHP. To get an idea, this number is greater than the number of servers using the "Netscape's Enterprise server" on the Internet.
While all this is happening, the work of developing the next generation of PHP is running. This version uses the powerful engine of scripts Zend to provide high performance and supports other Web servers, as well as Apache, PHP running as a native module.
The source code and binary distributions for some platforms (including Windows) can be found in http://www.php.net/  . 


PHP Programming Elements
The instructions are separated as in C or perl - ending each sentence with a semicolon (;). The closing tag (?>) Also implies the end of the sentence and the following are equivalent:
<? Php 
  echo "This is a test"; 
  ?> 
  <? Php echo "This is a test"?> 


Data Types

PHP supports the following types:
  • arrangement
  • Floating point numbers
  • whole
  • object
  • chain
The type of a variable not normally indicated by the programmer, but instead, he decides to PHP at runtime depending on the context in which that variable is used.
If you wanted to force a variable to be converted to a particular type, it could force the variable or function using settype () for it.
In PHP a variable identifier always begins with a dollar sign ($).

Whole

Integers can be specified using the following syntax:
$ A = 1234 /  / decimal number  
  $ A = -123,  / / a negative number  
  $ A = 0123 /  / octal number (equivalent to 83 decimal)  
  $ A = 0x12,  / / hexadecimal number (equivalent to 18 decimal) 

Floating point numbers

The floating point numbers ("double") may be specified using any of the following syntax:
$ A = 1234; 
$ A = 1.2e3;

Chains

Character strings can be specified using one of two types of delimiters.
If the string is enclosed in double quotes ("), the variables that are within the string will be expanded (subject to certain limitations of interpretation). As in C and Perl, the backslash character (" \ ") can be used to specify special characters:
Escaped characters
Sequence
meaning
\ N
New line
\ A
Carriage Return
\ T
Horizontal tab
\ \
Backslash
\ $
Dollar sign
\ "
Double quotes
\ [0-7] {1,3}
The sequence of characters matching the regular expression is a character in octal notation
\ X [0-9A-Fa-f] {1,2}
The sequence of characters matching the regular expression is a character in hexadecimal notation
The second way to delimit a string uses the single quote character ('). When a string is enclosed in single quotes, the only escape characters that will be understood are "\ \" and "\ '". The variables within a string delimited by single quotes are not expanded into achain.
Another way to delimit strings is by using the embedded document syntax (<<<). It should provide an identifier EOD after<<<and then the chain.
Example of quoted strings with embedded document syntax:
$ Str = <<<EOD Example of string Expanding multiple lines using incrustado.EOD document syntax;
Note: The syntax of the embedded document was added in PHP 4.
Strings can be concatenated using the '.' (Point). Note that the operator '+' (addition) does not apply to this.
You can access the characters in a string by treating it as a numerically indexed array of characters, using a syntax similar to C. See the following example:
Examples of chains
<? Php
/ * Assigning a string. * /
$ Str = "This is a string";
/ * Appending to it. * /
$ Str = $ str. "With some more text";
/ * Another way to add, including a newline character. * /
$ Str .= "and a newline at the end. \ N";
/ * This string will end up being '<p> Issue 9 </ p>' * /
$ Num = 9; 
$ Str = "<p> Number: $ num </ p>";

/ * This will be '<p> Number: $ num </ p>' * /
$ Num = 9; 
$ Str = '<p> Number: $ num </ p>';

/ * Get the first character of a string * /
$ Str = 'This is a test.'; 
$ First = $ str [0];

/ * Get the last character of a string. * /
$ Str = 'This is still a test.'; 
$ Last = $ str [strlen ($ str) -1];

?>

STRING CONVERSION

When a string is evaluated as a numeric value, the resulting value and type are determined as follows.
The string will evaluate as a double if it contains any of the characters '.', 'E', or 'E'. Otherwise, it evaluates to an integer.
The value is given by the initial portion of the chain. If the string starts with valid numeric data, this is the value used.Otherwise, the value is 0 (zero). Valid numeric data is an optional sign, followed by one or more digits (optionally containing a decimal point), followed by an optional exponent. The exponent is an 'e' or 'E' followed by one or more digits.
When the first expression is a string, the type of the variable depends on the second expression.
$ Foo = 1 + "10.5"  / / $ foo is double (11.5)  
  $ foo = 1 + "-1.3e3"  / / $ foo is double (-1299)  
  $ foo = 1 + "bob-1.3e3"  / / $ foo is integer (1)  
  $ foo = 1 + "bob3"  / / $ foo is integer (1)  
  $ foo = 1 + "10 Little Piggies"  / / $ foo is integer (11)  
  $ foo = "10.0 pigs" + 1 /  / $ foo is integer (11)  
  $ foo = "10.0 pigs" + 1.0 /  / $ foo is double (11) 
The next line will help you check the results in a PHP script:
echo "\ $ foo == $ foo, the type is". gettype ($ foo). "<br> \ N";


Arrangements
In PHP the current arrangements act as both hash tables (associative arrays) or indexed arrays (vectors).

DIMENSIONAL ARRAYS

PHP supports both scalar and associative arrays. You can create an array using the function list () or array () , or you can assign the value of each array element explicitly.
$ A [0] = "abc",  
  $ A [1] = "def",  
  B $ ["foo"] = 13; 
You can also create an array simply adding values ​​to it. When you assign a value to a variable array using empty brackets, the value is added at the end of the array.
$ A [] = "hello"  / / $ a [2] == "hello"  
$ A [] = "world"  / / $ a [3] == "world"

Arrangements can be sorted using various functions of PHP: asort (), arsort (), ksort (), rsort (), sort (), uasort () and uksort () depending on the type of organization required.
You can also count the number of elements in an array using the count () function and browsing functions using next () andprev (). Another common way to traverse an array is using each () function.

MULTIDIMENSIONAL ARRAYS

Multidimensional arrays are actually quite simple. For each dimension of the array, you can add another value [key] at the end:
$ A [1] = $ f / / examples of one-dimensional 
  $ A ['foo'] = $ f,  
  $ A [1] [0] = $ f /  / two-dimensional  
  $ A ['foo'] [2] = $ f /  / (you can mix numeric and associative indices )  
  $ A [3] ["bar"] = $ f /  / (you can mix numeric and associative indices)  
  $ a ["foo"] [4] ['bar'] [0] = $ f  / / four- dimensional! 
You can "fill" multidimensional arrays in many ways, but the easiest is to understand how to use the array function () for associative arrays. These two examples will fill the one-dimensional array in the same way:
/ / Example 1:   
$ A ["color"] = "red",  
  $ A ['taste'] = 'sweet',  
  $ A ['form'] = "rounded",  
  $ A ["name"] = "apple",  
  $ A [3] = 4;   
/ / Example 2:   
$ A = array ("color"  => "red", "taste" => "sweet", "form" => "round", "name" => "apple", 3 => 4); 

Its graphical representation could be:

$ A
color
red
flavor
sweet
form
rounded
name
apple
3
4
The array () function can be used to create multidimensional arrays:
<? Php 
   $ A = array ("apple" => array ("color" => "red", "taste" => "sweet", "form" => "round"),  
  "Orange" => array ("color" => "orange", "taste" => "acid", "form" => "round"),  
  "Banana" => array ("color" => "yellow", "taste" => "sweet" "form" => "aplatanado"));   
echo $ a ["apple"] ["taste"]  / / return "sweet" 
?>

Its graphical representation could be:

$ A
color
flavor
form
apple
red
sweet
rounded
orange
orange
acid
rounded
banana
yellow
sweet
aplatanado


Variables

Variables in PHP are represented by a dollar sign followed by the identifier of the variable. The name of the variable is sensitive to case-sensitive.
$ Var = "Bob",  
  $ var = "Joe";  
  echo "$ var, $ var"  / / outputs "Bob, Joe" 
PHP4 provides another way to assign values ​​to variables: assign by reference. This means that the new variable simply references (in other words, "becomes an alias for" or "targets") to the original variable. Changes to the new variable affect the original, and vice versa. This also means that there is no copying is performed, so the assignment happens more quickly. In any case, any increase in speed is noticed only in cycles or when assigning large arrays or objects.
To assign by reference, simply prepend an ampersand (&) at the beginning of the variable whose value is being assigned (the source variable). For example, the following code outputs 'My name is Bob' twice:
<? Php 
$ Foo = 'Bob' / / Assign the value 'Bob' to $ foo 
  $ Bar = & $ foo / / path reference $ foo $ bar. 
  $ Bar = "My name is $ bar" / / Changing to $ bar ... 
  echo $ foo / / $ foo is altered too. 
  echo $ bar; 
?>
One important thing to note is that only named variables may be assigned by reference.
<? Php 
$ Foo = 25; 
  $ Bar = & $ foo / / This is a valid assignment. 
  $ Bar = & (24 * 7) / / Invalid; references an unnamed expression.   
function test () { 
  return 25; 
  }   
$ Bar = & test ();       / / Invalid. 
?>


Variable Scope

The scope of a variable is the context within which the variable is defined. Most of the PHP variables only have a single scope.This single scope spans included and files required. For example:
$ A = 1,  
  includes "b.inc"; 
Here, the scope of the variable $ A covers the script included in b.inc.
Within the user-defined functions a local level appears to function. Any variable used inside a function is by default limited to the local level of this function. For example:
$ A = 1,  / * global scope * /
Function Test () { 
  echo $ a; / * reference to local scope variable * / 
  }   
Test ();
This script does not produce any output because the echo a local version of the variable a, which has not been assigned any value within this scope. You may notice a slight difference with the C language in that global variables are automatically available to function unless specifically overwritten by a local definition. This may cause some problems because people may inadvertently change a global variable. In PHP global variables must be declared global inside a function if they are to be used within it.
Example:
$ A = 1;  
  $ B = 2;   
Function Sum () {  
       global $ a, $ b;  
  $ B = $ a + $ b;  
  }   
Sum ();  
  echo $ b; 
The above script will output "3". By declaring $ a and $ b global within the function, all references to either variable will refer to the global version. There is no limit to the number of global variables can be manipulated within a function.
A second way to access variables from the global scope is $ GLOBALS array using PHP3 own. The above example can be rewritten as:
$ A = 1;  
  $ B = 2;   
Function Sum () {  
  $ GLOBALS ["b"] = $ GLOBALS ['a'] + $ GLOBALS ["b"];  
  }   
Sum ();  
  echo $ b; 
The $ GLOBALS is an associative array with the global variable name as key and the contents of that variable as the value of array element.
Another important feature of variable scoping is the static variable. A static variable exists only in the local function scope, but does not lose its value when program execution leaves this scope. Consider the following example:
Function Test () { 
  $ A = 0; 
       echo $ a; 
  $ A + +; 
  } 
This function is quite useless since every time it is called it sets $ a to the value. The $ a + + which increments the variable serves no purpose as soon as the function ends, the $ a variable disappears. To make a useful counting function which will not lose track of the current count, the $ a variable must be declared as static:
Function Test () { 
       static $ a = 0; 
       echo $ a; 
  $ A + +; 
  } 
Now, every time you call the function Test (), will preserve the value of $ a and increment it.
Static variables also provide a way to deal with recursive functions. A recursive function is one that calls itself. Care must be taken when writing a recursive function because it can happen that calls itself indefinitely. Make sure an adequate way of terminating the recursion. The following simple function recursively counts to 10, using the static variable $ count to know when to stop:
Function Test () { 
       static $ count = 0; 
  $ Count + +; 
  echo $ count; 
if ($ count <10) {  
  Test ();  
       } 
      $ Count -;  
  } 


Variables from outside PHP 
HTML Forms (GET and POST)

When you send a form to a PHP script, the form variables are automatically available through the same PHP script. For example, consider the following form:
Variables simple form
action="foo.php" <form method="post"> 
  Name: <input type="text" name="nombre"> <br> 
       <input type="submit"> 
  </ Form> 
When the form is submitted, PHP will create the variable name, containing what is entered in the Name: field of the form.
PHP also handles arrangements in the context of form variables, but only in one dimension. You can, for example, group related variables together, or use this feature to retrieve values ​​from a multiple select input:
More complex form variables
action = "arreglo.php" <form method="post">  
  Name: <input type = "text"  persona [name]  name = "  "> <br>  
  Email: <input type = "text"  persona [email]  name = "  "> <br>  
  Drink: <br>  
  <select multiple name = "  bebida []  ">  
  Water value = "agua"> <option  
  value = Wine "wine"> <option  
  value = Beer "cerveza"> <option  
  </ select>  
  <input type="submit">  
  </ form> 
If the feature is enabled track_vars PHP, either by setting track_vars or through the <? php_track_vars?>, the variables sent by POST or GET methods form also will be available in the global associative arrays $ HTTP_POST_VARS and $HTTP_GET_VARS.


Operators

PHP provides a set of very simple to use operators to form expressions. 
Arithmetic Operators
Example
Name
Result
$ A + $ b
Addition
Sum of $ a and $ b.
$ A - $ b
Subtraction
Difference between $ a and $ b.
$ A * $ b
Multiplication
Product of $ a and $ b.
$ A / $ b
Division
Ratio between $ b $ a
$ A% $ b
Module
Remainder of $ a divided by $ b.

Assignment Operators

The basic assignment operator is an equal sign "=". At first glance one might think that the comparison operator is "equal to".But no, actually means that the left operand has the value of the expression to the right (ie, "take the value of").
The value of an assignment expression is the actual value assigned.
That is, the value of $ a = 3 is 3. This allows for important things like
$ A = ($ b = 4) + 5 / / now $ a is equal to 9, and $ b is 4.
In addition to the basic assignment operator, there are "combined operators" for all arithmetic and are binary strings. The combined operator allows one time, use a variable in an expression and then set the value of that variable to the result of the expression. For example:
$ A = 3; 
  $ A + = 5; / / sets $ a to 8, as if we had written $ a = $ a + 5; 
  $ B = "Hello"; 
  $ B .= "There!" / / Sets $ ba "Hello There!" Just as if we made ​​$ b = $ ​​b.  "There!" 
Note that the assignment makes a new copy of the original variable (assignment by value), so changes to the original variable does not affect the copy. This may be of interest if required to copy something like an array with many elements within a cycle is repeated many times (each time you make a new copy of the array). PHP 4 supports assignment by reference, using the $ var = & $ otravar;, but this is not possible in PHP 3. Assignment by reference means that both variables end up pointing to the same data is copied and nothing really.


Bitwise Operators

The bitwise operators allow you to enable or disable individual bits of an integer.
Example
Name
Result
$ A & $ b
And
Activate the bits that are set in both $ a and $ b.
$ A | $ b
O
Activates the bits that are set in $ a or that are in $ b.
$ A ^ $ b
XOR ("exclusive or")
Activate the bits that are set in $ a or $ b but not both at once.
~ $ A
Not
Bits are activated that are not set in $ a.
$ A <<$ b
Move leftShift the bits of $ a, $ b position to the left (for binary arithmetic, each displaced position equal to double the value of $ a)
$ A>> $ b
Right ShiftShift the bits of $ a, $ b places to the right (for binary arithmetic, each displaced position is equivalent to dividing by two the value of $ a)

Comparison Operators

Comparison operators, as its name implies, allow you to compare two values ​​and establish a relationship between them.
Example
Name
Result
$ A == $ b
Equality
True if $ a is equal to $ b.
$ A === $ b
Identity
True if $ a is equal to $ b if the same type (PHP4 only)
$ A! = $ B
Inequality
True if $ a is not equal to $ b.
$ A <$ b
Less than
True if $ a is strictly less than $ b.
$ A> $ b
Greater than
True if $ a is strictly greater than $ b.
$ A <= $ b
Less than or equal
True if $ a is less than or equal to $ b.
$ A> = $ b
Greater than or equal
True if $ a is greater than or equal to $ b.
Another important operator is the ternary conditional represented by "?", Which functions as in C and many other languages.
(Expr1)?  (expr2): (expr3);
The expression takes the value expr2 if expr1 evaluates to true, and expr3 if expr1 evaluates to false.


Increment / Decrement

PHP supports decrement operators pre and post-increment-style C.
Example
Name
Effect
+ + $ A
Preincrement
Increments $ a by one, then returns $ a.
$ A + +
Postincrement
Returns $ a, then increments $ a by one.
- $ A
Predecremento
Decrements $ a by one, then returns $ a.
A $ -
Postdecremento
Returns $ a, then decrements $ a by one.
Example:
<? Php 

  echo "<h3> postincrement </ h3>",  
  $ A = 5;  
  echo "Should be 5:". $ A ++."< br> \ n "  
  echo "Should be 6:". $ A. "<br> \ N"  
  echo "<h3> preincrement </ h3>",  
  $ A = 5;  
  echo "Should be 6: a. ".++$" <br> \ n "  
  echo "Should be 6: ". $ A. "<br> \ N"  
  echo "<h3> Postdecremento </ h3>"; 
$ A = 5; 
  echo "Should be 5:". $ a -. "<br> \ n"; 
  echo "Should be 4:". $ a.  "<br> \ N"; 
  echo "<h3> Predecremento </ h3>"; 
$ A = 5; 
  echo "Should be 4: a. ".--$  "<br> \ N"; 
  echo "Should be 4:". $ a.  "<br> \ N"; 
?>  

Logical Operator
Example
Name
Result
$ A and $ b
And
True if both $ a and $ b are true.
$ A or $ b
O
True if $ a or $ b are true.
$ A xor $ b
Exclusive OR
True if $ a is true or $ b is true, but not both at once.
 $ A
Denial
True if $ a is not true.
$ A & & $ b
And
True if both $ a and $ b are true.
$ A | | $ b
O
True if $ a or $ b are true.
The ratio of the two variations of "and" y "or" is that they operate with different precedence 


Operator Precedence
Operator precedence specifies how to group expressions. For example, the expression 1 + 5 * 3, the answer is 16 and not 18 because the multiplication operator ("*") has a higher precedence than addition ("+").
The following table lists the precedence of operators, indicating the lowest priority first.
Associativity
Operators
left
,
left
or
left
xor
left
and
right
print
left
= + = -= *= / = .=% = & = | = ^ = ~ = = <<=>>
left
 :
left
| |
left
& &
left
|
left
^
left
&
nonassociative
==! = ===
nonassociative
<<=>> =
left
<<>>
left
+ -.
left
* /%
right
! ~ + + - (Int) (double) (string) (array) (object) @
right
[
nonassociative
new


Chain Operators

There are two string operators. The first is the concatenation operator dot (.), Which returns the concatenation of its left and right operands. The second is the concatenation assignment operator point equals (.=).
$ A = "Hello"; 
  $ B = $ a.  "World!" / / Now $ b contains "Hello World!" 
  $ A = "Hello"; 
  $ A .= "World!" / / Now $ a contains "Hello World!" 


Judgments

Any PHP script consists of a series of statements. A statement can be an assignment, a function call, a loop, a conditional statement of even a statement that does nothing (an empty statement). Statements usually end with a semicolon. In addition, statements may contain groups of statements enclosed in braces. A group of statements is also a sentence. 

If decision structure

The if construct is one of the most important features of many languages, including PHP. Allows conditional execution of code fragments. If PHP defines a structure that is similar to that of C:
if (expr) 
  sentence 
Where expr is evaluated and used as conditional value. If expr evaluates to true (TRUE), PHP will execute statement and if it evaluates to false (FALSE) will ignore it.
The following example would display a is bigger than b if $ a is bigger than b:
if ($ a> $ b) 
  print "a is bigger than b"; 
Often, you want more of a statement to be executed conditionally. Of course, no need to wrap each statement with an ifclause. Instead, you can group several statements. For example, this code would display a is bigger than b if $ a is bigger than $b, and then assign the value of a into $ b:
if ($ a> $ b) { 
  print "a is bigger than b"; 
  $ B = $ a; 
  } 
If statements can be nested indefinitely within other if statements, which provides complete flexibility for conditional execution of different parts of the program.

else

Often we want to execute a statement if a certain condition is met and a different statement if the condition is not met. This is what else is for. Complement else extends an if statement to execute a statement if the expression in the if statement evaluates to false. For example, the following code would display a is bigger than b if $ a is bigger than b, and a is NOT bigger than b otherwise:
if ($ a> $ b) { 
  print "a is bigger than b"; 
  } 
  else { 
  print "a is NOT bigger than b"; 
  } 

elseif

elseif, as its name suggests, is a combination of if and else. Like else, it extends an if statement to execute a different statement in case the original if expression is evaluated as false. However, unlike else, it will run alternative expression only if the elseif conditional expression evaluates to TRUE. For example, the following code would display a is bigger than b, a equals b or a is smaller than b:
if ($ a> $ b) { 
      print "a is bigger than b"; 
  } Elseif ($ a == $ b) { 
      print "a equals b"; 
  Else {} 
  print "a is bigger than b"; 
  } 
There may be several elseif 's within the same if statement. The first elseif expression (if any) that evaluates to true is executed. In PHP, you can also write else if (two words) and the behavior would be identical to a elseif (one word). The syntactic meaning is slightly different but the bottom line is that both result in exactly the same behavior.
The elseif statement is only executed if the preceding if expression and any preceding elseif expressions evaluate to false and the current elseif expression evaluated as true.


Cyclic structure while

The while loops are the simplest in PHP. They behave like their C counterparts The basic form of a while statement is:
while (expr) statement
The meaning of a while statement is simple. It tells PHP to execute the (s) statement (s) nested (s) repeatedly, as the whileexpression evaluates to true. The value of the expression is checked each time at the beginning of the cycle, so even if this value changes during the execution (s) statement (s) nested (s), execution will not stop until the end of the iteration (each time PHP runs the statements in the loop is one iteration). Sometimes, if the while expression evaluates to false from the beginning, the (s) statement (s) nested (s) will not run even once.
As with the while statement, you can group multiple statements within the while loop, surrounding a group of statements with curly braces, or using the alternate syntax:
while (expr) statement ... endwhile;
The following examples are identical and both print numbers from 1 to 10:
/ * Example 1 * / 

  $ I = 1; 
while ($ i <= 10) { 
       print $ i + + / * the printed value would be $ i before the increment (post-increment) * / 
  } 
/ * Example 2 * / 
$ I = 1; 
while ($ i <= 10):  
  print $ i;  
  $ i + +;  
  endwhile;   


Do .. while cyclic structure

The cycles do .. while are very similar to while loops, except that the conditions are checked at the end of each iteration instead of the beginning. The main difference from regular cycles while is ensuring the implementation of the first iteration of a do .. while(the condition is checked only at the end of the iteration), while it may not necessarily run with a while loop regular (the condition is checked at the beginning of each iteration, if it evaluates as false from the beginning the loop execution would end immediately).
There is only one syntax for do .. while cycles:
$ I = 0;  
  do {  
  print $ i;  
  } while ($ i> 0); 
The above cycle is executed exactly once, after the first iteration, when truth expression is checked, it evaluates to false ($ i is not bigger than0 ) And the loop execution ends.
Advanced C users may be familiar with a different use do .. while cycle, which allows you to stop execution in the middle of code blocks, by encapsulating it with a do .. while (0) and using the break statement to exit. The following code fragment demonstrates this:
do {  
  if ($ i <5) {  
            print "i is not big enough";  
            break;  
  }  
  $ $ I *= factor;  
  if ($ i <$ minimum_limit) {  
            break;  
  } 
print "i is correct"; 
  ... Processes i. .. 
  } While (0) / / break the endless cycle controlled 

Cyclic structure for
The cycles are more complex for PHP. They behave like their C counterparts The syntax of a for loop is:
for (expr1, expr2, expr3) statement
The first expression (expr1) is evaluated or executed once unconditionally at the beginning of the cycle.
At the beginning of each iteration, expr2 is evaluated . If it evaluates to true, the cycle continues and the nested statement is executed. If it evaluates to false, the loop execution ends. At the end of each iteration, we evaluate expr3.
Each of the expressions can be empty. Expr2 being empty means that the cycle should be run indefinitely (PHP implicitly considers it as true, as C). This may not be as useless as you might think, since they often want to exit a loop by using a conditional break statement instead of using the condition for.
Consider the following examples. All of them display numbers from 1 to 10:
/ * Example 1 * / 

  for ($ i = 1, $ i <= 10; $ i + +) { 
  print $ i; 
  } 
/ * Example 2 * / 
for ($ i = 1;; $ i + +) {  
    if ($ i> 10) {
      break; 
   } 
   print $ i;   } 
/ * Example 3 * / 

  $ I = 1; 
for (;;) { 
    if ($i > 10) { 
      break; 
   } 
   print $i; 
   $ I + +;   } 
/ * Example 4 * / 
for ($ i = 1; $ i <= 10; print $ i, $ i + +); 
PHP also supports the "  colon syntax  "alternative cycles  for  .
for (expr1, expr2, expr3) sentence; ...; endfor; break


break  unconditionally changes the execution flow out of the following structures:  for  ,  while  , or  switch  .
break  accepts an optional parameter, which determines how many control structures must come out.

continuous

continue  is used within the structure of the loop to skip the rest of this current iteration and continue execution at the beginning of the next iteration.
continue  accepts an optional parameter, which determines how many levels should cycle to jump before continuing execution.


Switch decision structure

The statement  switch  is similar to a series of statements  if  the same expression. In many cases, is to compare the same variable (or expression) with many different values ​​and execute a different piece of code depending on which value is equal. This sentence serves the  switch  .
The following two examples are two different ways to write the same structure, one uses a series of statements  if  the other uses the sentence  switch  :
if ($ i == 0) {  
   print "eg Igual 0";   } 
if ($ i == 1) {  
   print "eg Igual 1";   } 
if ($ i == 2) {  
   print "eg Igual 2";   } 
switch ($i) { 
 case 0:           print "i es igual a 0";   break; 
 case 1: 
 print "i es igual a 1";   break; 
 case 2: 
 print "i es igual a 2"           break;  
  } 
It is important to understand how it executes the statement  switch  to avoid errors. The ruling  switch  runs line by line (actually, statement by statement). At the beginning, no code is executed. Only when a sentence is  married  with a value that matches the expression value of the  switch  . and PHP begin to execute the sentence. PHP will execute the statements until the end of the block  switch  statement or until the first  break  that encounter. If there is a sentence  break  at the end of a list of statements case  , PHP will execute the statements following the  case  .  For example:
switch ($ i) {  
 case 0:            echo "i es Igual 0";        case 1:  echo "i es Igual 1";
 case 2:  print "eg Igual 2";   } 
Here, if  $ i  is equal to 0,  PHP would execute all statements in  print  !.  If  $ i  is equal to 1, PHP would execute the last two sentences  print  and only if   i is equal to 2, it would conduct  'expected '  show and only  'i equals 2'  . Thus, it is important to remember the sentences  break  (even if intentionally may want to avoid in certain circumstances).
In a statement  switch  , the condition is evaluated only once and the result is compared in each sentence  case  . In a statement elseif  , the condition is evaluated again. If the condition is more complex than a simple comparison is within a short cycle, a structure  switch  may be more convenient.
The statement list of a  case  can also be empty, which simply passes control to the statement list for the next  case  .
switch ($ i) {  
     case 0:        case 1:      case 2:
        print "menor que es 3, but not negative";             break; 
      case 3:          print "example 3";
   } 
A special case is the  default  . This type of  case  matches anything that did not match the other  case   For example:
switch ($i) { 
 case 0:            print "i es igual a 0";             break; 
 case 1: print "i es igual a 1"; break; case 2: print "i es igual a 2";            break; 
       default: 
 print "i no es igual a 0, 1 o 2"; 
  } 
The term  case  can be any expression that evaluates to a simple type, ie integers or floating point strings. Can not be used here or arrays, or objects unless they are converted to a simple type.
The alternative syntax for control structures mentioned above, is available for the  switch  .
switch ($ i)  
 case 0:            print "i equals 0"; 
            break; 
  case 1: print "i equals 1"; break; case 2: print "i equals 2";             break; 
  default: print "i is not equal to 0, 1 or 2";  endswitch; 

User-Defined Functions
A function is defined with the following syntax:
function foo ($ arg_1, $ arg_2, ..., $ arg_n) {  
   echo "Example function. \ n";
  return $retval;
  } 

PASSING PARAMETERS BY REFERENCE

By default, the function parameters  are passed by value  (so if you change the value of the argument within the function, not get changed outside of it). To allow a function to modify its parameters must be passed by reference. This is achieved by putting an ampersand  (   ) to the parameter name in the definition of the function:
function add_some_extra(&$string) { 
      $string .= ' y algo más.'; 
  } 
$ Str = 'This is a string';  
 add_some_extra ($ str);
  echo $ str;  / / outputs 'This is a string, and then some.'   


MySQL Functions

PHP provides a broad set of functions that allow access to server databases using MySQL.
You can find more information about MySQL  http://www.mysql.com/
Below are the most used functions in PHP to manage a MySQL database. Complete examples of its use are discussed in the next section of the course.
MySQL Function Table
Function
Description
mysql_affected_rowsReturns the number of affected rows in previous MySQL operation
mysql_change_userChange logged in user of the active connection
mysql_client_encodingReturns the name of the character set
mysql_closeClose the MySQL connection
mysql_connectOpens a connection to a MySQL server
mysql_create_dbCreate a MySQL database
mysql_data_seekMoves the internal pointer
mysql_db_nameGet result data
mysql_db_querySend a MySQL query
mysql_drop_dbDeletes a MySQL database
mysql_errnoReturns the number of error messages in previous MySQL operation
mysql_errorReturns the text of error message in previous MySQL operation
mysql_escape_stringEscapes a string for use in a mysql_query.
mysql_fetch_arrayFetch a result row as an associative array
mysql_fetch_assocRetrieves a result row as an associative array
mysql_fetch_fieldExtracts information from a column and returns it as an object.
mysql_fetch_lengthsReturns the length of each output in a result
mysql_fetch_objectFetch a result row as an object
mysql_fetch_rowReturns a result row as an array
mysql_field_flagsGet the flags associated with the specified field in a result
mysql_field_lenReturns the specified field length
mysql_field_nameReturns the name of the specified field in a result
mysql_field_seekAssigns the result pointer to a specified field offset
mysql_field_tableReturns the name of the table that the specified field
mysql_field_typeReturns the type of the specified field in a result
mysql_free_resultFrees the result memory
mysql_get_client_infoMySQL client information
mysql_get_host_infoObtain information from the MySQL host
mysql_get_proto_infoGet MySQL protocol info
mysql_get_server_infoMySQL server information
mysql_infoGet information about the most recent query
mysql_insert_idReturns the ID generated from the previous INSERT operation
mysql_list_dbsList databases available on the MySQL server
mysql_list_fieldsList result fields in MySQL
mysql_list_processesList MySQL processes
mysql_list_tablesList tables in a MySQL database
mysql_num_fieldsReturns the number of fields in result
mysql_num_rowsReturns the number of rows in result
mysql_pconnectOpens a persistent connection to MySQL server
mysql_pingMake a check of response (ping) on ​​a server connection or reconnect if there is no connection
mysql_querySend a MySQL query
mysql_real_escape_string
Escapes special characters in a string for use in an SQL statement, taking in the current charset of the connection.
IMPORTANT NOTE  : The material presented in this section was removed, revised, supplemented and synthesized from the official PHP manual can be found at:  http://www.php.net/

0 comments:

Post a Comment

Twitter Delicious Facebook Digg Stumbleupon Favorites More

 
Design by Free WordPress Themes | Bloggerized by Lasantha - Premium Blogger Themes | Premium Wordpress Themes