PHP Basics GnuGroup India ILG-Insight GNU/Linux Group Prepared By:Jagjit Phull
Flow in the Web.....
Dynamic content flow
Calling the PHP Parser Invoking PHP Method 1 <?php echo &quot;Hello world&quot; ; ?> Method 2 <? echo &quot;Hello world&quot;; ?>
The Structure of PHP Using Comments There are two ways in which you can add comments to your PHP code. The first turns a single line into a comment by preceding it with a pair of forward slashes, like this: // This is a comment This version of the comment feature is a great way to temporarily remove a line of code from a program that is giving you errors. You can also use this type of comment directly after a line of code to describe its action, like this: $x += 10; // Increment $x by 10 When you need multiple-line comments <?php /* This is a section of multiline comments which will not be interpreted */ ?>
Basic Syntax Semicolons
PHP commands end with a semicolon, like this:
$x += 10;
The $ symbol, you must place a $ in front of all variables. Three different types of variable assignment
<?php
$mycounter = 1;
$mystring = &quot;Hello&quot;;
$myarray = array(&quot;One&quot;, &quot;Two&quot;, &quot;Three&quot;);
?>
Variables Think of variables as matchboxes containing items.
String variables
Imagine you have a matchbox on which you have written the word username. You then write Fred Smith on a piece of paper and place it into the box.The same process as assigning a string value to a variable, like this:
$username = &quot;Fred Smith&quot;;
The quotation marks indicate that “Fred Smith” is a string of characters.
When you want to see what’s in the box, you open it, take the piece of paper out, and read it. In PHP, doing so looks like this:
echo $username;
e.g <?php // test1.php $username = &quot;Fred Smith&quot;; echo $username; echo &quot;<br />&quot;; $current_user = $username; echo $current_user; ?> Call it up by entering the URL of your web development directory and the filename test1.php into the address bar of your browser.
http://localhost/web/test1.php
Numeric variables $count = 17;
$count = 17.5; Variables don’t contain just strings—they can contain numbers, too. Using the matchbox analogy, to store the number 17 in the variable $count, the equivalent would be placing, say, 17 beads in a matchbox on which you have written the word count:
You could also use a floating-point number (containing a decimal point); the syntax is the same:
Arrays $team = array('Bill', 'Joe', 'Mike', 'Chris', 'Jim'); You can think of them as several matchboxes glued together.
let’s say we want to store the player names for a five-person soccer team in an array called $team. To do this, we could glue five matchboxes side by side and write down the names of all the players on separate pieces of paper, placing one in each matchbox.
Across the whole top of the matchbox assembly we would write the word team.
If we then wanted to know who player 4 is, we could use this command:
echo $team[3]; // Displays the name Chris
Two Dimensional Arrays A multidimensional array simulated with matchboxes.
It’s easy to understand if you grasp the basic array syntax. There are three array() constructs nested inside the outer array() construct.
To then return the third element in the second row of this array, you would use the following PHP command, which will display an “x”:
echo $oxo[1][2]; As an example of a two-dimensional array, let’s say we want to keep track of a game of tic-tac-toe, which requires a data structure of nine cells arranged in a 3×3 square.
To represent this with matchboxes, imagine nine of them glued to each other in a matrix of three rows by three columns.
You can now place a piece of paper with either an “x” or an “o” in the correct matchbox for each move played.
Defining a two-dimensional array
<?php
$oxo = array(array('x', '', 'o'),
array('o', 'o', 'x'),
array('x', 'o', '' ));
?>
Variable naming rules When creating PHP variables, you must follow these four rules: • Variable names must start with a letter of the alphabet or the _ (underscore) character. • Variable names can contain only the characters: a-z, A-Z, 0-9, and _ (underscore). • Variable names may not contain spaces. If a variable must comprise more than one word it should be separated with the _ (underscore) character. (e.g., $user_name). • Variable names are case-sensitive. The variable $High_Score is not the same as the variable $high_score.
Operators Arithmetic operators
operators Assignment
Operators Comparison
Operators Logical
Variable Assignment The syntax to assign a value to a variable is always variable = value Or To reassign the value to another variable, it is other
variable = variable.
Variable incrementing and decrementing
Adding or subtracting 1 is a common operation that PHP provides special operators for it. You can use one of the following in place of the += and -= operators:
++$x;
--$y;
String concatenation String concatenation uses the period (.) to append one string of characters to another.
echo &quot;You have &quot; . $msgs . &quot; messages.&quot;;
Just as you can add a value to a numeric variable with the += operator, you can append one string to another using .= like this:
$bulletin .= $newsflash;
In this case, if $bulletin contains a news bulletin and $newsflash has a news flash, the command appends the news flash to the news bulletin so that $bulletin now comprises both strings of text.
String types PHP supports two types of strings that are denoted by the type of quotation mark that you use. If you wish to assign a literal string, preserving the exact contents, you should use the single quotation mark (apostrophe) like this: $info = 'Preface variables with a $ like this: $variable'; In this case, every character within the single-quoted string is assigned to $info. If you had used double quotes, PHP would have attempted to evaluate $variable as a variable. When you want to include the value of a variable inside a string,you do so by using double-quoted strings: echo &quot;There have been $count presidents of the US&quot;;
Escaping characters Sometimes a string needs to contain characters with special meanings that might beinterpreted incorrectly. For example, the following line of code will not work, because the second quotation mark encountered in the word sister’s will tell the PHP parser that the string end has been reached. Consequently, the rest of the line will be rejected as an error:
$text = 'My sister's car is a Ford'; // Erroneous syntax
To correct this, you can add a backslash directly before the offending quotation mark to tell PHP to treat the character literally and not to interpret it:
$text = 'My sister\'s car is a Ford';
Variable Typing PHP is a very loosely typed language. This means that variables do not have to be declared before they are used, and that PHP always converts variables to the type required by their context when they are accessed.
For example, you can create a multiple-digit number and extract the nth digit from it simply by assuming it to be a string. In the following snippet of code, the numbers 12345 and 67890 are multiplied together, returning a result of 838102050, which is then placed in the variable $number,
Automatic conversion from a number to a string
<?php
$number = 12345 * 67890;
echo substr($number, 3, 1);
?>
At the point of the assignment, $number is a numeric variable. But on the second line,a call is placed to the PHP function substr, which asks for one character to be returned from $number, starting at the fourth position (remembering that PHP offsets start from zero). To do this, PHP turns $number into a nine-character string, so that substr can access it and return the character, which in this case is 1.
Automatically converting a string to a number
<?php
$pi = &quot;3.1415927&quot;;
$radius = 5;
echo $pi * ($radius * $radius);
?>
Constants Constants are similar to variables, holding information to be accessed later, except that they are what they sound like—constant. In other words, once you have defined one, its value is set for the remainder of the program and cannot be altered. e.g to hold the location of your server root (the folder with the main files of your website). You would define such a constant like this:
define(&quot;ROOT_LOCATION&quot;, &quot;/usr/local/www/&quot;);
Then, to read the contents of the variable you just refer to it like a regular variable (but it isn’t preceded by a dollar sign):
$directory = ROOT_LOCATION;
Now, whenever you need to run your PHP code on a different server with a different folder configuration, you have only a single line of code to change.
NOTE: The main two things you have to remember about constants are that they must not be prefaced with a $ sign (as with regular variables), and that you can define them only using the define function.
Predefined constants PHP's magic constants:One handy use of these variables is for debugging purposes, when you need to insert a line of code to see whether the program flow reaches it:
echo &quot;This is line &quot; . __LINE__ . &quot; of file &quot; . __FILE__;
This causes the current program line in the current file (including the path) being executed to be output to the web browser.
The Difference Between the echo and print Commands print is an actual function that takes a single parameter.
Print can be used for complex expressions. an example to output whether the value of a variable is TRUE or FALSE using print, something you could not perform in the same manner with echo, because it would display a “Parse error” message:
$b ? print &quot;TRUE&quot; : print &quot;FALSE&quot;;
The question mark is simply a way of interrogating whether variable $b is true or false. Whichever command is on the left of the following colon is executed if $b is true, whereas the command to the right is executed if $b is false. echo is a PHP language construct.
The echo command will be a be faster than print in general text output, because, not being a function, it doesn’t set a return value.
As it isn’t a function, echo cannot be used as part of a more complex expression.
Functions Functions are used to separate out sections of code that perform a particular task. For example, maybe you often need to look up a date and return it in a certain format. To create a function
A simple function declaration
<?php
function longdate($timestamp)
{
return date(&quot;l F jS Y&quot;, $timestamp);
}
?>
This function takes a Unix timestamp (an integer number representing a date and time based on the number of seconds since 00:00 AM on January 1, 1970) as its input and then calls the PHP date function with the correct format string to return a date in the format Wednesday August 1st 2012.
To output today’s date using this function, place the following call in your code:
echo longdate(time());
Variable Scope If you have a very long program, it’s quite possible that you could start to run out of good variable names, but with PHP you can decide the scope of a variable. In other words, you can, for example, tell it that you want the variable $temp to be used only inside a particular function and to forget it was ever used when the function returns.
Local variable s : Local variables are variables that are created within and can be accessed only by a function. They are generally temporary variables that are used to store partially processed results prior to the function’s return.
<?php
function longdate($timestamp)
{
$temp = date(&quot;l F jS Y&quot;, $timestamp);
return &quot;The date is $temp&quot;;
}
?>
The value returned by the date function to the temporary variable $temp, which is then inserted into the string returned by the function.
Global variables :There are cases when you need a variable to have global scope, because you want all your code to be able to access it. Also, some data may be large and complex, and you don’t want to keep passing it as arguments to functions.
To declare a variable as having global scope, use the keyword global. Let’s assume that you have a way of logging your users into your website and want all your code to know whether it is interacting with a logged-in user or a guest. One way to do this is to create a global variable such as $is_logged_in:
global $is_logged_in;
Now your login function simply has to set that variable to 1 upon success of a login attempt, or 0 upon its failure. Because the scope of the variable is global, every line of code in your program can access it.
Static Variables What if you have a local variable inside a function that you don’t want any other parts of your code to have access to, but that you would also like to keep its value for the next time the function is called?
The solution is to declare a static variable,
A function using a static variable
<?php
function test()
{
static $count = 0;
echo $count;
$count++;
}
?>
Here the very first line of function test creates a static variable called $count and initializes it to a value of zero. The next line outputs the variable’s value; the final one increments it.
Allowed and disallowed static variable declarations
<?php
static $int = 0; // Allowed
static $int = 1+2; // Disallowed (will produce a Parse error)
static $int = sqrt(144); // Disallowed
?>
Superglobal variables Starting with PHP 4.1.0, several predefined variables are available. These are known as superglobal variables, which means that they are provided by the PHP environment but are global within the program, accessible absolutely everywhere. These superglobals contain lots of useful information about the currently running program and its environment They are structured as associative arrays.
Superglobals and security A word of caution is in order before you start using superglobal variables, because they are often used by hackers trying to find exploits to break in to your website. What they do is load up $_POST, $_GET, or other superglobals with malicious code, such as Unix or MySQL commands that can damage or display sensitive data if you naïvely access them.
Therefore, you should always sanitize superglobals before using them. One way to do this is via the PHP htmlentities function. It converts all characters into HTML entities. For example, less-than and greater-than characters (< and >) are transformed into the strings &lt; and &gt; so that they are rendered harmless, as are all quotes and backslashes, and so on. A much better way to access $_SERVER (and other superglobals) is:
$came_from = htmlentities($_SERVER['HTTP_REFERRER']);
Expressions and Control Flow in PHP
Expressions An expression is a combination of values,variables, operators, and functions that results in a value. It’s familiar to elementary-school algebra:
y = 3(abs(2x) + 4)
which in PHP would be:
$y = 3 * (abs(2*$x) + 4);
Four simple Boolean expressions
<?php
echo &quot;a: [&quot; . (20 > 9) . &quot;]<br />&quot;;
echo &quot;b: [&quot; . (5 == 6) . &quot;]<br />&quot;;
echo &quot;c: [&quot; . (1 == 0) . &quot;]<br />&quot;;
echo &quot;d: [&quot; . (1 == 1) . &quot;]<br />&quot;;
?>
Literals and Variables The simplest form of an expression is a literal, which simply means something that evaluates to itself, such as the number 73 or the string “Hello”. An expression could also simply be a variable, which evaluates to the value that has been assigned to it. They are both types of expressions, because they return a value. Five types of literals
<?php
$myname = &quot;Brian&quot;;
$myage = 37;
echo &quot;a: &quot; . 73 . &quot;<br />&quot;; // Numeric literal
echo &quot;b: &quot; . &quot;Hello&quot; . &quot;<br />&quot;; // String literal
echo &quot;c: &quot; . FALSE . &quot;<br />&quot;; // Constant literal
echo &quot;d: &quot; . $myname . &quot;<br />&quot;; // Variable string literal
echo &quot;e: &quot; . $myage . &quot;<br />&quot;; // Variable numeric literal
?>
An expression and a statement
<?php
$days_to_new_year = 366 - $day_number; // Expression
if ($days_to_new_year < 30)
{
echo &quot;Not long now till new year&quot;; // Statement
}
?>
Operators PHP operators
Each operator takes a different number of operands:
• Unary operators, such as incrementing ($a++) or negation (-$a), which take a single operand.
• Binary operators, which represent the bulk of PHP operators, including addition, subtraction, multiplication, and division.
• One ternary operator, which takes the form ? x : y. It’s a terse, single-line if statement that chooses between two expressions, depending on the result of a third one.
Relational Operators Relational operators test two operands and return a Boolean result of either TRUE or FALSE. There are three types of relational operators: equality, comparison, and logical.
Equality
A ssigning a value and testing for equality
<?php
$month = &quot;March&quot;;
if ($month == &quot;March&quot;) echo &quot;It's springtime&quot;;
?>
Any strings composed entirely of numbers will be converted to numbers whenever compared with a number. The equality and identity operators <?php $a = &quot;1000&quot;; $b = &quot;+1000&quot;; if ($a == $b) echo &quot;1&quot;; if ($a === $b) echo &quot;2&quot;; ?> if you run the example, you will see that it outputs the number 1, which means that the first if statement evaluated to TRUE. This is because both strings were first converted to numbers, and 1000 is the same numerical value as +1000.
In contrast, the second if statement uses the identity operator—three equals signs in a row which prevents PHP from automatically converting types. $a and $b are there fore compared as strings and are now found to be different, so nothing is output.
The inequality and not identical operators
<?php
$a = &quot;1000&quot;;
$b = &quot;+1000&quot;;
if ($a != $b) echo &quot;1&quot;;
if ($a !== $b) echo &quot;2&quot;;
?>
The first if statement does not output the number 1, because the code is asking whether $a and $b are not equal to each other numerically.Instead, it outputs the number 2, because the second if statement is asking whether $a and $b are not identical to each other in their present operand types, and the answer is TRUE; they are not the same.
Comparison operators Using comparison operators, you can test for more than just equality and inequality. The four comparison operators
<?php
$a = 2; $b = 3;
if ($a > $b) echo &quot;$a is greater than $b<br />&quot;;
if ($a < $b) echo &quot;$a is less than $b<br />&quot;;
if ($a >= $b) echo &quot;$a is greater than or equal to $b<br />&quot;;
if ($a <= $b) echo &quot;$a is less than or equal to $b<br />&quot;;
?>
Try this example yourself, altering the values of $a and $b, to see the results. Try setting them to the same value and see what happens.
Logical operators Logical operators produce true-or-false results, and therefore are also known as Boolean operators.the operators can be lower- or uppercase. The logical operators in use
<?php
$a = 1; $b = 0;
echo ($a AND $b) . &quot;<br />&quot;;
echo ($a or $b) . &quot;<br />&quot;;
echo ($a XOR $b) . &quot;<br />&quot;;
echo !$a . &quot;<br />&quot;;
?>
When coding, remember to bear in mind that AND and OR have lower precedence than the other versions of the operators, && and ||. In complex expressions, it may be safer to use && and || for this reason.
Conditionals
The if Statement One way of thinking about program flow is to imagine it as a single-lane highway that you are driving along. It’s pretty much a straight line, but now and then you encounter various signs telling you where to go.
An if statement with curly braces
<?php
if ($bank_balance < 100)
{
$money += 1000;
$bank_balance += $money;
}

Php Learning show

  • 1.
    PHP Basics GnuGroupIndia ILG-Insight GNU/Linux Group Prepared By:Jagjit Phull
  • 2.
    Flow in theWeb.....
  • 3.
  • 4.
    Calling the PHPParser Invoking PHP Method 1 <?php echo &quot;Hello world&quot; ; ?> Method 2 <? echo &quot;Hello world&quot;; ?>
  • 5.
    The Structure ofPHP Using Comments There are two ways in which you can add comments to your PHP code. The first turns a single line into a comment by preceding it with a pair of forward slashes, like this: // This is a comment This version of the comment feature is a great way to temporarily remove a line of code from a program that is giving you errors. You can also use this type of comment directly after a line of code to describe its action, like this: $x += 10; // Increment $x by 10 When you need multiple-line comments <?php /* This is a section of multiline comments which will not be interpreted */ ?>
  • 6.
  • 7.
    PHP commands endwith a semicolon, like this:
  • 8.
  • 9.
    The $ symbol,you must place a $ in front of all variables. Three different types of variable assignment
  • 10.
  • 11.
  • 12.
  • 13.
    $myarray =array(&quot;One&quot;, &quot;Two&quot;, &quot;Three&quot;);
  • 14.
  • 15.
    Variables Think ofvariables as matchboxes containing items.
  • 16.
  • 17.
    Imagine you havea matchbox on which you have written the word username. You then write Fred Smith on a piece of paper and place it into the box.The same process as assigning a string value to a variable, like this:
  • 18.
  • 19.
    The quotation marksindicate that “Fred Smith” is a string of characters.
  • 20.
    When you wantto see what’s in the box, you open it, take the piece of paper out, and read it. In PHP, doing so looks like this:
  • 21.
    echo $username;
  • 22.
    e.g <?php // test1.php $username = &quot;Fred Smith&quot;; echo $username; echo &quot;<br />&quot;; $current_user = $username; echo $current_user; ?> Call it up by entering the URL of your web development directory and the filename test1.php into the address bar of your browser.
  • 23.
  • 24.
  • 25.
    $count = 17.5;Variables don’t contain just strings—they can contain numbers, too. Using the matchbox analogy, to store the number 17 in the variable $count, the equivalent would be placing, say, 17 beads in a matchbox on which you have written the word count:
  • 26.
    You could alsouse a floating-point number (containing a decimal point); the syntax is the same:
  • 27.
    Arrays $team =array('Bill', 'Joe', 'Mike', 'Chris', 'Jim'); You can think of them as several matchboxes glued together.
  • 28.
    let’s say wewant to store the player names for a five-person soccer team in an array called $team. To do this, we could glue five matchboxes side by side and write down the names of all the players on separate pieces of paper, placing one in each matchbox.
  • 29.
    Across the wholetop of the matchbox assembly we would write the word team.
  • 30.
    If we thenwanted to know who player 4 is, we could use this command:
  • 31.
    echo $team[3]; //Displays the name Chris
  • 32.
    Two Dimensional ArraysA multidimensional array simulated with matchboxes.
  • 33.
    It’s easy tounderstand if you grasp the basic array syntax. There are three array() constructs nested inside the outer array() construct.
  • 34.
    To then returnthe third element in the second row of this array, you would use the following PHP command, which will display an “x”:
  • 35.
    echo $oxo[1][2]; Asan example of a two-dimensional array, let’s say we want to keep track of a game of tic-tac-toe, which requires a data structure of nine cells arranged in a 3×3 square.
  • 36.
    To represent thiswith matchboxes, imagine nine of them glued to each other in a matrix of three rows by three columns.
  • 37.
    You can nowplace a piece of paper with either an “x” or an “o” in the correct matchbox for each move played.
  • 38.
  • 39.
  • 40.
  • 41.
  • 42.
  • 43.
  • 44.
    Variable naming rulesWhen creating PHP variables, you must follow these four rules: • Variable names must start with a letter of the alphabet or the _ (underscore) character. • Variable names can contain only the characters: a-z, A-Z, 0-9, and _ (underscore). • Variable names may not contain spaces. If a variable must comprise more than one word it should be separated with the _ (underscore) character. (e.g., $user_name). • Variable names are case-sensitive. The variable $High_Score is not the same as the variable $high_score.
  • 45.
  • 46.
  • 47.
  • 48.
  • 49.
    Variable Assignment Thesyntax to assign a value to a variable is always variable = value Or To reassign the value to another variable, it is other
  • 50.
  • 51.
  • 52.
    Adding or subtracting1 is a common operation that PHP provides special operators for it. You can use one of the following in place of the += and -= operators:
  • 53.
  • 54.
  • 55.
    String concatenation Stringconcatenation uses the period (.) to append one string of characters to another.
  • 56.
    echo &quot;You have&quot; . $msgs . &quot; messages.&quot;;
  • 57.
    Just as youcan add a value to a numeric variable with the += operator, you can append one string to another using .= like this:
  • 58.
  • 59.
    In this case,if $bulletin contains a news bulletin and $newsflash has a news flash, the command appends the news flash to the news bulletin so that $bulletin now comprises both strings of text.
  • 60.
    String types PHPsupports two types of strings that are denoted by the type of quotation mark that you use. If you wish to assign a literal string, preserving the exact contents, you should use the single quotation mark (apostrophe) like this: $info = 'Preface variables with a $ like this: $variable'; In this case, every character within the single-quoted string is assigned to $info. If you had used double quotes, PHP would have attempted to evaluate $variable as a variable. When you want to include the value of a variable inside a string,you do so by using double-quoted strings: echo &quot;There have been $count presidents of the US&quot;;
  • 61.
    Escaping characters Sometimesa string needs to contain characters with special meanings that might beinterpreted incorrectly. For example, the following line of code will not work, because the second quotation mark encountered in the word sister’s will tell the PHP parser that the string end has been reached. Consequently, the rest of the line will be rejected as an error:
  • 62.
    $text = 'Mysister's car is a Ford'; // Erroneous syntax
  • 63.
    To correct this,you can add a backslash directly before the offending quotation mark to tell PHP to treat the character literally and not to interpret it:
  • 64.
    $text = 'Mysister\'s car is a Ford';
  • 65.
    Variable Typing PHPis a very loosely typed language. This means that variables do not have to be declared before they are used, and that PHP always converts variables to the type required by their context when they are accessed.
  • 66.
    For example, youcan create a multiple-digit number and extract the nth digit from it simply by assuming it to be a string. In the following snippet of code, the numbers 12345 and 67890 are multiplied together, returning a result of 838102050, which is then placed in the variable $number,
  • 67.
    Automatic conversion froma number to a string
  • 68.
  • 69.
  • 70.
  • 71.
  • 72.
    At the pointof the assignment, $number is a numeric variable. But on the second line,a call is placed to the PHP function substr, which asks for one character to be returned from $number, starting at the fourth position (remembering that PHP offsets start from zero). To do this, PHP turns $number into a nine-character string, so that substr can access it and return the character, which in this case is 1.
  • 73.
    Automatically converting astring to a number
  • 74.
  • 75.
  • 76.
  • 77.
    echo $pi *($radius * $radius);
  • 78.
  • 79.
    Constants Constants aresimilar to variables, holding information to be accessed later, except that they are what they sound like—constant. In other words, once you have defined one, its value is set for the remainder of the program and cannot be altered. e.g to hold the location of your server root (the folder with the main files of your website). You would define such a constant like this:
  • 80.
  • 81.
    Then, to readthe contents of the variable you just refer to it like a regular variable (but it isn’t preceded by a dollar sign):
  • 82.
  • 83.
    Now, whenever youneed to run your PHP code on a different server with a different folder configuration, you have only a single line of code to change.
  • 84.
    NOTE: The maintwo things you have to remember about constants are that they must not be prefaced with a $ sign (as with regular variables), and that you can define them only using the define function.
  • 85.
    Predefined constants PHP'smagic constants:One handy use of these variables is for debugging purposes, when you need to insert a line of code to see whether the program flow reaches it:
  • 86.
    echo &quot;This isline &quot; . __LINE__ . &quot; of file &quot; . __FILE__;
  • 87.
    This causes thecurrent program line in the current file (including the path) being executed to be output to the web browser.
  • 88.
    The Difference Betweenthe echo and print Commands print is an actual function that takes a single parameter.
  • 89.
    Print can beused for complex expressions. an example to output whether the value of a variable is TRUE or FALSE using print, something you could not perform in the same manner with echo, because it would display a “Parse error” message:
  • 90.
    $b ? print&quot;TRUE&quot; : print &quot;FALSE&quot;;
  • 91.
    The question markis simply a way of interrogating whether variable $b is true or false. Whichever command is on the left of the following colon is executed if $b is true, whereas the command to the right is executed if $b is false. echo is a PHP language construct.
  • 92.
    The echo commandwill be a be faster than print in general text output, because, not being a function, it doesn’t set a return value.
  • 93.
    As it isn’ta function, echo cannot be used as part of a more complex expression.
  • 94.
    Functions Functions areused to separate out sections of code that perform a particular task. For example, maybe you often need to look up a date and return it in a certain format. To create a function
  • 95.
    A simple functiondeclaration
  • 96.
  • 97.
  • 98.
  • 99.
    return date(&quot;l FjS Y&quot;, $timestamp);
  • 100.
  • 101.
  • 102.
    This function takesa Unix timestamp (an integer number representing a date and time based on the number of seconds since 00:00 AM on January 1, 1970) as its input and then calls the PHP date function with the correct format string to return a date in the format Wednesday August 1st 2012.
  • 103.
    To output today’sdate using this function, place the following call in your code:
  • 104.
  • 105.
    Variable Scope Ifyou have a very long program, it’s quite possible that you could start to run out of good variable names, but with PHP you can decide the scope of a variable. In other words, you can, for example, tell it that you want the variable $temp to be used only inside a particular function and to forget it was ever used when the function returns.
  • 106.
    Local variable s: Local variables are variables that are created within and can be accessed only by a function. They are generally temporary variables that are used to store partially processed results prior to the function’s return.
  • 107.
  • 108.
  • 109.
  • 110.
    $temp = date(&quot;lF jS Y&quot;, $timestamp);
  • 111.
    return &quot;The dateis $temp&quot;;
  • 112.
  • 113.
  • 114.
    The value returnedby the date function to the temporary variable $temp, which is then inserted into the string returned by the function.
  • 115.
    Global variables :Thereare cases when you need a variable to have global scope, because you want all your code to be able to access it. Also, some data may be large and complex, and you don’t want to keep passing it as arguments to functions.
  • 116.
    To declare avariable as having global scope, use the keyword global. Let’s assume that you have a way of logging your users into your website and want all your code to know whether it is interacting with a logged-in user or a guest. One way to do this is to create a global variable such as $is_logged_in:
  • 117.
  • 118.
    Now your loginfunction simply has to set that variable to 1 upon success of a login attempt, or 0 upon its failure. Because the scope of the variable is global, every line of code in your program can access it.
  • 119.
    Static Variables Whatif you have a local variable inside a function that you don’t want any other parts of your code to have access to, but that you would also like to keep its value for the next time the function is called?
  • 120.
    The solution isto declare a static variable,
  • 121.
    A function usinga static variable
  • 122.
  • 123.
  • 124.
  • 125.
  • 126.
  • 127.
  • 128.
  • 129.
  • 130.
    Here the veryfirst line of function test creates a static variable called $count and initializes it to a value of zero. The next line outputs the variable’s value; the final one increments it.
  • 131.
    Allowed and disallowedstatic variable declarations
  • 132.
  • 133.
    static $int =0; // Allowed
  • 134.
    static $int =1+2; // Disallowed (will produce a Parse error)
  • 135.
    static $int =sqrt(144); // Disallowed
  • 136.
  • 137.
    Superglobal variables Startingwith PHP 4.1.0, several predefined variables are available. These are known as superglobal variables, which means that they are provided by the PHP environment but are global within the program, accessible absolutely everywhere. These superglobals contain lots of useful information about the currently running program and its environment They are structured as associative arrays.
  • 138.
    Superglobals and securityA word of caution is in order before you start using superglobal variables, because they are often used by hackers trying to find exploits to break in to your website. What they do is load up $_POST, $_GET, or other superglobals with malicious code, such as Unix or MySQL commands that can damage or display sensitive data if you naïvely access them.
  • 139.
    Therefore, you shouldalways sanitize superglobals before using them. One way to do this is via the PHP htmlentities function. It converts all characters into HTML entities. For example, less-than and greater-than characters (< and >) are transformed into the strings &lt; and &gt; so that they are rendered harmless, as are all quotes and backslashes, and so on. A much better way to access $_SERVER (and other superglobals) is:
  • 140.
  • 141.
  • 142.
    Expressions An expressionis a combination of values,variables, operators, and functions that results in a value. It’s familiar to elementary-school algebra:
  • 143.
  • 144.
    which in PHPwould be:
  • 145.
    $y = 3* (abs(2*$x) + 4);
  • 146.
  • 147.
  • 148.
    echo &quot;a: [&quot;. (20 > 9) . &quot;]<br />&quot;;
  • 149.
    echo &quot;b: [&quot;. (5 == 6) . &quot;]<br />&quot;;
  • 150.
    echo &quot;c: [&quot;. (1 == 0) . &quot;]<br />&quot;;
  • 151.
    echo &quot;d: [&quot;. (1 == 1) . &quot;]<br />&quot;;
  • 152.
  • 153.
    Literals and VariablesThe simplest form of an expression is a literal, which simply means something that evaluates to itself, such as the number 73 or the string “Hello”. An expression could also simply be a variable, which evaluates to the value that has been assigned to it. They are both types of expressions, because they return a value. Five types of literals
  • 154.
  • 155.
  • 156.
  • 157.
    echo &quot;a: &quot;. 73 . &quot;<br />&quot;; // Numeric literal
  • 158.
    echo &quot;b: &quot;. &quot;Hello&quot; . &quot;<br />&quot;; // String literal
  • 159.
    echo &quot;c: &quot;. FALSE . &quot;<br />&quot;; // Constant literal
  • 160.
    echo &quot;d: &quot;. $myname . &quot;<br />&quot;; // Variable string literal
  • 161.
    echo &quot;e: &quot;. $myage . &quot;<br />&quot;; // Variable numeric literal
  • 162.
  • 163.
    An expression anda statement
  • 164.
  • 165.
    $days_to_new_year = 366- $day_number; // Expression
  • 166.
  • 167.
  • 168.
    echo &quot;Not longnow till new year&quot;; // Statement
  • 169.
  • 170.
  • 171.
  • 172.
    Each operator takesa different number of operands:
  • 173.
    • Unaryoperators, such as incrementing ($a++) or negation (-$a), which take a single operand.
  • 174.
    • Binaryoperators, which represent the bulk of PHP operators, including addition, subtraction, multiplication, and division.
  • 175.
    • Oneternary operator, which takes the form ? x : y. It’s a terse, single-line if statement that chooses between two expressions, depending on the result of a third one.
  • 176.
    Relational Operators Relationaloperators test two operands and return a Boolean result of either TRUE or FALSE. There are three types of relational operators: equality, comparison, and logical.
  • 177.
  • 178.
    A ssigning avalue and testing for equality
  • 179.
  • 180.
  • 181.
    if ($month ==&quot;March&quot;) echo &quot;It's springtime&quot;;
  • 182.
  • 183.
    Any strings composedentirely of numbers will be converted to numbers whenever compared with a number. The equality and identity operators <?php $a = &quot;1000&quot;; $b = &quot;+1000&quot;; if ($a == $b) echo &quot;1&quot;; if ($a === $b) echo &quot;2&quot;; ?> if you run the example, you will see that it outputs the number 1, which means that the first if statement evaluated to TRUE. This is because both strings were first converted to numbers, and 1000 is the same numerical value as +1000.
  • 184.
    In contrast, thesecond if statement uses the identity operator—three equals signs in a row which prevents PHP from automatically converting types. $a and $b are there fore compared as strings and are now found to be different, so nothing is output.
  • 185.
    The inequality andnot identical operators
  • 186.
  • 187.
  • 188.
  • 189.
    if ($a !=$b) echo &quot;1&quot;;
  • 190.
    if ($a !==$b) echo &quot;2&quot;;
  • 191.
  • 192.
    The first ifstatement does not output the number 1, because the code is asking whether $a and $b are not equal to each other numerically.Instead, it outputs the number 2, because the second if statement is asking whether $a and $b are not identical to each other in their present operand types, and the answer is TRUE; they are not the same.
  • 193.
    Comparison operators Usingcomparison operators, you can test for more than just equality and inequality. The four comparison operators
  • 194.
  • 195.
    $a = 2;$b = 3;
  • 196.
    if ($a >$b) echo &quot;$a is greater than $b<br />&quot;;
  • 197.
    if ($a <$b) echo &quot;$a is less than $b<br />&quot;;
  • 198.
    if ($a >=$b) echo &quot;$a is greater than or equal to $b<br />&quot;;
  • 199.
    if ($a <=$b) echo &quot;$a is less than or equal to $b<br />&quot;;
  • 200.
  • 201.
    Try this exampleyourself, altering the values of $a and $b, to see the results. Try setting them to the same value and see what happens.
  • 202.
    Logical operators Logicaloperators produce true-or-false results, and therefore are also known as Boolean operators.the operators can be lower- or uppercase. The logical operators in use
  • 203.
  • 204.
    $a = 1;$b = 0;
  • 205.
    echo ($a AND$b) . &quot;<br />&quot;;
  • 206.
    echo ($a or$b) . &quot;<br />&quot;;
  • 207.
    echo ($a XOR$b) . &quot;<br />&quot;;
  • 208.
    echo !$a . &quot;<br />&quot;;
  • 209.
  • 210.
    When coding, rememberto bear in mind that AND and OR have lower precedence than the other versions of the operators, && and ||. In complex expressions, it may be safer to use && and || for this reason.
  • 211.
  • 212.
    The if StatementOne way of thinking about program flow is to imagine it as a single-lane highway that you are driving along. It’s pretty much a straight line, but now and then you encounter various signs telling you where to go.
  • 213.
    An if statementwith curly braces
  • 214.
  • 215.
  • 216.
  • 217.
  • 218.
  • 219.
  • 220.
  • 221.
    The else StatementSometimes when a conditional is not TRUE, you may not want to continue on to the main program code immediately but might wish to do something else instead. This is where the else statement comes in. With it, you can set up a second detour on your highway
  • 222.
    An if...else statementwith curly braces
  • 223.
  • 224.
  • 225.
  • 226.
  • 227.
  • 228.
  • 229.
  • 230.
  • 231.
  • 232.
  • 233.
  • 234.
  • 235.
    The elseif StatementThere are also times when you want a number of different possibilities to occur, based upon a sequence of conditions. You can achieve this using the elseif statement. An if...elseif...else statement with curly braces
  • 236.
  • 237.
  • 238.
  • 239.
  • 240.
  • 241.
  • 242.
    elseif ($bank_balance >200) Cont... { $savings += 100; $bank_balance -= 100; } else { $savings += 50; $bank_balance -= 50; } ?>
  • 243.
    The switch StatementThe switch statement is useful in cases in which one variable or the result of an expression can have multiple values, which should each trigger a different function.
  • 244.
    Consider a PHP-drivenmenu system that passes a single string to the main menu code according to what the user requests. Let’s say the options are Home, About,News, Login, and Links, and we set the variable $page to one of these, according to the user’s input.
  • 245.
  • 246.
  • 247.
    if ($page== &quot;Home&quot;) echo &quot;You selected Home&quot;;
  • 248.
    elseif ($page ==&quot;About&quot;) echo &quot;You selected About&quot;;
  • 249.
    elseif ($page ==&quot;News&quot;) echo &quot;You selected News&quot;;
  • 250.
    elseif ($page ==&quot;Login&quot;) echo &quot;You selected Login&quot;;
  • 251.
    elseif ($page ==&quot;Links&quot;) echo &quot;You selected Links&quot;;
  • 252.
  • 253.
  • 254.
  • 255.
  • 256.
  • 257.
    case &quot;Home&quot;: echo&quot;You selected Home&quot;;
  • 258.
  • 259.
    case &quot;About&quot;: echo&quot;You selected About&quot;;
  • 260.
    break; case &quot;News&quot;:echo &quot;You selected News&quot;; break; case &quot;Login&quot;: echo &quot;You selected Login&quot;; break; case &quot;Links&quot;: echo &quot;You selected Links&quot;; break; } ?> One thing to note about switch statements is that you do not use curly braces inside case commands. Instead, they commence with a colon and end with the break statement. The entire list of cases in the switch statement is enclosed in a set of curly braces, though
  • 261.
    Breaking out Ifyou wish to break out of the switch statement because a condition has been fulfilled, use the break command. This command tells PHP to break out of the switch and jump to the following statement.
  • 262.
    Default action : A typical requirement in switch statements is to fall back on a default action if none of the case conditions are met. Alternate switch statement syntax <?php switch ($page): case &quot;Home&quot;: echo &quot;You selected Home&quot;; break; case &quot;Links&quot;: echo &quot;You selected Links&quot;; break; endswitch; ?>
  • 263.
    The ? OperatorOne way of avoiding the verbosity of if and else statements is to use the more compact ternary operator, ?, which is unusual in that it takes three operands rather than the more usual two.
  • 264.
    The ? operatoris passed an expression that it must evaluate, along with two statements to execute: one for when the expression evaluates to TRUE, the other for when it is FALSE. Using the ? operator
  • 265.
  • 266.
    echo $fuel <=1 ? &quot;Fill tank now&quot; : &quot;There's enough fuel&quot;;
  • 267.
  • 268.
    In this statement,if there is one gallon or less of fuel (in other words $fuel is set to 1 or less), the string “Fill tank now” is returned to the preceding echo statement. Otherwise, the string “There’s enough fuel” is returned.
  • 269.
    Assigning a ?conditional result to a variable
  • 270.
  • 271.
    $enough = $fuel<= 1 ? FALSE : TRUE;
  • 272.
  • 273.
    Here $enough willbe assigned the value TRUE only when there is more than a gallon of fuel; otherwise, it is assigned the value FALSE.
  • 274.
    Looping One ofthe great things about computers is that they can repeat calculating tasks quickly and tirelessly. Often you may want a program to repeat the same sequence of code again and again until something happens, such as a user inputting a value or the program reaching a natural end. PHP’s various loop structures provide the perfect way to do this. A while loop
  • 275.
  • 276.
  • 277.
  • 278.
  • 279.
  • 280.
  • 281.
  • 282.
  • 283.
    e.g A whileloop to print the multiplication table for 12
  • 284.
  • 285.
  • 286.
  • 287.
  • 288.
    echo &quot;$count times12 is &quot; . $count * 12 . &quot;<br />&quot;;
  • 289.
  • 290.
  • 291.
    ?> Shortened version<?php $count = 0; while (++$count <= 12) echo &quot;$count times 12 is &quot; . $count * 12 . &quot;<br />&quot;; ?>
  • 292.
    do...while Loops A slight variation to the while loop is the do...while loop, used when you want ablock of code to be executed at least once and made conditional only after that.
  • 293.
  • 294.
  • 295.
  • 296.
  • 297.
    echo &quot;$count times12 is &quot; . $count * 12;
  • 298.
  • 299.
  • 300.
    ?> A do...whileloop for printing the times table for 12
  • 301.
  • 302.
  • 303.
  • 304.
    echo &quot;$count times12 is &quot; . $count * 12 . &quot;<br />&quot;;
  • 305.
  • 306.
  • 307.
    for Loops Thefinal kind of loop statement, the for loop, is also the most powerful, as it combines the abilities to set up variables as you enter the loop, test for conditions while iteratingloops, and modify variables after each iteration.
  • 308.
    Each for statementtakes three parameters:
  • 309.
    • Aninitialization expression
  • 310.
    • Acondition expression
  • 311.
    • Amodification expression
  • 312.
    These are separatedby semicolons like this: for (expr1 ; expr2 ; expr3). At the start of the first iteration of the loop, the initialization expression is executed. Outputting the times table for 12 from a for loop
  • 313.
  • 314.
    for ($count =1 ; $count <= 12 ; ++$count)
  • 315.
    echo &quot;$count times12 is &quot; . $count * 12 . &quot;<br />&quot;;
  • 316.
  • 317.
    For loop withcurly braces
  • 318.
  • 319.
    for ($count =1 ; $count <= 12 ; ++$count)
  • 320.
  • 321.
    echo &quot;$count times12 is &quot; . $count * 12;
  • 322.
  • 323.
  • 324.
  • 325.
    when to usefor and while loops The for loop is explicitly designed around a single value that changes on a regular basis. Usually you have a value that increments, as when you are passed a list of user choices and want to process each choice in turn. But you can transform the variable any way you like. When your condition doesn’t depend on a simple, regular change to a variable. For instance, if you want to check for some special input or error and end the loop when it occurs, use a while statement.
  • 326.
    Breaking Out ofa Loop Just as you saw how to break out of a switch statement, you can also break out from a for loop using the same break command. This step can be necessary when, for example, one of your statements returns an error and the loop cannot continue executing safely.
  • 327.
    First line opensthe file text.txt for writing in binary mode, and then returns a pointer to the file in the variable $fp, which is used later to refer to the open file.
  • 328.
    The loop theniterates 100 times (from 0 to 99) writing the string data to the file. After each write, the variable $written is assigned a value by the fwrite function representing the number of characters correctly written. But if there is an error, the fwrite function assigns the value FALSE.
  • 329.
    The behavior of fwrite makes it easy for the code to check the variable $written to see whether it is set to FALSE and, if so, to break out of the loop to the following statement closing the file. Writing a file using a for loop with error trapping
  • 330.
  • 331.
  • 332.
    for ($j =0 ; $j < 100 ; ++$j)
  • 333.
  • 334.
    $written = fwrite($fp,&quot;data&quot;);
  • 335.
    if ($written ==FALSE) break;
  • 336.
  • 337.
  • 338.
  • 339.
    To improve thecode, the line:
  • 340.
    if ($written ==FALSE) break;
  • 341.
    can be simplifiedusing the NOT operator, like this: if (!$written) break ;
  • 342.
    The continue StatementThe continue statement is a little like a break statement, except that it instructs PHP to stop processing the current loop and to move right to its next iteration. So, instead of breaking out of the whole loop, only the current iteration is exited.
  • 343.
    This approach canbe useful in cases where you know there is no point continuing execution within the current loop and you want to save processor cycles, or prevent an error from occurring, by moving right along to the next iteration of the loop. Trapping division-by-zero errors using continue
  • 344.
  • 345.
  • 346.
  • 347.
  • 348.
  • 349.
    if ($j ==0) continue;
  • 350.
    echo (10 /$j) . &quot;<br />&quot;;
  • 351.
  • 352.
  • 353.
    Implicit and ExplicitCasting PHP is a loosely typed language that allows you to declare a variable and its type simply by using it. It also automatically converts values from one type to another whenever required. This is called implicit casting However, there may be times when PHP’s implicit casting is not what you want.
  • 354.
    By default, PHPconverts the output to floating-point so it can give the most precise value.
  • 355.
    But what ifwe had wanted $c to be an integer instead? There are various ways in which this could be achieved; one way is to force the result of $a/$b to be cast to an integer value using the integer cast type (int), like this:
  • 356.
    $c = (int)($a / $b);
  • 357.
    This is calledexplicit casting. This expression returns a floating-point number
  • 358.
  • 359.
  • 360.
  • 361.
    $c = $a/ $b;
  • 362.
  • 363.
  • 364.
  • 365.
  • 366.
    PHP Functions Threestring functions
  • 367.
  • 368.
    echo strrev(&quot; .dlrowolleH&quot;); // Reverse string
  • 369.
  • 370.
  • 371.
  • 372.
    Print is apseudofunction, commonly called a construct. The difference is that you can omit the parentheses, as follows:
  • 373.
    print &quot;print doesn'trequire parentheses&quot;;
  • 374.
    You do haveto put parentheses after any other function you call, even if they’re empty (that is, if you’re not passing any argument to the function). The phpinfo function is extremely useful for obtaining informationabout your current PHP installation, but that information could also be very useful to potential hackers. Therefore, never leave a call to this function in any web-ready code.
  • 375.
  • 376.
    Defining a functionThe general syntax for a function is: function function_name([parameter [, ...]]) { // Statements } The first line of the syntax indicates that:
  • 377.
    • Adefinition starts with the word function.
  • 378.
    • Aname follows, which must start with a letter or underscore, followed by any number of letters, numbers, or underscores.
  • 379.
    • Theparentheses are required.
  • 380.
    • Oneor more parameters, separated by commas, are optional.
  • 381.
    Function names arecase-insensitive, so all of the following strings can refer to the print function: PRINT, Print, and PrInT. Returning a Value
  • 382.
    Look at asimple function to convert a person’s full name to lowercase and then capitalize the first letter of each name.
  • 383.
    Cleaning up afull name
  • 384.
  • 385.
  • 386.
  • 387.
  • 388.
  • 389.
  • 390.
  • 391.
    return $n1 .&quot; &quot; . $n2 . &quot; &quot; . $n3;
  • 392.
  • 393.
  • 394.
    Returning an ArrayReturning multiple values in an array
  • 395.
  • 396.
    $names = fix_names(&quot;RICHARD&quot;,&quot;m&quot;, &quot;stallMAN”);
  • 397.
    echo $names[0] .&quot; &quot; . $names[1] . &quot; &quot; . $names[2];
  • 398.
  • 399.
  • 400.
  • 401.
  • 402.
  • 403.
  • 404.
  • 405.
  • 406.
    Passing by ReferenceIn PHP, the & symbol, when prefaced to a variable, tells the parser to pass a reference to the variable’s value, not the value itself. matchbox metaphor
  • 407.
    Imagine that, insteadof taking a piece of paper out of a matchbox, reading it, copying it to another piece of paper, putting the original back, and passing the copy to a function -tedious isn't it,
  • 408.
    Rather,you simply attacha piece of thread to the original piece of paper and pass oneend of it to the function.
  • 409.
    Now the functioncan follow the thread to find the data to be accessed. This avoids all the overhead of creating a copy of the variable just for the function’s use. What’s more,the function can now modify the variable’s value.
  • 410.
    Returning values froma function by reference Returning values from a function by reference
  • 411.
  • 412.
  • 413.
  • 414.
  • 415.
    echo $a1 .&quot; &quot; . $a2 . &quot; &quot; . $a3 . &quot;<br />&quot;;
  • 416.
  • 417.
    echo $a1 .&quot; &quot; . $a2 . &quot; &quot; . $a3;
  • 418.
  • 419.
  • 420.
  • 421.
  • 422.
  • 423.
  • 424.
    ?> Rather thanpassing strings directly to the function, you first assign them to variables and print them out to see their “before” values. Then you call the function as before, but put a & symbol in front of each parameter, which tells PHP to pass the variables’ references only.
  • 425.
    Now the variables$n1, $n2, and $n3 are attached to “threads” that lead to the values of $a1, $a2, and $a3. In other words, there is one group of values, but two sets of variable names are allowed to access them.
  • 426.
    Returning Global VariablesYou can also give a function access to an externally created variable by declaring it a global variable from within the function. The global keyword followed by the variable name gives every part of your code full access to it.
  • 427.
    Now you don’thave to pass parameters to the function, and it doesn’t have to accept them. Once declared, these variables remain global and available to the rest of your program, including its functions Returning values in global variables <?php $a1 = &quot;RICHARD&quot;; $a2 = &quot;m&quot;; $a3 = &quot;stallMAN&quot;; echo $a1 . &quot; &quot; . $a2 . &quot; &quot; . $a3 . &quot;<br />&quot;; fix_names(); echo $a1 . &quot; &quot; . $a2 . &quot; &quot; . $a3; function fix_names() { global $a1; $a1 = ucfirst(strtolower($a1)); global $a2; $a2 = ucfirst(strtolower($a2)); global $a3; $a3 = ucfirst(strtolower($a3)); } ?>
  • 428.
    Including and RequiringFiles As you progress in your use of PHP programming, you are likely to start building a library of functions that you think you will need again. You’ll also probably start using libraries created by other programmers.
  • 429.
    There’s no needto copy and paste these functions into your code. You can save them in separate files and use commands to pull them in. There are two types of commands to perform this action: include and require.
  • 430.
    Using include_once : Each time you issue the include directive, it includes the requested file again, even if you’ve already inserted it. For instance, suppose that library.php contains a lot of useful functions, so you include it in your file, but also include another library that includes library.php. Through nesting, you’ve inadvertently included library.php twice. This willproduce error messages, because you’re trying to define the same constant or function multiple times. So you should use include_once instead include Statement : Using include, you can tell PHP to fetch a particular file and load all its contents. It’s as if you pasted the included file into the current file at the insertion point.
  • 431.
  • 432.
  • 433.
  • 434.
    // Your codegoes here
  • 435.
  • 436.
  • 437.
    Including a PHPfile only once
  • 438.
  • 439.
  • 440.
    // Your codegoes here
  • 441.
  • 442.
    Using require andrequire_once When it is absolutely essential to include a file, require it. For the same reasons I gave for using include_once, I recommend that you generally stick with require_once whenever you need to require a file Requiring a PHP file only once <?php require_once &quot;library.php&quot;; // Your code goes here ?>
  • 443.
  • 444.
    Basic Access We’vealready looked at arrays as if they were clusters of matchboxes glued together. Another way to think of an array is like a string of beads, with the beads representing variables that can be numeric, string, or even other arrays . They are like bead strings, because each element has its own location. Some arrays are referenced by numeric indexes; others allow alphanumeric identifiers. Built-in functions let you sort them, add or remove sections, and walk through them to handle each item through a special kind of loop. And by placing one or more arrays inside another, you can create arrays of two, three, or any number of dimensions.
  • 445.
    Numerically Indexed ArraysAdding items to an array <?php $paper[] = &quot;Copier&quot;; $paper[] = &quot;Inkjet&quot;; $paper[] = &quot;Laser&quot;; $paper[] = &quot;Photo&quot;; print_r($paper); ?> In this example, each time you assign a value to the array $paper, the first empty location within that array is used to store the value and a pointer internal to PHP is incremented to point to the next free location, ready for future insertions. The print_r function (which prints out the contents of a variable, array, or object) is used to verify that the array has been correctly populated. It prints out the following:
  • 446.
  • 447.
  • 448.
  • 449.
  • 450.
  • 451.
  • 452.
  • 453.
    Adding items toan array using explicit locations
  • 454.
  • 455.
  • 456.
  • 457.
  • 458.
  • 459.
  • 460.
    ?> Adding itemsto an array and retrieving them <?php $paper[] = &quot;Copier&quot;; $paper[] = &quot;Inkjet&quot;; $paper[] = &quot;Laser&quot;; $paper[] = &quot;Photo&quot;; for ($j = 0 ; $j < 4 ; ++$j) echo &quot;$j: $paper[$j]<br>&quot;; ?>
  • 461.
    Associative Arrays Associativearrays can reference the items in an array by name rather than by number.
  • 462.
    In place ofa number (which doesn’t convey any useful information, aside from the position of the item in the array), each item now has a unique name that you can use to reference it elsewhere, as with the echo statement—which simply prints out Laser Printer. The names (copier, inkjet, and so on) are called indexes or keys and the itemsassigned to them (such as “Laser Printer”) are called values. Adding items to an associative array and retrieving them
  • 463.
  • 464.
    $paper['copier'] = &quot;Copier& Multipurpose&quot;;
  • 465.
  • 466.
    $paper['laser'] =&quot;Laser Printer&quot;;
  • 467.
    $paper['photo'] =&quot;Photographic Paper&quot;;
  • 468.
  • 469.
  • 470.
    Assignment Using thearray Keyword Adding items to an array using the array keyword
  • 471.
  • 472.
    $p1 = array(&quot;Copier&quot;,&quot;Inkjet&quot;, &quot;Laser&quot;, &quot;Photo&quot;);
  • 473.
    echo &quot;p1 element:&quot; . $p1[2] . &quot;<br>&quot;;
  • 474.
    $p2 = array('copier' => &quot;Copier & Multipurpose&quot;,
  • 475.
    'inkjet' =>&quot;Inkjet Printer&quot;,
  • 476.
    'laser' =>&quot;Laser Printer&quot;,
  • 477.
    'photo' =>&quot;Photographic Paper&quot;);
  • 478.
    echo &quot;p2 element:&quot; . $p2['inkjet'] . &quot;<br>&quot;;
  • 479.
    ?> The firsthalf of this snippet assigns the old, shortened product descriptions to the array $p1. There are four items, so they will occupy slots 0 through 3. Therefore the echo statement prints out the following:
  • 480.
  • 481.
    The second halfassigns associative identifiers and accompanying longer product descriptions to the array $p2 using the format index => value. The use of => is similar to the regular = assignment operator, except that you are assigning a value to an index and not to a variable. The index is then inextricably linked with that value, unless it is reassigned a new value. The echo command therefore prints out:
  • 482.
  • 483.
    The foreach...as LoopUsing it, you can step through all the items in an array, one at a time, and do something with them.
  • 484.
    The process startswith the first item and ends with the last one, so you don’t even have to know how many items there are in an array.
  • 485.
    When PHP encountersa foreach statement, it takes the first item of the array and placesit in the variable following the as keyword, and each time control flow returns to the foreach, the next array element is placed in the as keyword. In this case, the variable $item is set to each of the four values in turn in the array $paper. Once all values have been used, execution of the loop ends. Walking through a numeric array using foreach...as
  • 486.
  • 487.
    $paper = array(&quot;Copier&quot;,&quot;Inkjet&quot;, &quot;Laser&quot;, &quot;Photo&quot;);
  • 488.
  • 489.
  • 490.
  • 491.
  • 492.
  • 493.
  • 494.
  • 495.
    Associative Array Walkingthrough an associative array using foreach...as
  • 496.
  • 497.
    $paper = array('copier'=> &quot;Copier & Multipurpose&quot;,
  • 498.
  • 499.
    'laser' =>&quot;Laser Printer&quot;,
  • 500.
    'photo' =>&quot;Photographic Paper&quot;);
  • 501.
    foreach ($paper as$item => $description)
  • 502.
  • 503.
    ?> Each itemof the array $paper is fed into the key and value pair of variables $item and $description, from where they are printed out.
  • 504.
    Walking through anassociative array using each and list
  • 505.
  • 506.
    $paper = array('copier'=> &quot;Copier & Multipurpose&quot;,
  • 507.
  • 508.
    'laser' =>&quot;Laser Printer&quot;,
  • 509.
    'photo' =>&quot;Photographic Paper&quot;);
  • 510.
  • 511.
  • 512.
    ?> In thisexample, a while loop is set up and will continue looping until the each function returns a value of FALSE. The each function acts like foreach: it returns an array containing a key and value pair from the array $paper and then moves its built-in pointer to the next pair in that array. When there are no more pairs to return, each returns FALSE.
  • 513.
    The list functiontakes an array as its argument (in this case the key and value pair returned by function each) and then assigns the values of the array to the variables listed within parentheses.
  • 514.
  • 515.
  • 516.
    list($a, $b) =array('Alice', 'Bob');
  • 517.
  • 518.
  • 519.
    Multidimensional Arrays Creatinga multidimensional associative array <?php $products = array( 'paper' => array( 'copier' => &quot;Copier & Multipurpose&quot;, 'inkjet' => &quot;Inkjet Printer&quot;, 'laser' => &quot;Laser Printer&quot;, 'photo' => &quot;Photographic Paper&quot;), 'pens' => array( 'ball' => &quot;Ball Point&quot;, 'hilite' => &quot;Highlighters&quot;, 'marker' => &quot;Markers&quot;), 'misc' => array( 'tape' => &quot;Sticky Tape&quot;, 'glue' => &quot;Adhesives&quot;, 'clips' => &quot;Paperclips&quot;) ); echo &quot;<pre>&quot;; foreach ($products as $section => $items) foreach ($items as $key => $value) echo &quot;$section:\t$key\t($value)<br>&quot;; echo &quot;</pre>&quot;; ?>
  • 520.
  • 521.
  • 522.
  • 523.
    array('r', 'n', 'b', 'k', 'q', 'b', 'n', 'r'),
  • 524.
    array('p', 'p', 'p', 'p', 'p', 'p', 'p', 'p'),
  • 525.
    array(' ', '', ' ', ' ', ' ', ' ', ' ', ' '),
  • 526.
    array(' ', '', ' ', ' ', ' ', ' ', ' ', ' '),
  • 527.
    array(' ', '', ' ', ' ', ' ', ' ', ' ', ' '),
  • 528.
    array(' ', '', ' ', ' ', ' ', ' ', ' ', ' '),
  • 529.
    array(' ', '', ' ', ' ', ' ', ' ', ' ', ' '),
  • 530.
    array(' ', '', ' ', ' ', ' ', ' ', ' ', ' '),
  • 531.
    array('P', 'P', 'P', 'P', 'P', 'P', 'P', 'P'),
  • 532.
    array('R', 'N', 'B', 'K', 'Q', 'B', 'N', 'R')); echo &quot;<pre>&quot;; foreach ($chessboard as $row) { foreach ($row as $piece) echo &quot;$piece &quot;; echo &quot;<br />&quot;; } echo &quot;</pre>&quot;; ?>
  • 533.
    Using Array Functionsis_array() Arrays and variables share the same namespace. This means that you cannot have a string variable called $fred and an array also called $fred. If you’re in doubt and your code needs to check whether a variable is an array, you can use the is_array function like this:
  • 534.
    echo (is_array($fred)) ?&quot;Is an array&quot; : &quot;Is not an array&quot;;
  • 535.
    count() Although theeach function and foreach...as loop structure are excellent ways to walk through an array’s contents, sometimes you need to know exactly how many elements there are in your array, particularly if you will be referencing them directly. To count all the elements in the top level of an array, use a command such as the following:
  • 536.
  • 537.
    Should you wishto know how many elements there are altogether in a multidimensional array, you can use a statement such as:
  • 538.
  • 539.
    The second parameteris optional and sets the mode to use. It should be either a 0 to limit counting to only the top level, or 1 to force recursive counting of all subarray elements, too.
  • 540.
    sort() Sorting isso common that PHP provides a built-in function. In its simplest form, you would use it like this:
  • 541.
  • 542.
    Unlike some otherfunctions, sort will act directly on the supplied array rather than returning a new array of sorted elements. Instead it returns TRUE on success and FALSE on error and also supports a few flags, but the main two that you might wish to use force sorting to be made either numerically or as strings, like this:
  • 543.
  • 544.
  • 545.
    You can alsosort an array in reverse order using the rsort function, like this:
  • 546.
  • 547.
  • 548.
    shuffle() There maybe times when you need the elements of an array to be put in random order,such as when creating a game of playing cards:
  • 549.
  • 550.
    Like sort, shuffleacts directly on the supplied array and returns TRUE on success or FALSE on error.
  • 551.
  • 552.
    Exploding a stringdelimited with *** into an array
  • 553.
  • 554.
    $temp = explode('***',&quot;A***sentence***with***asterisks&quot;);
  • 555.
  • 556.
    ?> This isa very useful function with which you can take a string containing several items separated by a single character (or string of characters) and then place each of these items into an array.
  • 557.
    Exploding a stringinto an array using spaces
  • 558.
  • 559.
    $temp = explode('', &quot;This is a sentence with seven words&quot;);
  • 560.
  • 561.
  • 562.
    Practical PHP printf,controls the format of the output by letting you put special formatting characters in a string.For each formatting character, printf expects you to pass an argument that it will display using that format. For instance, the following example uses the %d conversion specifier to display the value 3 in decimal:
  • 563.
    printf(&quot;There are %ditems in your basket&quot;, 3); Printf conversion specifiers
  • 564.
    Precision Setting :set the precision of the displayed result. <?php echo &quot;<pre>&quot;; // Enables viewing of the spaces // Pad to 15 spaces printf(&quot;The result is $%15f\n&quot;, 123.42 / 12); // Pad to 15 spaces, fill with zeros printf(&quot;The result is $%015f\n&quot;, 123.42 / 12); // Pad to 15 spaces, 2 decimal places precision printf(&quot;The result is $%15.2f\n&quot;, 123.42 / 12); // Pad to 15 spaces, 2 decimal places precision, fill with zeros printf(&quot;The result is $%015.2f\n&quot;, 123.42 / 12); // Pad to 15 spaces, 2 decimal places precision, fill with # symbol printf(&quot;The result is $%'#15.2f\n&quot;, 123.42 / 12); ?>
  • 565.
    Using sprintf :Often you don’t want to output the result of a conversion but need to use it elsewhere in your code. This is where the sprintf function comes in. With it, you can send the output to another variable rather than to the browser. $hexstring = sprintf(&quot;%X%X%X&quot;, 65, 127, 245);
  • 566.
    $out = sprintf(&quot;Theresult is: $%.2f&quot;, 123.42 / 12);
  • 567.
  • 568.
    Date and TimeFunctions To keep track of the date and time, PHP uses standard Unix timestamps, which are simply the number of seconds since the start of January 1, 1970. To determine the current timestamp, you can use the time function:
  • 569.
  • 570.
    Because the valueis stored as seconds, to obtain the timestamp for this time next week, you would use the following, which adds 7 days × 24 hours × 60 minutes × 60 seconds to the returned value:
  • 571.
    echo time() +7 * 24 * 60 * 60; To display the date, use the date function, which supports a plethora of formatting options, enabling you to display the date any way you could wish. The format is as follows:
  • 572.
  • 573.
    Using checkdate You’veseen how to display a valid date in a variety of formats. But how can you check whether a user has submitted a valid date to your program? The answer is to pass the month, day and year to the checkdate function, which returns a value of TRUE if the date is valid, or FALSE if it is not. Checking for the validity of a date
  • 574.
  • 575.
    $month = 9; // September (only has 30 days)
  • 576.
    $day =31; // 31st
  • 577.
    $year = 2012; // 2012
  • 578.
    if (checkdate($month, $day,$year)) echo &quot;Date is valid&quot;;
  • 579.
    else echo &quot;Dateis invalid&quot;;
  • 580.
  • 581.
    File Handling CheckingWhether a File Exists ?
  • 582.
    To determine whethera file already exists, you can use the file_exists function, which returns either TRUE or FALSE, and is used like this:
  • 583.
  • 584.
    When you runthis in a browser, all being well, you will receive the message “File ‘testfile.txt’ written successfully”. If you receive an error message, your hard disk maybe full or, more likely, you may not have permission to create or write to the file, in which case you should modify the attributes of the destination folder according to your operating system. Otherwise, the file testfile.txt should now be residing in the same folder in which you saved the testfile.php program. Creating a File
  • 585.
    <?php //testfile.php
  • 586.
    $fh = fopen(&quot;testfile.txt&quot;,'w') or die(&quot;Failed to create file&quot;);
  • 587.
  • 588.
  • 589.
  • 590.
  • 591.
  • 592.
    fwrite($fh, $text) ordie(&quot;Could not write to file&quot;);
  • 593.
  • 594.
    echo &quot;File 'testfile.txt'written successfully&quot;;
  • 595.
  • 596.
  • 597.
    Every open filerequires a file resource so that PHP can access and manage it. Thereafter, each file handling function that accesses the opened file, such as fwrite or fclose, must be passed $fh as a parameter to identify the file being accessed. Don’t worry about the content of the $fh variable; it’s a number PHP uses to refer to internal information about the file—you just pass the variable to other functions.
  • 598.
    Upon failure, FALSEwill be returned by fopen.it calls the die function to end the program and gives the user an error message.
  • 599.
    Note : Thesecond parameter to the fopen call. It is simply the character w, which tells the function to open the file for writing. The function creates the file if it doesn’t already exist. Be careful when playing around with these functions: if the file already exists, the w mode parameter causes the fopen call to delete the old contents (even if you don’t write anything new!).
  • 600.
    Reading from FilesReading a file with fgets
  • 601.
  • 602.
    $fh = fopen(&quot;testfile.txt&quot;,'r') or die(&quot;File does not exist or you lack permission to open it&quot;);
  • 603.
    $line = fgets($fh);
  • 604.
  • 605.
  • 606.
  • 607.
    To read froma text file is to grab a whole line through fgets (think of the final s as standing for “string”),
  • 608.
    Retrieve multiple linesor portions of lines through the fread function Reading a file with fread
  • 609.
  • 610.
    $fh = fopen(&quot;testfile.txt&quot;,'r') or die(&quot;File does not exist or you lack permission to open it&quot;);
  • 611.
    $text = fread($fh, 3);
  • 612.
  • 613.
  • 614.
  • 615.
    Copying Files Alternatesyntax for copying a file
  • 616.
  • 617.
    if (!copy('testfile.txt', 'testfile2.txt'))echo &quot;Could not copy file&quot;;
  • 618.
    else echo &quot;Filesuccessfully copied to 'testfile2.txt'&quot;;
  • 619.
  • 620.
  • 621.
    copy('testfile.txt', 'testfile2.txt') ordie(&quot;Could not copy file&quot;);
  • 622.
    echo &quot;File successfullycopied to 'testfile2.txt'&quot;;
  • 623.
  • 624.
    Moving a FileTo move a file, rename it with the rename function.
  • 625.
    You can usethe rename function on directories, too. To avoid any warning messages, if the original file doesn’t exist, you can call the file_exists function first to check. Moving a file
  • 626.
  • 627.
  • 628.
    echo &quot;Could notrename file&quot;;
  • 629.
    else echo &quot;Filesuccessfully renamed to 'testfile2.new'&quot;;
  • 630.
  • 631.
    Deleting a FileDeleting a file is just a matter of using the unlink function to remove it from the file system Deleting a file
  • 632.
  • 633.
    if (!unlink('testfile2.new')) echo&quot;Could not delete file&quot;;
  • 634.
    else echo &quot;File'testfile2.new' successfully deleted&quot;;
  • 635.
  • 636.
    Updating Files Oftenyou will want to add more data to a saved file,You can use one of the append write modes or you can simply open a file for reading and writing with one of the other modes that supports writing, and move the file pointer to the correct place within the file that you wish to write to or read from.
  • 637.
    The file pointeris the position within a file at which the next file access will take place, whether it’s a read or a write. It is not the same as the file handle (as stored in the variable $fh) which contains details about the file being accessed. Updating a file
  • 638.
  • 639.
    $fh = fopen(&quot;testfile.txt&quot;,'r+') or die(&quot;Failed to open file&quot;);
  • 640.
  • 641.
  • 642.
    fwrite($fh, &quot;$text&quot;) ordie(&quot;Could not write to file&quot;);
  • 643.
  • 644.
    echo &quot;File 'testfile.txt'successfully updated&quot;;
  • 645.
  • 646.
    What this programdoes is open testfile.txt for both reading and writing by setting the mode with '+r', which puts the file pointer right at the start. It then uses the fgets function to read in a single line from the file (up to the first line feed). After that, the fseek function is called to move the file pointer right to the file end, at which point the line of text that was extracted from the start of the file (stored in $text) is then appended to file’s end and the file is closed.
  • 647.
    Locking Files forMultiple Accesses Web programs are often called by many users at the same time. If more than one person tries to write to a file simultaneously, it can become corrupted. And if one person writes to it while another is reading from it, the file is all right but the person reading it can get odd results. To handle simultaneous users, it’s necessary to use the file locking flock function. This function queues up all other requests to access a file until your program releases the lock.
  • 648.
    Note:There is atrick to file locking to preserve the best possible response time for your website visitors: perform it directly before you make a change to a file, and then unlock it immediately afterward. Updating a file with file locking
  • 649.
  • 650.
    $fh = fopen(&quot;testfile.txt&quot;,'r+') or die(&quot;Failed to open file&quot;);
  • 651.
  • 652.
  • 653.
  • 654.
  • 655.
    fwrite($fh, &quot;$text&quot;) ordie(&quot;Could not write to file&quot;);
  • 656.
  • 657.
  • 658.
  • 659.
    echo &quot;File 'testfile.txt'successfully updated&quot;;
  • 660.
  • 661.
    Reading an EntireFile A handy function for reading in an entire file without having to use file handles is file_get_contents.
  • 662.
    Note : Grabbingthe gmail.com home page
  • 663.
  • 664.
  • 665.
  • 666.
  • 667.
    echo &quot;<pre>&quot;; //Enables display of line feeds
  • 668.
  • 669.
    echo &quot;</pre>&quot;; //Terminates pre tag
  • 670.
  • 671.
    Uploading Files Thefirst line of the multiline echo statement starts an HTML document, displays the title, and then starts the document’s body.
  • 672.
    Next we cometo the form that selects the POST method of form submission, sets the target for posted data to the program upload.php (the program itself), and tells the web browser that the data posted should be encoded using the content type of multipart/form-data.
  • 673.
    With the formset up, the next lines display the prompt “Select File:” and then request two inputs. The first input being asked for is a file, which is done by using an input type of file and a name of filename, and the input field has a width of 10 characters.The second requested input is just a Submit button that is given the label “Upload
  • 674.
    <?php // upload.phpecho <<<_END <html><head><title>PHP Form Upload</title></head><body> <form method='post' action='upload.php' enctype='multipart/form-data'> Select File: <input type='file' name='filename' size='10' /> <input type='submit' value='Upload' /> </form> _END; if ($_FILES) { $name = $_FILES['filename']['name']; move_uploaded_file($_FILES['filename']['tmp_name'], $name); echo &quot;Uploaded image '$name'<br /><img src='$name' />&quot;; } echo &quot;</body></html>&quot;; ?>
  • 675.
    The PHP codeto receive the uploaded data is fairly simple, because all uploaded files are placed into the associative system array $_FILES. Therefore a quick check to see whether $_FILES has anything in it is sufficient to determine whether the user has uploaded a file. This is done with the statement if ($_FILES).
  • 676.
  • 677.
    Creating a databaseCREATE DATABASE publications; Now that you’ve created the database, you want to work with it, so issue: USE publications;
  • 678.
    Creating users GRANTALL ON publications.* TO 'ilg' IDENTIFIED BY 'ilg007';
  • 679.
    What this doesis allow the user ilg@localhost (the localhost is implied by omitting it) full access to the publications database using the password ilg007.
  • 680.
    Creating a tableCreating a table called classics
  • 681.
    mysql > CREATE TABLE classics (
  • 682.
  • 683.
  • 684.
  • 685.
  • 686.
    For creating theabove table within publications database,
  • 687.
  • 688.
    To check whetheryour new table has been created, type:
  • 689.
  • 690.
    A MySQL session:Creating and checking a new table mysql> USE publications; Database changed mysql> CREATE TABLE classics ( -> author VARCHAR(128), -> title VARCHAR(128), -> type VARCHAR(16), -> year CHAR(4)) ENGINE MyISAM; Query OK, 0 rows affected (0.03 sec) mysql> DESCRIBE classics; +--------+--------------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +--------+--------------+------+-----+---------+-------+ | author | varchar(128) | YES | | NULL | | | title | varchar(128) | YES | | NULL | | | type | varchar(16) | YES | | NULL | | | year | char(4) | YES | | NULL | | +--------+--------------+------+-----+---------+-------+ 4 rows in set (0.00 sec)
  • 691.
    Describe, Explain TheDESCRIBE command is an invaluable debugging aid when you need to ensure that you have correctly created a MySQL table. You can also use it to remind yourself about a table’s field or column names and the types of data in each one. Let’s look at each of the headings in detail:
  • 692.
    Field : The name of each field or column within a table.
  • 693.
    Type : The type of data being stored in the field.
  • 694.
    Null : Whether a field is allowed to contain a value of NULL.
  • 695.
    Key : MySQL supports keys or indexes, which are quick ways to look up and search for data. The Key heading shows what type of key (if any) has been applied.Default The default value that will be assigned to the field if no value is specified when a new row is created.
  • 696.
    Extra : Additional information, such as whether a field is set to auto-increment.
  • 697.
    Data types VARCHARstands for VARiable length CHARacter string and the command takes a numeric value that tells MySQL the maximum length allowed to a string stored in this field.
  • 698.
    Both CHAR andVARCHAR accept text strings and impose a limit on the size of the field.The difference is that every string in a CHAR field has the specified size. If you put in a smaller string, it is padded with spaces. A VARCHAR field does not pad the text; it lets the size of the field vary to fit the text that is inserted. But VARCHAR requires a small amount of overhead to keep track of the size of each value. So CHAR is slightly more efficient if the sizes are similar in all records, whereas VARCHAR is more efficient if sizes can vary a lot and get large. In addition, the overhead causes access to VARCHAR data to be slightly slower than to CHAR data.
  • 699.
  • 700.
    The BINARY datatype The BINARY data type is used for storing strings of full bytes that do not have an associated character set.Use the BINARY data type to store a GIF image.
  • 701.
    The TEXT andVARCHAR data types Mysql's text data types
  • 702.
    The BLOB datatype The term BLOB stands for Binary Large OBject and therefore, as you would think, the BLOB data type is most useful for binary data in excess of 65,536 bytes in size. The other main difference between the BLOB and BINARY data types is that BLOBs cannot have default values
  • 703.
    Numeric data typesMysql's numeric data type
  • 704.
    DATE and TIMEMySQL’s DATE and TIME data types The DATETIME and TIMESTAMP data types display the same way. The main difference is that TIMESTAMP has a very narrow range (from the years 1970 through 2037), whereas DATETIME will hold just about any date you’re likely to specify TIMESTAMP is useful, however, because you can let MySQL set the value for you. If you don’t specify the value when adding a row, the current time is automatically inserted.You can also have MySQL update a TIMESTAMP column each time you change a row.
  • 705.
    The AUTO_INCREMENT datatype Adding the auto-incrementing column id
  • 706.
    ALTER TABLE classicsADD id INT UNSIGNED NOT NULL AUTO_INCREMENT KEY;
  • 707.
    This is yourintroduction to the ALTER command, which is very similar to CREATE. ALTER operates on an existing table, and can add, change, or delete columns. Our example adds a column named id with the following characteristics:
  • 708.
    INT UNSIGNED: Makesthe column take an integer large enough for you to store more than 4 billion records in the table.
  • 709.
    NOT NULL: Ensuresthat every column has a value. Many programmers use NULL in a field to indicate that the field doesn’t have any value. But that would allow duplicates, which would violate the whole reason for this column’s existence. So we disallow NULL values.
  • 710.
    AUTO_INCREMENT: CausesMySQL to set a unique value for this column in every row, as described earlier. We don’t really have control over the value that this column will take in each row, but we don’t care: all we care about is that we are guaranteed a unique value.
  • 711.
    KEY: Anauto-increment column is useful as a key, because you will tend to search for rows based on this column. This will be explained in the section
  • 712.
    Adding the auto-incrementingid column at table creation
  • 713.
  • 714.
  • 715.
  • 716.
  • 717.
  • 718.
    id INT UNSIGNEDNOT NULL AUTO_INCREMENT KEY) ENGINE MyISAM;
  • 719.
  • 720.
  • 721.
    Adding data toa table To add data to a table, use the INSERT command.
  • 722.
    INSERT INTO classics(author,title, type, year) VALUES('Mark Twain','The Adventures of Tom Sawyer','Fiction','1876');
  • 723.
    INSERT INTO classics(author,title, type, year) VALUES('Jane Austen','Pride and Prejudice','Fiction','1811');
  • 724.
    INSERT INTO classics(author,title, type, year) VALUES('Charles Darwin','The Origin of Species','Non-Fiction','1856');
  • 725.
    INSERT INTO classics(author,title, type, year) VALUES('Charles Dickens','The Old Curiosity Shop','Fiction','1841');
  • 726.
    INSERT INTO classics(author,title, type, year) VALUES('William Shakespeare','Romeo and Juliet','Play','1594');
  • 727.
    Renaming a tableRenaming a table, like any other change to the structure or meta-information about atable, is achieved via the ALTER command.
  • 728.
    ALTER TABLE classicsRENAME pre1900;
  • 729.
    Rename the tableback to classics for examples to work.
  • 730.
    ALTER TABLE pre1900RENAME classics;
  • 731.
    Changing the datatype of a column
  • 732.
    ALTER TABLE classicsMODIFY year SMALLINT;
  • 733.
    Adding a newcolumn To add the new column pages, which will be used to store the number of pages in a publication
  • 734.
    ALTER TABLE classicsADD pages SMALLINT UNSIGNED;
  • 735.
  • 736.
    ALTER TABLE classicsCHANGE type category VARCHAR(16);
  • 737.
  • 738.
  • 739.
    Deleting a tableCreating, viewing, and deleting a table (This is a temp)
  • 740.
  • 741.
  • 742.
  • 743.
  • 744.
    Indexes As thingsstand, the table classics works and can be searched without problem by MySQL—until it grows to more than a couple hundred rows, that is. At that point, database accesses will get slower and slower with every new row added, because MySQL has to search through every row whenever a query is issued. This is like searching through every book in a library whenever you need to look something up.
  • 745.
    Creating an IndexThe way to achieve fast searches is to add an index, either when creating a table or at any time afterward.
  • 746.
    Adding indexes tothe classics table
  • 747.
    ALTER TABLE classicsADD INDEX(author(20));
  • 748.
    ALTER TABLE classicsADD INDEX(title(20));
  • 749.
    ALTER TABLE classicsADD INDEX(category(4));
  • 750.
    ALTER TABLE classicsADD INDEX(year);
  • 751.
  • 752.
    Using CREATE INDEXAn alternative to using ALTER TABLE to add an index is to use the CREATE INDEX command.
  • 753.
    They are equivalent,except that CREATE INDEX cannot be used to create a PRIMARY KEY
  • 754.
    These two commandsare equivalent
  • 755.
    ALTER TABLE classicsADD INDEX(author(20));
  • 756.
    CREATE INDEX authorON classics (author(20));
  • 757.
    Adding indexes whencreating tables Creating the table classics with indexes CREATE TABLE classics ( author VARCHAR(128), title VARCHAR(128), category VARCHAR(16), year SMALLINT, INDEX(author(20)), INDEX(title(20)), INDEX(category(4)), INDEX(year)) ENGINE MyISAM;
  • 758.
    Primary keys Populatingthe isbn column with data and using a primary key (single unique key for each publication to enable instant accessing of a row.)
  • 759.
    ALTER TABLE classicsADD isbn CHAR(13);
  • 760.
    UPDATE classics SETisbn='9781598184891' WHERE year='1876';
  • 761.
    UPDATE classics SETisbn='9780582506206' WHERE year='1811';
  • 762.
    UPDATE classics SETisbn='9780517123201' WHERE year='1856';
  • 763.
    UPDATE classics SETisbn='9780099533474' WHERE year='1841';
  • 764.
    UPDATE classics SETisbn='9780192814968' WHERE year='1594';
  • 765.
    ALTER TABLE classicsADD PRIMARY KEY(isbn);
  • 766.
  • 767.
    Creating a FULLTEXTindex Unlike a regular index, MySQL’s FULLTEXT allows super-fast searches of entire columns of text. What it does is it stores every word in every data string in a special index that you can search using “natural language,” in a similar manner to using a search engine.some things that you should know about FULLTEXT indexes:
  • 768.
    • FULLTEXTindexes can be used only with MyISAM tables, the type used by MySQL’s default storage engine (MySQL supports at least 10 different storage engines). If you need to convert a table to MyISAM, you can usually use the MySQL command:
  • 769.
    ALTER TABLE tablenameENGINE = MyISAM;.
  • 770.
    • FULLTEXTindexes can be created for CHAR, VARCHAR, and TEXT columns only.
  • 771.
    • AFULLTEXT index definition can be given in the CREATE TABLE statement when a table is created, or added later using ALTER TABLE (or CREATE INDEX).
  • 772.
    • For largedata sets, it is much faster to load your data into a table that has no
  • 773.
    FULLTEXT index andthen create the index than to load data into a table that has an existing FULLTEXT index.
  • 774.
    Adding a FULLTEXTindex to the classics table
  • 775.
    ALTER TABLE classicsADD FULLTEXT(author,title);
  • 776.
    You can nowperform FULLTEXT searches across this pair of columns.
  • 777.
    Using MATCH... AGAINSTon FULLTEXT indexes
  • 778.
    SELECT author,title FROMclassics WHERE MATCH(author,title) AGAINST('and');
  • 779.
    SELECT author,title FROMclassics WHERE MATCH(author,title) AGAINST('old shop');
  • 780.
    SELECT author,title FROMclassics WHERE MATCH(author,title) AGAINST('tom sawyer');
  • 781.
    Querying a MySQLDatabase SELECT:command is used to extract data from a table.The basic syntax is:
  • 782.
  • 783.
  • 784.
  • 785.
  • 786.
    SELECT COUNT : Counting rows
  • 787.
  • 788.
    DELETE When youneed to remove a row from a table, use the DELETE command. Its syntax is similar to the SELECT command and allows you to narrow down the exact row or rows to delete using qualifiers such as WHERE and LIMIT.
  • 789.
  • 790.
    DELETE FROM classicsWHERE title='Little Dorrit';
  • 791.
    WHERE The WHEREkeyword enables you to narrow down queries by returning only those where a certain expression is true.
  • 792.
  • 793.
    SELECT author,title FROMclassics WHERE author=&quot;Mark Twain&quot;;
  • 794.
    SELECT author,title FROMclassics WHERE isbn=&quot;9781598184891 &quot;;
  • 795.
    Using the LIKEqualifier
  • 796.
    SELECT author,title FROMclassics WHERE author LIKE &quot;Charles%&quot;;
  • 797.
    SELECT author,title FROMclassics WHERE title LIKE &quot;%Species&quot;;
  • 798.
    SELECT author,title FROMclassics WHERE title LIKE &quot;%and%&quot;;
  • 799.
    LIMIT The LIMITqualifier enables you to choose how many rows to return in a query, and where in the table to start returning them. When passed a single parameter, it tells MySQL to start at the beginning of the results and just return the number of rows given in that parameter. If you pass it two parameters, the first indicates the offset from the start of the results where MySQL should start the display, and the second indicates how many to return. You can think of the first parameter as saying, “Skip this number of results at the start.”
  • 800.
    Limiting the numberof results returned
  • 801.
    SELECT author,title FROMclassics LIMIT 3;
  • 802.
    SELECT author,title FROMclassics LIMIT 1,2;
  • 803.
    SELECT author,title FROMclassics LIMIT 3,1;
  • 804.
    UPDATE...SET This constructallows you to update the contents of a field. If you wish to change the contents of one or more fields, you need to first narrow in on just the field or fields to be changed, in much the same way you use the SELECT command.
  • 805.
  • 806.
    UPDATE classics SETauthor='Mark Twain (Samuel Langhorne Clemens)' WHERE author='Mark Twain';
  • 807.
    UPDATE classics SETcategory='Classic Fiction' WHERE category='Fiction';
  • 808.
    ORDER BY ORDERBY sorts returned results by one or more columns in ascending or descending order.
  • 809.
  • 810.
    SELECT author,title FROMclassics ORDER BY author;
  • 811.
    SELECT author,title FROMclassics ORDER BY title DESC;
  • 812.
    The first queryreturns the publications by author in ascending alphabetical order (the default), and the second returns them by title in descending order.
  • 813.
    f you wantedto sort all the rows by author and then by descending year of publication (to view the most recent first), you would issue the following query:
  • 814.
    SELECT author,title,year FROMclassics ORDER BY author,year DESC;
  • 815.
    GROUP BY Ina similar fashion to ORDER BY, you can group results returned from queries using GROUP BY, which is good for retrieving information about a group of data.
  • 816.
    SELECT category,COUNT(author) FROMclassics GROUP BY category;
  • 817.
    Joining Tables TogetherIt is quite normal to maintain multiple tables within a database, each holding a different type of information. For example, consider the case of a customers table that needs to be able to be cross-referenced with publications purchased from the classics table. Creating and populating the customers table
  • 818.
  • 819.
  • 820.
  • 821.
    PRIMARY KEY (isbn))ENGINE MyISAM;
  • 822.
    INSERT INTO customers(name,isbn)VALUES('Joe Bloggs','9780099533474');
  • 823.
    INSERT INTO customers(name,isbn) VALUES('Mary Smith','9780582506206');
  • 824.
    INSERT INTO customers(name,isbn) VALUES('Jack Wilson','9780517123201');
  • 825.
    SELECT * FROMcustomers;
  • 826.
    Joining two tablesinto a single SELECT SELECT name,author,title from customers,classics WHERE customers.isbn=classics.isbn;
  • 827.
  • 828.
    Using NATURAL JOIN,you can save yourself some typing and make queries a little clearer.This kind of join takes two tables and automatically joins columns that have the same name .
  • 829.
    SELECT name,author,title FROMcustomers NATURAL JOIN classics;
  • 830.
  • 831.
    If you wishto specify the column on which to join two tables, use the JOIN...ON construct
  • 832.
    SELECT name,author,title FROMcustomers JOIN classics ON customers.isbn=classics.isbn;
  • 833.
    Using Logical OperatorsYou can also use the logical operators AND, OR, and NOT in your MySQL WHERE queries to further narrow down your selections.
  • 834.
  • 835.
    SELECT author,title FROMclassics WHERE author LIKE &quot;Charles%&quot; AND author LIKE &quot;%Darwin&quot;;
  • 836.
    SELECT author,title FROMclassics WHERE author LIKE &quot;%Mark Twain%&quot; OR author LIKE &quot;%Samuel Langhorne Clemens%&quot;;
  • 837.
    SELECT author,title FROMclassics WHERE author LIKE &quot;Charles%&quot; AND author NOT LIKE &quot;%Darwin&quot; ;
  • 838.
    Mastering MySQL PrimaryKeys: The Keys to Relational Databases
  • 839.
    Normalization:The process ofseparating your data into tables and creating primary keys is called normalization. Its main goal is to make sure each piece of information appears in the database only once. Duplicating data is very inefficient, because it makes databases larger than they need to be and therefore slows down access.
  • 840.
  • 841.
    For a databaseto satisfy the First Normal Form, it must fulfill three requirements:
  • 842.
    1. There shouldbe no repeating columns containing the same kind of data.
  • 843.
    2. All columnsshould contain a single value.
  • 844.
    3. There shouldbe a primary key to uniquely identify each row.
  • 845.
    The Second NormalForm is all about redundancy across multiple rows. In order to achieve Second Normal Form, your tables must already be in First Normal Form.Once this has been done, Second Normal Form is achieved by identifying columns whose data repeats in different places and then removing them to their own tables.
  • 846.
  • 847.
    When Not toUse Normalization Why you should throw these rules out of the window on high-traffic sites. That’s right— you should never fully normalize your tables on sites that will cause MySQL to thrash.Normalization requires spreading data across multiple tables, and this means making multiple calls to MySQL for each query. On a very popular site, if you have normalized tables, your database access will slow down considerably once you get above a few dozen concurrent users, because they will be creating hundreds of database accesses between them
  • 848.
    Relationships MySQL iscalled a relational database management system because its tables store not only data but the relationships among the data. There are three categories of relationships.
  • 849.
  • 850.
    One-to-Many :One-to-many (ormany-to-one) relationships occur when one row in one table is linked to many rows in another table.
  • 851.
    Many-to-Many :Ina many-to-many relationship, many rows in one table are linked to many rows in another table.
  • 852.
    Transactions In someapplications, it is vitally important that a sequence of queries runs in the correct order and that every single query successfully completes. For example, suppose that you are creating a sequence of queries to transfer funds from one bank account to another. You would not want either of the following events to occur:
  • 853.
    • Youadd the funds to the second account, but when you try to subtract them from the first account the update fails, and now both accounts have the funds.
  • 854.
    • Yousubtract the funds from the first bank account, but the update request to add them to the second account fails, and the funds have now disappeared into thin air.
  • 855.
    Transaction Storage EnginesIn order to be able to use MySQL’s transaction facility, you have to be using MySQL’sInnoDB storage engine.
  • 856.
  • 857.
  • 858.
    number INT, balanceFLOAT, PRIMARY KEY(number)
  • 859.
  • 860.
  • 861.
  • 862.
    INSERT INTO accounts(number,balance) VALUES(12345, 1025.50);
  • 863.
    INSERT INTO accounts(number,balance) VALUES(67890, 140.00);
  • 864.
    SELECT * FROMaccounts;
  • 865.
    Using BEGIN Transactionsin MySQL start with either a BEGIN or a START TRANSACTION statement
  • 866.
  • 867.
  • 868.
    UPDATE accounts SETbalance=balance+25.11 WHERE number=12345;
  • 869.
  • 870.
    SELECT * FROMaccounts;
  • 871.
    Using COMMIT Whenyou are satisfied that a series of queries in a transaction has successfully completed, issue a COMMIT command to commit all the changes to the database.Until a COMMIT is received, all the changes you make are considered to be merely temporary by MySQL. This feature gives you the opportunity to cancel a transaction by not sending a COMMIT but by issuing a ROLLBACK command instead.
  • 872.
    Using ROLLBACK Usingthe ROLLBACK command, you can tell MySQL to forget all the queries made since the start of a transaction and to end the transaction.
  • 873.
    A funds transfertransaction
  • 874.
  • 875.
    UPDATE accounts SETbalance=balance-250 WHERE number=12345;
  • 876.
    UPDATE accounts SETbalance=balance+250 WHERE number=67890;
  • 877.
    SELECT * FROMaccounts;
  • 878.
  • 879.
  • 880.
    SELECT * FROMaccounts;
  • 881.
    Backing Up andRestoring Using mysqldump :With mysqldump, you can dump a database or collection of databases into one or more files containing all the instructions necessary to recreate all your tables and repopulate them with your data. It can also generate files in CSV (Comma-Separated Values) and other delimited text formats, or even in XML format. Its main drawback is that you must make sure that no one writes to a table while you’re backing it up. There are various ways to do this, but the easiest is to shut down the MySQL server before mysqldump and start up the server again after mysqldump finishes.
  • 882.
    You can lockthe tables you are backing up before running mysqldump. To lock tables for reading (as we want to read the data), from the MySQL command line issue the command:
  • 883.
    LOCK TABLES tablename1tablename2 ... READ
  • 884.
    Then, to releasethe lock(s), enter:
  • 885.
  • 886.
    By default, theoutput from mysqldump is simply printed out, but you can capture it in a file through the > redirect symbol.
  • 887.
    The basic formatof the mysqldump command is:
  • 888.
    mysqldump -u user-ppassword database
  • 889.
    Dumping the publicationsdatabase to screen
  • 890.
    mysqldump -u user-ppassword publications
  • 891.
    Creating a BackupFile :Now that you have mysqldump working, and have verified it outputs correctly to the screen, you can send the backup data directly to a file using the > redirect symbol.
  • 892.
    mysqldump -u user-ppassword publications > publications.sql
  • 893.
    Dumping just theclassics table from publications
  • 894.
    $ mysql -uuser -ppassword
  • 895.
    mysql> LOCK TABLESclassics READ
  • 896.
  • 897.
    $ mysqldump -uuser -ppassword publications classics > classics.sql
  • 898.
    $ mysql -uuser -ppassword
  • 899.
  • 900.
  • 901.
    Dumping all theMySQL databases to file
  • 902.
    mysqldump -u user-ppassword --all-databases > all_databases.sql
  • 903.
    Restoring from aBackup File To perform a restore from a file, call the mysql executable, passing it the file to restore from using the < symbol. So, to recover an entire database that you dumped using the --all-databases option
  • 904.
    Restoring an entireset of databases
  • 905.
    mysql -u user-ppassword < all_databases.sql
  • 906.
  • 907.
    mysql -u user-ppassword -D publications < publications.sql
  • 908.
    Restoring the classicstable to the publications database
  • 909.
    mysql -u user-ppassword -D publications < classics.sql
  • 910.
  • 911.
    Querying a MySQLDatabase with PHP The Process The process of using MySQL with PHP is:
  • 912.
  • 913.
    2. Select thedatabase to use.
  • 914.
    3. Build aquery string.
  • 915.
  • 916.
    5. Retrieve theresults and output it to a web page.
  • 917.
    6. Repeat Steps3 to 5 until all desired data have been retrieved.
  • 918.
  • 919.
    Creating a LoginFile Most websites developed with PHP contain multiple program files that will require access to MySQL and will therefore need the login and password details. Therefore,it’s sensible to create a single file to store these and then include that file wherever it’s needed. The login.php file
  • 920.
  • 921.
  • 922.
  • 923.
  • 924.
  • 925.
  • 926.
    Connecting to MySQLThe login.php file saved, you can include it in any PHP files that will need to access the database by using the require_once statement. This has been chosen in preference to an include statement, as it will generate a fatal error if the file is not found.
  • 927.
    This example runsPHP’s mysql_connect function, which requires three parameters, the hostname, username, and password of a MySQL server. Upon success it returns an identifier to the server; otherwise, FALSE is returned. Notice that the second line uses an if statement with the die function, which does what it sounds like and quits from PHP with an error message if $db_server is not TRUE. Connecting to a MySQL database
  • 928.
  • 929.
  • 930.
    $db_server = mysql_connect($db_hostname,$db_username, $db_password);
  • 931.
    if (!$db_server) die(&quot;Unableto connect to MySQL: &quot; . mysql_error());
  • 932.
  • 933.
    The die messageexplains that it was not possible to connect to the MySQL database,and—to help identify why this happened—includes a call to the mysql_error function. his function outputs the error text from the last called MySQL function.
  • 934.
    Selecting a databaseThe command to select the database is mysql_select_db. Pass it the name of the database you want and the server to which you connected. Selecting a database
  • 935.
  • 936.
  • 937.
    or die(&quot;Unable toselect database: &quot; . mysql_error());
  • 938.
  • 939.
    Building and executinga query Sending a query to MySQL from PHP is as simple as issuing it using the mysql_query function.
  • 940.
    First, the variable$query is set to the query to be made. In this case it is asking to see all rows in the table classics. Note that, unlike using MySQL’s command line, no semicolon is required at the tail of the query, because the mysql_query function is used to issue a complete query, and cannot be used to query by sending multiple parts, one at a time. Therefore, MySQL knows the query is complete and doesn’t look for a semicolon. Querying a database
  • 941.
  • 942.
    $query = &quot;SELECT* FROM classics&quot;;
  • 943.
  • 944.
    if (!$result) die(&quot;Database access failed: &quot; . mysql_error());
  • 945.
  • 946.
    Fetching a resultOnce you have a resource returned from a mysql_query function, you can use it to retrieve the data you want. The simplest way to do this is to fetch the cells you want,one at a time, using the mysql_result function.
  • 947.
    Fetching results onecell at a time
  • 948.
  • 949.
  • 950.
    $db_server = mysql_connect($db_hostname,$db_username, $db_password);
  • 951.
    if (!$db_server) die(&quot;Unableto connect to MySQL: &quot; . mysql_error());
  • 952.
  • 953.
    or die(&quot;Unable toselect database: &quot; . mysql_error());
  • 954.
    $query = &quot;SELECT* FROM classics&quot;;
  • 955.
  • 956.
    $result = mysql_query($query);if (!$result) die (&quot;Database access failed: &quot; . mysql_error()); $rows = mysql_num_rows($result); for ($j = 0 ; $j < $rows ; ++$j) { echo 'Author: ' . mysql_result($result,$j,'author') . '<br />'; echo 'Title: ' . mysql_result($result,$j,'title') . '<br />'; echo 'Category: ' . mysql_result($result,$j,'category') . '<br />'; echo 'Year: ' . mysql_result($result,$j,'year') . '<br />'; echo 'ISBN: ' . mysql_result($result,$j,'isbn') . '<br /><br />'; } ?>
  • 957.
    Fetching a rowEach row is fetched in its entirety using the mysql_fetch_row function. This returns a single row of data in an array, which is then assigned to the variable $row. for loop for fetching results one row at a time
  • 958.
  • 959.
    for ($j =0 ; $j < $rows ; ++$j)
  • 960.
  • 961.
  • 962.
    echo 'Author: '. $row[0] . '<br />';
  • 963.
    echo 'Title: '. $row[1] . '<br />';
  • 964.
    echo 'Category: '. $row[2] . '<br />';
  • 965.
    echo 'Year: '. $row[3] . '<br />';
  • 966.
    echo 'ISBN: '. $row[4] . '<br /><br />';
  • 967.
  • 968.
  • 969.
    Closing a connectionWhen you have finished using a database, you should close the connection Closing a MySQL database connection
  • 970.
  • 971.
  • 972.
  • 973.
  • 974.
    Creating a TableLet’s assume that you are working for a wildlife park and need to create a database to hold details about all the types of cats it houses. You are told that there are nine families of cats: Lion, Tiger, Jaguar, Leopard, Cougar, Cheetah, Lynx, Caracal, and Domestic, so you’ll need a column for that. Then each cat has been given a name, so that’s another column, and you also want to keep track of their ages, which is another.Of course, you will probably need more columns later, perhaps to hold dietary requirements, inoculations, and other details, but for now that’s enough to get going. A unique identifier is also needed for each animal, so you also decide to create a column for that called id.
  • 975.
    Creating a tablecalled cats <?php require_once 'login.php'; $db_server = mysql_connect($db_hostname, $db_username, $db_password); if (!$db_server) die(&quot;Unable to connect to MySQL: &quot; . mysql_error()); mysql_select_db($db_database) or die(&quot;Unable to select database: &quot; . mysql_error()); $query = &quot;CREATE TABLE cats ( id SMALLINT NOT NULL AUTO_INCREMENT, family VARCHAR(32) NOT NULL, name VARCHAR(32) NOT NULL, age TINYINT NOT NULL, PRIMARY KEY (id) )&quot;; $result = mysql_query($query); if (!$result) die (&quot;Database access failed: &quot; . mysql_error()); ?>
  • 976.
    Describing a TableWhen you aren’t logged into the MySQL command line, next slide presents a handy piece of code that you can use to verify that a table has been correctly created from inside a browser. It simply issues the query DESCRIBE cats and then outputs an HTML table with four headings: Column, Type, Null, and Key, underneath which all columns within the table are shown. To use it with other tables, simply replace the name “cats” in the query with that of the new table
  • 977.
    Describing the catstable <?php require_once 'login.php'; $db_server = mysql_connect($db_hostname, $db_username, $db_password); if (!$db_server) die(&quot;Unable to connect to MySQL: &quot; . mysql_error()); mysql_select_db($db_database) or die(&quot;Unable to select database: &quot; . mysql_error()); $query = &quot;DESCRIBE cats&quot;; $result = mysql_query($query); if (!$result) die (&quot;Database access failed: &quot; . mysql_error()); $rows = mysql_num_rows($result); echo &quot;<table><tr> <th>Column</th> <th>Type</th> <th>Null</th> <th>Key</th> </tr>&quot;; for ($j = 0 ; $j < $rows ; ++$j) { $row = mysql_fetch_row($result); echo &quot;<tr>&quot;; for ($k = 0 ; $k < 4 ; ++$k) echo &quot;<td>$row[$k]</td>&quot;; echo &quot;</tr>&quot;; } echo &quot;</table>&quot;; ?>
  • 978.
    Dropping a TableDropping the table cats <?php require_once 'login.php'; $db_server = mysql_connect($db_hostname, $db_username, $db_password); if (!$db_server) die(&quot;Unable to connect to MySQL: &quot; . mysql_error()); mysql_select_db($db_database) or die(&quot;Unable to select database: &quot; . mysql_error()); $query = &quot;DROP TABLE cats&quot;; $result = mysql_query($query); if (!$result) die (&quot;Database access failed: &quot; . mysql_error()); ?>
  • 979.
    Adding Data Addingdata to table cats <?php require_once 'login.php'; $db_server = mysql_connect($db_hostname, $db_username, $db_password); if (!$db_server) die(&quot;Unable to connect to MySQL: &quot; . mysql_error()); mysql_select_db($db_database) or die(&quot;Unable to select database: &quot; . mysql_error()); $query = &quot;INSERT INTO cats VALUES(NULL, 'Lion', 'Leo', 4)&quot;; $result = mysql_query($query); if (!$result) die (&quot;Database access failed: &quot; . mysql_error()); ?>
  • 980.
    Retrieving Data Retrievingrows from the cats table <?php require_once 'login.php'; $db_server = mysql_connect($db_hostname, $db_username, $db_password); if (!$db_server) die(&quot;Unable to connect to MySQL: &quot; . mysql_error()); mysql_select_db($db_database) or die(&quot;Unable to select database: &quot; . mysql_error()); $query = &quot;SELECT * FROM cats&quot;; $result = mysql_query($query); if (!$result) die (&quot;Database access failed: &quot; . mysql_error()); $rows = mysql_num_rows($result); echo &quot;<table><tr> <th>Id</th> <th>Family</th> <th>Name</th><th>Age</th></tr>&quot;; for ($j = 0 ; $j < $rows ; ++$j) { $row = mysql_fetch_row($result); echo &quot;<tr>&quot;; for ($k = 0 ; $k < 4 ; ++$k) echo &quot;<td>$row[$k]</td>&quot;; echo &quot;</tr>&quot;; } echo &quot;</table>&quot;; ?>
  • 981.
    Updating Data RenamingCharly the Cheetah to Charlie <?php require_once 'login.php'; $db_server = mysql_connect($db_hostname, $db_username, $db_password); if (!$db_server) die(&quot;Unable to connect to MySQL: &quot; . mysql_error()); mysql_select_db($db_database) or die(&quot;Unable to select database: &quot; . mysql_error()); $query = &quot;UPDATE cats SET name='Charlie' WHERE name='Charly'&quot;; $result = mysql_query($query); if (!$result) die (&quot;Database access failed: &quot; . mysql_error()); ?>
  • 982.
    Deleting Data RemovingGrowler the Cougar from the cats table <?php require_once 'login.php'; $db_server = mysql_connect($db_hostname, $db_username, $db_password); if (!$db_server) die(&quot;Unable to connect to MySQL: &quot; . mysql_error()); mysql_select_db($db_database) or die(&quot;Unable to select database: &quot; . mysql_error()); $query = &quot;DELETE FROM cats WHERE name='Growler'&quot;; $result = mysql_query($query); if (!$result) die (&quot;Database access failed: &quot; . mysql_error()); ?>
  • 983.
    Using AUTO_INCREMENT Addingdata to cats table and reporting the insertion id
  • 984.
  • 985.
  • 986.
    $db_server = mysql_connect($db_hostname,$db_username, $db_password);
  • 987.
    if (!$db_server) die(&quot;Unableto connect to MySQL: &quot; . mysql_error());
  • 988.
    mysql_select_db($db_database) or die(&quot;Unableto select database: &quot; . mysql_error());
  • 989.
    $query = &quot;INSERTINTO cats VALUES(NULL, 'Lynx', 'Stumpy', 5)&quot;; $result = mysql_query($query); echo &quot;The Insert ID was: &quot; . mysql_insert_id(); if (!$result) die (&quot;Database access failed: &quot; . mysql_error()); ?>
  • 990.
    Preventing SQL InjectionYou should always use the function
  • 991.
  • 992.
    for all callsto MySQL It's a function you can use that will remove any magic quotes added to a user-inputted string and then properly sanitize it for you.
  • 993.
    The get_magic_quotes_gpc functionreturns TRUE if magic quotes are active. In that case,any slashes that have been added to a string have to be removed or the function mysql_real_escape_string could end up double-escaping some characters, creating corrupted strings. How to properly sanitize user input for MySQL <?php function mysql_fix_string($string) { if (get_magic_quotes_gpc()) $string = stripslashes($string); return mysql_real_escape_string($string); } ?>
  • 994.
    How to safelyaccess MySQL with user input <?php $user = mysql_fix_string($_POST['user']); $pass = mysql_fix_string($_POST['pass']); $query = &quot;SELECT * FROM users WHERE user='$user' AND pass='$pass'&quot;; function mysql_fix_string($string) { if (get_magic_quotes_gpc()) $string = stripslashes($string); return mysql_real_escape_string($string); } ?>
  • 995.
    Preventing HTML InjectionThere’s another type of injection you need to concern yourself about—not for the safety of your own websites, but for your users’ privacy and protection. That’s Cross Site Scripting, also referred to as XSS.
  • 996.
    This occurs whenyou allow HTML, or more often JavaScript code, to be input by a user and then displayed back by your website. One place this is common is in a comment form. What most often happens is that a malicious user will try to write code that steals cookies from your site’s users, allowing him or her to discover username and password pairs or other information. Even worse, the malicious user might launch an attack to download a Trojan onto a user’s computer.
  • 997.
    The htmlentities function, which strips out all HTML markup codes and replaces them with a form that displays the characters, but does not allow a browser to act on them
  • 998.
  • 999.
    This code loadsin a JavaScript program and then executes malicious functions. But if it is first passed through htmlentities , it will be turned into the following, totally harmless string:
  • 1000.
    &lt;script src='http://x.com/hack.js'&gt; &lt;/script&gt;&lt;script&gt;hack();&lt;/script&gt;Therefore, if you are ever going to display anything that your users enter, either im mediately or after first storing it in database, you need to first sanitize it with htmlentities.
  • 1001.
    Functions for preventingboth SQL and XSS injection attacks
  • 1002.
  • 1003.
  • 1004.
  • 1005.
  • 1006.
  • 1007.
  • 1008.
  • 1009.
    if (get_magic_quotes_gpc()) $string= stripslashes($string);
  • 1010.
  • 1011.
  • 1012.
  • 1013.
    The mysql_entities_fix_string function first calls mysql_fix_string and then passes the result through htmlentities before returning the fully sanitized string
  • 1014.
    How to safelyaccess MySQL and prevent XSS attacks <?php $user = mysql_entities_fix_string($_POST['user']); $pass = mysql_entities_fix_string($_POST['pass']); $query = &quot;SELECT * FROM users WHERE user='$user' AND pass='$pass'&quot;; function mysql_entities_fix_string($string) { return htmlentities(mysql_fix_string($string)); } function mysql_fix_string($string) { if (get_magic_quotes_gpc()) $string = stripslashes($string); return mysql_real_escape_string($string); } ?>
  • 1015.
  • 1016.
    Building Forms First,a form is created into which a user can enter the required details. This data is then sent to the web server, where it is interpreted, often with some error checking. If the PHP code identifies one or more fields that require reentering, the form may be redisplayed with an error message. When the code is satisfied with the accuracy of the input, it takes some action that usually involves the database, such as entering details about a purchase.
  • 1017.
    To build aform, you must have at least the following elements:
  • 1018.
    1) An opening<form> and closing </form> tag
  • 1019.
    2) A submissiontype specifying either a get or post method
  • 1020.
    3) One ormore input fields
  • 1021.
    4) The destinationURL to which the form data is to be submitted
  • 1022.
    PHP GET andPOST Methods There are two ways the browser client can send information to the web server. * The GET Method * The POST Method Before the browser sends the information, it encodes it using a scheme called URL encoding. In this scheme, name/value pairs are joined with equal signs and different pairs are separated by the ampersand. name1=value1&name2=value2&name3=value3 Spaces are removed and replaced with the + character and any other nonalphanumeric characters are replaced with a hexadecimal values. After the information is encoded it is sent to the server.
  • 1023.
    The GET MethodThe GET method sends the encoded user information appended to the page request. The page and the encoded information are separated by the ? character. http://www.test.com/index.htm?name1=value1&name2=value2 The GET method produces a long string that appears in your server logs, in the browser's Location: box. The GET method is restricted to send upto 1024 characters only. Never use GET method if you have password or other sensitive information to be sent to the server. GET can't be used to send binary data, like images or word documents, to the server. The data sent by GET method can be accessed using QUERY_STRING environment variable. The PHP provides $_GET associative array to access all the sent information using GET method.
  • 1024.
    The POST MethodThe POST method transfers information via HTTP headers. The information is encoded as described in case of GET method and put into a header called QUERY_STRING. The POST method does not have any restriction on data size to be sent. The POST method can be used to send ASCII as well as binary data. The data sent by POST method goes through HTTP header so security depends on HTTP protocol. By using Secure HTTP you can make sure that your information is secure. The PHP provides $_POST associative array to access all the sent information using GET method.
  • 1025.
    <?php // formtest.phpif (isset($_POST['name'])) $name = $_POST['name']; else $name = &quot;(Not entered)&quot;; echo <<<_END <html> <head> <title>Form Test</title> </head> <body> Your name is: $name<br /> <form method=&quot;post&quot; action=&quot;formtest2.php&quot;> What is your name? <input type=&quot;text&quot; name=&quot;name&quot; /> <input type=&quot;submit&quot; /> </form> </body> </html> _END; ?> The echo <<<_END..._END construct is used whenever multiline HTML must be output. $_POST associative array, which contains an element for each field in an HTML form. formtest.php—a simple PHP form handler
  • 1026.
    The input nameused was name and the form method was post, so element name of the $_POST array contains the value in $_POST['name'].
  • 1027.
    The PHP isset function is used to test whether $_POST['name'] has been assigned a value . If nothing was posted, the program assigns the value “(Not entered)”; otherwise, it stores the value that was entered. Then a single line has been added after the <body> statement to display that value, which is stored in $name.
  • 1028.
    register_globals: An OldSolution Hangs On Before security became such a big issue, the default behavior of PHP was to assign the$_POST and $_GET arrays directly to PHP variables. For example, there would be no need to use the instruction $name=$_POST['name']; because $name would already be given that value automatically by PHP at the program start!
  • 1029.
    Initially (prior toversion 4.2.0 of PHP), this seemed a very useful idea that saved a lot of extra code-writing, but this practice has now been discontinued and the feature is disabled by default. Should you find register_globals enabled on a production web server for which you are developing, you should urgently ask your server administrator to disable it.
  • 1030.
    So why disableregister_globals? It enables anyone to enter a GET input on the tail of a URL, like this: http://myserver.com?override=1, and if your code were ever to use the variable $override and you forgot to initialize it (for example, through $override=0;), the program could be compromised by such an exploit.
  • 1031.
    Input Types HTMLforms are very versatile and allow you to submit a wide range of different typesof inputs ranging from text boxes and text areas to checkboxes, radio buttons,and more.
  • 1032.
    Text Boxes :The type of input you will most often use is the text box. It accepts a wide range of alphanumeric text and other characters in a single-line box. The general format of a text box input is:
  • 1033.
    <input type=&quot;text&quot; name=&quot;name&quot;size=&quot;size&quot; maxlength=&quot;length&quot; value=&quot;value&quot; />
  • 1034.
    Text Areas : When you need to accept input of more than a short line of text, use a text area. This is similar to a text box but, because it allows multiple lines, it has some different parameters.
  • 1035.
    <textarea name=&quot;name&quot; cols=&quot;width&quot;rows=&quot;height&quot; wrap=&quot;type&quot;></textarea>
  • 1036.
    Checkboxes :When youwant to offer a number of different options to a user, from which he or she can select one or more items, checkboxes are the way to go. The format to use is:
  • 1037.
    <input type=&quot;checkbox&quot; name=&quot;name&quot;value=&quot;value&quot; checked=&quot;checked&quot; />
  • 1038.
    Radio Buttons : Radio buttons are named after the push-in preset buttons found on many older radios,where any previously depressed button pops back up when another is pressed. They are used when you want only a single value to be returned from a selection of two or more options. All the buttons in a group must use the same name and, because only a single value is returned, you do not have to pass an array.
  • 1039.
    Cookies, Sessions, andAuthentication A cookie is an item of data that a web server saves to your computer’s hard disk via a web browser. It can contain almost any alphanumeric information (as long as it’s under 4 KB) and can be retrieved from your computer and returned to the server. Common uses include session tracking, maintaining data across multiple visits, holding shopping cart contents, storing login details, and more.
  • 1040.
    Cookies are exchangedduring the transfer of headers, before the actual HTML of a web page is sent, and it is impossible to send a cookie once any HTML has been transferred.
  • 1041.
    This exchange showsa browser receiving two pages:
  • 1042.
    1. The browserissues a request to retrieve the main page, index.html, at the website http://www.webserver.com. The first header specifies the file and the second header specifies the server.
  • 1043.
    2. When theweb server at webserver.com receives this pair of headers, it returns some of its own. The second header defines the type of content to be sent (text/html) and the third one sends a cookie of the name name and with the value value. Only then are the contents of the web page transferred.
  • 1044.
    3. Once thebrowser has received the cookie, it will then return it with every future request made to the issuing server until the cookie expires or is deleted. So, when the browser requests the new page /news.html, it also returns the cookie name with the value value.
  • 1045.
    4. Because thecookie has already been set, when the server receives the request to send /news.html, it does not have to resend the cookie, but just returns the requested page.
  • 1046.
    Setting a CookieTo set a cookie in PHP .as long as no HTML has yet been transferred,you can call the setcookie function, which has the following syntax
  • 1047.
    setcookie(name, value, expire,path, domain, secure, httponly);
  • 1048.
    So, to createa cookie with the name username and the value “Hannah” that is accessible across the entire web server on the current domain, and removed from the browser’s cache in seven days, use the following:
  • 1049.
    setcookie('username', 'Hannah', time()+ 60 * 60 * 24 * 7, '/');
  • 1050.
  • 1051.
  • 1052.
  • 1053.
    To delete acookie, you must issue it again and set a date in the past. It is important for all parameters in your new setcookie call except the timestamp to be identical to the parameters when the cookie was first issued; otherwise, the deletion will fail. Therefore, to delete the cookie created earlier, you would use the following:
  • 1054.
  • 1055.
    HTTP Authentication HTTPauthentication uses the web server to manage users and passwords for the application.
  • 1056.
    To use HTTPauthentication, PHP sends a header request asking to start an authentication dialog with the browser. The server must have this feature turned on in order for it to work, but because it’s so common, your server is very likely to offer the feature.
  • 1057.
    PHP Authentication withinput checking <?php $username = 'admin'; $password = 'letmein'; if (isset($_SERVER['PHP_AUTH_USER']) && isset($_SERVER['PHP_AUTH_PW'])) { if ($_SERVER['PHP_AUTH_USER'] == $username && $_SERVER['PHP_AUTH_PW'] == $password) echo &quot;You are now logged in&quot;; else die(&quot;Invalid username / password combination&quot;); } else { header('WWW-Authenticate: Basic realm=&quot;Restricted Section&quot;'); header('HTTP/1.0 401 Unauthorized'); die (&quot;Please enter your username and password&quot;); } ?>
  • 1058.
    Storing Usernames andPasswords Creating a users table and adding two accounts
  • 1059.
  • 1060.
  • 1061.
    $db_server = mysql_connect($db_hostname,$db_username, $db_password);
  • 1062.
    if (!$db_server) die(&quot;Unableto connect to MySQL: &quot; . mysql_error());
  • 1063.
  • 1064.
    or die(&quot;Unable toselect database: &quot; . mysql_error());
  • 1065.
    $query = &quot;CREATETABLE users (
  • 1066.
  • 1067.
  • 1068.
    username VARCHAR(32) NOT NULL UNIQUE,
  • 1069.
  • 1070.
  • 1071.
    $result = mysql_query($query);if (!$result) die (&quot;Database access failed: &quot; . mysql_error()); $salt1 = &quot;qm&h*&quot;; $salt2 = &quot;pg!@&quot;; $forename = 'Bill'; $surname = 'Smith'; $username = 'bsmith'; $password = 'mysecret'; $token = md5(&quot;$salt1$password$salt2&quot;); add_user($forename, $surname, $username, $token);
  • 1072.
    $forename = 'Pauline';$surname = 'Jones'; $username = 'pjones'; $password = 'acrobat'; $token = md5(&quot;$salt1$password$salt2&quot;); add_user($forename, $surname, $username, $token); $forename = 'Pauline'; $surname = 'Jones'; $username = 'pjones'; $password = 'acrobat'; $token = md5(&quot;$salt1$password$salt2&quot;); add_user($forename, $surname, $username, $token);
  • 1073.
    function add_user($fn, $sn,$un, $pw) { $query = &quot;INSERT INTO users VALUES('$fn', '$sn', '$un', '$pw')&quot;; $result = mysql_query($query); if (!$result) die (&quot;Database access failed: &quot; . mysql_error()); } ?> This program will create the table users within your publications database i n this table, it will create two users: Bill Smith and Pauline Jones. They have the usernames and passwords of bsmith/mysecret and pjones/acrobat, respectively.
  • 1074.
    PHP authentication usingMySQL <?php // authenticate.php require_once 'login.php'; $db_server = mysql_connect($db_hostname, $db_username, $db_password); if (!$db_server) die(&quot;Unable to connect to MySQL: &quot; . mysql_error()); mysql_select_db($db_database) or die(&quot;Unable to select database: &quot; . mysql_error()); if (isset($_SERVER['PHP_AUTH_USER']) && isset($_SERVER['PHP_AUTH_PW'])) { $un_temp = mysql_entities_fix_string($_SERVER['PHP_AUTH_USER']); $pw_temp = mysql_entities_fix_string($_SERVER['PHP_AUTH_PW']);
  • 1075.
    $query = &quot;SELECT* FROM users WHERE username='$un_temp'&quot;; $result = mysql_query($query); if (!$result) die(&quot;Database access failed: &quot; . mysql_error()); elseif (mysql_num_rows($result)) { $row = mysql_fetch_row($result); $salt1 = &quot;qm&h*&quot;; $salt2 = &quot;pg!@&quot;; $token = md5(&quot;$salt1$pw_temp$salt2&quot;); if ($token == $row[3]) echo &quot;$row[0] $row[1] : Hi $row[0], you are now logged in as '$row[2]'&quot;; else die(&quot;Invalid username/password combination&quot;); }
  • 1076.
    else die(&quot;Invalid username/passwordcombination&quot;); } else { header('WWW-Authenticate: Basic realm=&quot;Restricted Section&quot;'); header('HTTP/1.0 401 Unauthorized'); die (&quot;Please enter your username and password&quot;); } function mysql_entities_fix_string($string) { return htmlentities(mysql_fix_string($string)); }
  • 1077.
    function mysql_fix_string($string) {if (get_magic_quotes_gpc()) $string = stripslashes($string); return mysql_real_escape_string($string); } ?>
  • 1078.
    Using Sessions PHPprovides a much more powerful and simpler solution in the form of sessions. These are groups of variables that are stored on the server but relate only to the current user. To ensure that the right variables are applied to the right users, a cookie is saved in their web browsers to uniquely identify them.
  • 1079.
    This cookie hasmeaning only to the web server and cannot be used to ascertain any information about a user. You might ask about those users who have their cookies turned off. Well, that’s not a problem since PHP 4.2.0, because it will identify when this is the case and place a cookie token in the GET portion of each URL request instead. Either way, sessions provide a solid way of keeping track of your users.
  • 1080.
    Starting a SessionStarting a session requires calling the PHP function session_start before any HTML has been output, similarly to how cookies are sent during header exchanges. Then, to begin saving session variables, you just assign them as part of the $_SESSION array, like this:
  • 1081.
  • 1082.
    They can thenbe read back just as easily in later program runs, like this:
  • 1083.
  • 1084.
    Setting a sessionafter successful authentication
  • 1085.
  • 1086.
  • 1087.
    $db_server = mysql_connect($db_hostname,$db_username, $db_password);
  • 1088.
    if (!$db_server) die(&quot;Unableto connect to MySQL: &quot; . mysql_error());
  • 1089.
    mysql_select_db($db_database) ordie(&quot;Unable to select database: &quot; . mysql_error());
  • 1090.
  • 1091.
  • 1092.
  • 1093.
  • 1094.
  • 1095.
    $query = &quot;SELECT* FROM users WHERE username='$un_temp'&quot;; $result = mysql_query($query); if (!$result) die(&quot;Database access failed: &quot; . mysql_error()); elseif (mysql_num_rows($result)) { $row = mysql_fetch_row($result); $salt1 = &quot;qm&h*&quot;; $salt2 = &quot;pg!@&quot;; $token = md5(&quot;$salt1$pw_temp$salt2&quot;);
  • 1096.
    if ($token ==$row[3]) { session_start(); $_SESSION['username'] = $un_temp; $_SESSION['password'] = $pw_temp; $_SESSION['forename'] = $row[0]; $_SESSION['surname'] = $row[1]; echo &quot;$row[0] $row[1] : Hi $row[0], you are now logged in as '$row[2]'&quot;; die (&quot;<p><a href=continue.php>Click here to continue</a></p>&quot;); }
  • 1097.
    else die(&quot;Invalid username/passwordcombination&quot;); } else die(&quot;Invalid username/password combination&quot;); } else { header('WWW-Authenticate: Basic realm=&quot;Restricted Section&quot;'); header('HTTP/1.0 401 Unauthorized'); die (&quot;Please enter your username and password&quot;); }
  • 1098.
    function mysql_entities_fix_string($string) {return htmlentities(mysql_fix_string($string)); } function mysql_fix_string($string) { if (get_magic_quotes_gpc()) $string = stripslashes($string); return mysql_real_escape_string($string); } ?>
  • 1099.
    Retrieving session variables<?php // continue.php session_start(); if (isset($_SESSION['username'])) { $username = $_SESSION['username']; $password = $_SESSION['password']; $forename = $_SESSION['forename']; $surname = $_SESSION['surname']; echo &quot;Welcome back $forename.<br /> Your full name is $forename $surname.<br /> Your username is '$username' and your password is '$password'.&quot;; } else echo &quot;Please <a href=authenticate2.php>click here</a> to log in.&quot;; ?>
  • 1100.
    Ending a SessionWhen the time comes to end a session, usually when a user requests to log out from your site, you can use the session_destroy function in association with the unset function
  • 1101.
    A handy functionto destroy a session and its data
  • 1102.
  • 1103.
  • 1104.
  • 1105.
  • 1106.
  • 1107.
    if (session_id() !=&quot;&quot; || isset($_COOKIE[session_name()]))
  • 1108.
  • 1109.
  • 1110.
  • 1111.
  • 1112.
    Setting a timeoutThere are other times when you might wish to close a user’s session yourself, such as when the user has forgotten or neglected to log out, and you wish the program to do it for them for their own security. The way to do this is to set the timeout, after which a logout will automatically occur if there has been no activity.
  • 1113.
    To do this,use the ini_set function as follows. This example sets the timeout to exactly one day:
  • 1114.
  • 1115.
    If you wishto know what the current timeout period is, you can display it using the following:
  • 1116.