You are on page 1of 636

IntelliBitz Technologies

Training Division
168, Medavakkam Main Road
Madipakkam, Chennai 91.
PH: +91 044 2247 5106
www.intellibitz.com
training@intellibitz.com
www.intellibitz.com                                                                                                                          training@intellibitz.com

PHP WEB
PROGRAMMING.

www.intellibitz.com                                                                                                                          training@intellibitz.com

CHAPTER 1

STARTING WITH PHP.

www.intellibitz.com                                                                                                                          training@intellibitz.com

PHP First Steps - Overview

PHP and the WWW

PHP as a server-side language

What's so great about PHP?

PHP in action

PHP basics

www.intellibitz.com                                                                                                                          training@intellibitz.com

PHP and the Web

www.intellibitz.com Is typed in firefox

Firefox sends a message over the internet to the computer
named www.intellibitz.com

Apache, a program running on www.intellibitz.com, gets the
message and asks the PHP interpreter, another program
running on the www.intellibitz.com computer, “what
does /index.php look like?”

www.intellibitz.com                                                                                                                          training@intellibitz.com

PHP and the Web

The PHP interpreter reads the file /var/www/html/index.php
from disk drive

The PHP interpreter runs the commands in index.php,
possibly exchanging data with a database program such
as MySQL

The PHP interpreter takes the index.php program output
and sends it back to Apache as answer

www.intellibitz.com                                                                                                                          training@intellibitz.com

PHP and the Web

Apache sends the page contents it got from the PHP
interpreter back to your computer over the Internet in
response to Firefox

Firefox displays the page on the screen, following the
instructions of the HTML tags in the page

www.intellibitz.com                                                                                                                          training@intellibitz.com

PHP – a server-side language

PHP runs on the web server

Javascript and Flash in contrast, are client-side because
they run on a web client

The instructions in a PHP program cause the PHP
interpreter on a web server to output a web page. The
instructions in Javascript cause Firefox to run browser
commands.

www.intellibitz.com                                                                                                                          training@intellibitz.com

What's So Great About PHP?

PHP is free

PHP is cross-platform

PHP is widely used

PHP hides its complexity

PHP is built for Web Programming

www.intellibitz.com                                                                                                                          training@intellibitz.com

PHP in action

The PHP interpreter runs the commands between <?php ?
> tags

PHP processing form data via $_POST

String syntax called a 'here document'

Using PHP internal library functions like number_format ()

Displaying infromation from a database

www.intellibitz.com                                                                                                                          training@intellibitz.com

Basic Rules of PHP Programs

Start and End Tags

Whitespace and Case-Sensitivity

Comments

www.intellibitz.com                                                                                                                          training@intellibitz.com

Chapter Summary

PHP's usage by a web server to create a response to send
back to browser

PHP as a server-side language, contrasting with a
Javascript a client-side language

PHP is free, cross-platform, widely-used

PHP basics, program structure, process form, and talk to
databases

www.intellibitz.com                                                                                                                          training@intellibitz.com

intellibitz.com .com                                                                                                                          training@intellibitz. CHAPTER 2 TEXT AND NUMBERS www.

com .intellibitz.com                                                                                                                     training@intellibitz. Working with Text and Numbers ● Defining Text Strings ● Validating and formatting text ● Manipulating Text ● Numbers ● Arithmetic Operators ● Variables ● Putting variables inside strings www.

single quotes are delimiters ● Backslash \ to be used for escaping ● The escape character can itself be escaped www.com                                                                                                                     training@intellibitz.intellibitz.. Text ● Pieces of text are called strings ● String can even contain binary file such as image or sound ● String is surrounded by a single quotes.com .

com . ● Here documents obey the same escape-character and variable substitution rules ● Use a . www.intellibitz.This is called as variable interpolation. Defining Text Strings ● Variable names in a double-quoted string will be substituted with its value. (period) to combine two strings.com                                                                                                                     training@intellibitz. is the cancatenation.The .

use the equality operator (==) ● Use strcasecmp () to compare strings ignoring case www. Manipulating Text ● Validating string using trim () and strlen () ● To compare two strings.com                                                                                                                     training@intellibitz.com .intellibitz.

Formatting Text ● Use printf () with a format string and the items to print ● Zero-padding. ucwords ().com                                                                                                                     training@intellibitz. strtoupper ().ucfirst() substr ().intellibitz. str_replace () www.com . displaying signs with printf () ● Use of strtolower ().

● $trimStr = trim($string).com                                                                                                                     training@intellibitz.$full).intellibitz. String Functions.$new. ● Join() alias of implode(). ● $length = strlen($string). ● $str = implode($separator.$arrayStr). ● $resultStr = str_replace($old. www. ● $arrayStr = explode($separator.com .$string).

$n) ● $string is repeated $n times and returned as string.com                                                                                                                     training@intellibitz. ● This function returns an array comprising the characters that make up the string. ● str_word_count ● Return information about words used in a string www. ● $array= str_split($string). String Functions ● $padded = str_pad ($string. ● $repeat = str_repeat($string.intellibitz.$length) ● The returned string is atleast $length characters long.com .

● If $length is negative . String functions ● $substring = substr($string.com .$length) ● The portion of the string starting from the $n th character for $length number of character is returned. www.com                                                                                                                     training@intellibitz.that many characters will be omitted from end of the string.$n.intellibitz. ● If $n is negative the substring wil start that many characters from end of the string.

comparison is case insensitive. > 0 if it is greater than str.intellibitz. int $offset [.com . ● If case_insensitivity is TRUE. www. substr_compare() prints warning and returns FALSE. If length is equal or greater than length of main_str and length is set. int $length [. and 0 if they are equal. string $str. String functions ● substr_compare ● int substr_compare ( string $main_str. – Returns < 0 if main_str from position offset is less than str.com                                                                                                                     training@intellibitz. bool $case_insensitivity]] ) – substr_compare() compares main_str from position offset with str up to length characters.

String functions ● substr_replace ● mixed substr_replace ( mixed $string. int $offset [. int $start [. string $replacement.com . int $length]] ) – substr_count() returns the number of times the needle substring occurs in the haystack string. int $length] ) – Replace text within a portion of a string ● substr_count ● int substr_count ( string $haystack. Please note that needle is case sensitive.com                                                                                                                     training@intellibitz. www.intellibitz. string $needle [.

● strcmp($string1.strtoupper() ● Converts the case to lower and upper respectively. String functions.$string2) ● Returns 0 if both are equal ● Returns positive int if first string has higher ASCII value.intellibitz. ● Returns negative int if second string has higher ASCII value. ● similar_text (string $first.com .string $second ● Calculate the similarity between two strings – It returns the number matching characters in both string www.com                                                                                                                     training@intellibitz. ● strtolower().

$format). ● The returned array contains each extracted value from the string according to the specified format. ● $found = strpbrk($string.$characters) ● The string is scanned for any of the characters. ● $array = sscanf($string.com .if match is found it returns a string starting from the character it just matched to end of the string. ● The $format argument returns how the subsequent arguments are printed.intellibitz.$var1..). String functions ● printf($format..$var2.com                                                                                                                     training@intellibitz. www.

strnatcasecmp(). ● $res= strpos($bigstring.Chop is alias of rtrim ● string chr ( int $ascii ) ● Returns a one-character string containing the character specified by ascii www.stripos().$search) ● The function returns the position of the $search string in $bigstring ● rtrim().com                                                                                                                     training@intellibitz. String functions.intellibitz.com .str_ireplace(). strrpos().strcasecmp().ltrim(). strnatcmp().

string $from.com .com                                                                                                                     training@intellibitz. int $chunklen [. string $to ) www.intellibitz. string $end]] ) ● string convert_cyr_string ( string $str. String functions ● strrev Reverse a string ● ● chunk_split — Split a string into smaller chunks ● string chunk_split ( string $body [.

com . returns FALSE. ● Stristr() .case insensitive ● Strchr ● Alias of strstr() www. ● If needle is not a string.intellibitz. string $needle ) ● Returns part of haystack string from the first occurrence of needle to the end of haystack.com                                                                                                                     training@intellibitz. ● If needle is not found. it is converted to an integer and applied as the ordinal value of a character. String functions ● strstr ● Find first occurrence of a string – string strstr ( string $haystack.

string $from.intellibitz.com                                                                                                                     training@intellibitz.com . www. String functions ● Strtok() ● string strtok ( string $str. ● Strtr() ● string strtr ( string $str. translating all occurrences of each character in from to the corresponding character in to. string $to ) – This function returns a copy of str. string $token ) – strtok() splits a string (str) into smaller strings (tokens). with each token being delimited by any character from token.

String functions ● strcspn ● int strcspn ( string $str1.intellibitz. ● Strcoll Locale based string comparison ● ● If the current locale is C or POSIX. this function is equivalent to strcmp(). int $start [. www.com                                                                                                                     training@intellibitz. ● Note that this comparison is case sensitive. string $str2 [. and unlike strcmp() this function is not binary safe.com . int $length]] ) ● Find length of initial segment not matching mask ● Returns the length of the initial segment of str1 which does not contain any of the characters in str2.

com                                                                                                                     training@intellibitz. if one of the argument strings is longer than the limit of 255 characters.com . String functions ● convert_uuencode(). ● Levenshtein () – Calculate Levenshtein distance between two strings or -1. www.convert_uudecode().intellibitz. ● str_rot13 ● Perform the rot13 transform on a string ● The ROT13 encoding simply shifts every letter by 13 places in the alphabet while leaving non-alpha characters untouched.

double quote (").com .intellibitz.com                                                                                                                     training@intellibitz. These characters are single quote ('). backslash (\) and NUL (the NULL byte). stripslashes().stripcslashes(). String functions ● string addslashes ( string $str ) ● Returns a string with backslashes before characters that need to be quoted in database queries etc. ● str_shuffle ● Randomly shuffles a string ● str_split ● Convert a string to an array www. ● addcslashes().

com . ● charset-ISO-8859-1. ● ENT_QUOTES Will convert both double and single quotes. www.ISO-8859-15.intellibitz. string $charset]] ) ● Convert all applicable characters to HTML entities ● ENT_COMPATWill convert double-quotes and leave single-quotes alone. int $quote_style [.com                                                                                                                     training@intellibitz. ● ENT_NOQUOTES Will leave both double and single quotes unconverted. String functions ● string htmlentities ( string $string [.UTF-8.

● This function returns a string with some of these conversions made ● '&' (ampersand) becomes '&amp.' ● '>' (greater than) becomes '&gt.' when ENT_NOQUOTES is not set.com . String functions ● Htmlspecialchars() ● Convert special characters to HTML entities. ● '<' (less than) becomes '&lt.intellibitz. ● ''' (single quote) becomes '&#039.' only when ENT_QUOTES is set.com                                                                                                                     training@intellibitz.' ● '"' (double quote) becomes '&quot.' www.

It converts special HTML entities back to characters.Returns the decoded string.com                                                                                                                     training@intellibitz. String functions htmlspecialchars_decode ● – Convert special HTML entities back to characters – string htmlspecialchars_decode ( string $string [. ● nl2br – Inserts HTML line breaks before all newlines in a string – Returns string with '<br />' inserted before all newlines.com .intellibitz. int $quote_style] ) – This function is the opposite of htmlspecialchars(). ● strip_tags – Strip HTML and PHP tags from a string www.

The hash is a 32-character hexadecimal number. MD5 Message-Digest Algorithm. and returns that hash.com                                                                                                                     training@intellibitz. String functions ● md5($string) Calculates the md5 hash of a given string ● using RSA Data Security.com . ● sha1 ● Calculate the sha1 hash of a string www. ● md5_file($filename) ● md5_file — Calculates the md5 hash of a given file.intellibitz. Inc.

com . String functions ● soundex ● Calculate the soundex key of a string – Soundex keys have the property that words pronounced similarly produce the same soundex key.intellibitz. www. starting with a letter. – This soundex function returns a string 4 characters long.com                                                                                                                     training@intellibitz. and can thus be used to simplify searches in databases where you know the pronunciation but not the spelling.

intellibitz. ● money_format ● Formats a number as a currency string ● number_format ● Format a number with grouped thousands www.com                                                                                                                     training@intellibitz. ● – Similar to soundex() metaphone creates the same key for similar sounding words.com . String functions ● Metaphone Calculate the metaphone key of a string. The metaphone generated keys are of variable length. – It's more accurate than soundex() as it knows the basic rules of English pronunciation.

intellibitz. String functions ● ord ● Return ASCII value of character ● parse_str Parses the string into variables ● ● quoted_printable_decode ● Convert a quoted-printable string to an 8 bit string www.com                                                                                                                     training@intellibitz.com .

com .com                                                                                                                     training@intellibitz. www.\+*?[^]($) ● Note: This function is binary-safe. String functions ● quotemeta ● Quote meta characters ● string quotemeta ( string $str ) ● Returns a version of str with a backslash character (\) before every character that is among these: –.intellibitz.

www.com                                                                                                                     training@intellibitz.com . ● sprintf ● Return a formatted string ● str_getcsv ● Parse a CSV string into an array. always. Returns 1. String functions ● print ● Output a string ● int print ( string $arg ) ● Outputs arg. – print() is not actually a real function (it is a language construct) so you are not required to use parentheses with its argument list.intellibitz.

com                                                                                                                     training@intellibitz. int $width [. String functions ● wordwrap Wraps a string to a given number of characters – using a string break character ● string wordwrap ( string $str [. bool $cut]]] ) – Returns a string with str wrapped at the column number specified by the optional width parameter. So if you have a word that is larger than the given width. – wordwrap() will automatically wrap at column 75 and break using '\n' (newline) if width or break are not given. the string is always wrapped at the specified width.com . The line is broken using the (optional) break parameter. – If the cut is set to 1.intellibitz. it is broken apart www. string $break [.

com .intellibitz. String functions ● vfprintf ● Write a formatted string to a stream ● vprintf ● Output a formatted string ● vsprintf ● Return a formatted string – string vsprintf ( string $format. array $args ) www.com                                                                                                                     training@intellibitz.

● c . and presented as an unsigned decimal number. ● d . Type specifiers ● type specifier that says what type the argument data should be treated as.g. ● u .a literal percent character. No argument is required. ● X .the argument is treated as a float. and presented as a binary number. ● f . and presented as an octal number.intellibitz. 1.3. ● x . ● b .the argument is treated as an integer and presented as a hexadecimal number (with uppercase letters). www.2e+2).the argument is treated as an integer. and presented as a floating-point number (locale aware).the argument is treated as an integer.com                                                                                                                     training@intellibitz.the argument is treated as an integer. and presented as the character with that ASCII value. ● e . ● s .3. Available since PHP 4.the argument is treated as an integer and presented as a hexadecimal number (with lowercase letters).com .the argument is treated as and presented as a string.10 and PHP 5.the argument is treated as scientific notation (e. Possible types: ● % . ● F . ● o .the argument is treated as an integer.the argument is treated as a float.the argument is treated as an integer.0. and presented as a (signed) decimal number. and presented as a floating-point number (non- locale aware).

Numbers ● Numbers – floating point and decimals ● Arithmetic operators ● +.com                                                                                                                     training@intellibitz. /. % ● Operator precedence ● Grouping operations inside parentheses.intellibitz.com . -. will execute whats inside the parentheses first www. *.

Variables ● In PHP.com .com                                                                                                                     training@intellibitz. variables are denoted by $ followed by the variable's name ● Use = to assign value to a variable ● Variable names must begin with letter or an underscore ● Variable names are case-sensitive ● Avoid variable names differ by letter case ● Avoid using variable names as function names.intellibitz. www.

intellibitz.=.com . Operating on Variables ● Arithmetic and string operators work on variables just as they do on literals ● Operator followed by = means “apply this operator to the variable” ● +=. ++.com                                                                                                                     training@intellibitz. -- ● Variable interpolation and curly braces www. .

intellibitz. ● $root = sqrt($number) www.com                                                                                                                     training@intellibitz. ● $result = pow($number.$pow). ● % called modulus operator. ● $remainder = $dividend % $divisor.com . This function must be used instead.returns the remainder. ● PHP does not have power operator. Number functions ● $absvalue = abs($number) ● If $number is negative the value returned is positive.

www.intellibitz. Number functions ● $ceilinged = ceil($number). ● The function rounds the number to the nearest whole number.com . ● $floored = floor($number). ● Rounds a fractional number up to next integer.com                                                                                                                     training@intellibitz. ● Same as ceil but returned value is still a float type ● $rounded = round($number).

● $minimum = min($array).$max) ● Generates random numbers between $min and $max www. Number functions ● $maximum = max ($array).to a number in any other base. $newbase).com                                                                                                                     training@intellibitz.intellibitz.$oldbase. ● $newNumber = base_convert($number. up to base 36.com .again upto base 36. ● $result = rand($min. ● This function converts a number in any base .

intellibitz. ● This function returns the logarithm of the specified number to the base provided. ● $result = log($number.com . www. ● The function returns the natural base 'e' raised to the specified power.$base).com                                                                                                                     training@intellibitz. Number functions ● $result = exp($power).

com .sinh. Number functions ● sin.cos.atanh. acosh.com                                                                                                                     training@intellibitz.asinh.float $x) ● This function calculates the arc tangent of the two variables x and y.asin.acos. except that the signs of both arguments are used to determine the quadrant of the result.cosh. ● Float atan2(float $y. ● The function returns the result in radians.tanh. which is between -PI and PI (inclusive).intellibitz. www.tan.atan. It is similar to calculating the arc tangent of y / x.

is_infinite. Combined linear congruential generator. ● is_finite.com . ● deg2rad. ● float lcg_value ( void ) ● lcg_value() returns a pseudo random number in the range of (0.decbin.is_nan.hypot.decoct. ● fmod.com                                                                                                                     training@intellibitz.rad2deg.pi. www. 1).intellibitz. Number functions ● dechex.

The mt_rand() uses a random number generator with known characteristics using the » Mersenne Twister.intellibitz. which will produce random numbers four times faster than what the average libc rand() provides.com .com                                                                                                                     training@intellibitz. www. PHP uses the libc random number generator with the rand() function. Number functions ● mt_rand() ● By default.

com . Chapter Summary ● Defining strings in 3 different ways: single quotes. double quotes. removing leading and trailing whitespace ● Formatting string with printf () www.com                                                                                                                     training@intellibitz. and a here document ● Escaping: what it is and what characters need to be escaped in each kind of string ● Validating a string by checking its length.intellibitz.

strtoupper () or ucwords () ● Selecting part of a string with substr () ● Changing part of a string with str_replace () ● Defining numbers in your programs ● Doing math with numbers ● Storing values in variables www.com                                                                                                                     training@intellibitz.intellibitz. Chapter Summary ● Manipulating the case of string with strtolower ().com .

intellibitz.com .com                                                                                                                     training@intellibitz. Chapter Summary ● Naming variables appropriately ● Using combined operators with variables ● Using increment and decrement operators with variables ● Interpolating variables in strings www.

CHAPTER 3 Making Decisions and Looping www.com                                                                                                                     training@intellibitz.intellibitz.com .

Making Decisions and Looping ● Understanding true and false ● Making Decisions ● Building Complicated Decisions ● Repeating Yourself www.com .com                                                                                                                     training@intellibitz.intellibitz.

Understanding true and false ● All expression in PHP program has a truth value: true or false ● Most scalar values are true.0) are true ● All strings are true except for two: an empty string and the string containing only 0 ● An empty array is false www.intellibitz.com                                                                                                                     training@intellibitz. All integers and floating point (except 0 and 0.com .

com ..intellibitz. a conditional statement or even a statement that does nothing (an empty statement). ● A statement-group is a statement by itself as well. www. ● Statements usually end with a semicolon.}. ● In addition. a loop. Control statements ● Any PHP script is built out of a series of statements. statements can be grouped into a statement-group by encapsulating a group of statements with curly braces {.. ● A statement can be an assignment. a function call.com                                                                                                                     training@intellibitz.

com . to run different statements when the test expression is false ● use elseif() with if() to test manyconditions ● For a given set of if() and elseif() statements.com                                                                                                                     training@intellibitz. Making Decisions ● If () construct runs a block of code if its test expression is true ● Add an else to if() statement. at most one of the code blocks is run www.intellibitz.

if (expr) statement www. ● PHP features an if structure that is similar to that of C: ● The expression is evaluated to its Boolean value.com                                                                                                                     training@intellibitz. and if it evaluates to FALSE . If statement ● it allows for conditional execution of code fragments.it'll ignore it.intellibitz. PHP will execute statement. If expression evaluates to TRUE.com .

   $b = $a. <?php ● If statements can be nested indefinitely if ($a > $b) within other if statements. which provides you with complete flexibility for { conditional execution of the various    echo "a is bigger than b".com                                                                                                                     training@intellibitz. you    echo "a is bigger than b". Instead. If statements ● Often you'd want to have more than one <?php statement to be executed conditionally. } ?> www.com . if ($a > $b) ● In such case there's no need to wrap each statement with an if clause.intellibitz. parts of your program. can group several statements into a ?> statement group.

● else extends an if statement to execute } else { a statement in case the expression in the if statement evaluates to FALSE. If else statement ● Often you'd want to execute a statement <?php if a certain condition is met.com                                                                                                                     training@intellibitz. ● The else statement is only executed if } the if expression evaluated to FALSE.com .    echo "a is NOT bigger than b". ?> and if there were any elseif expressions . and a if ($a > $b) { different statement if the condition is not met.only if they evaluated to FALSE this else is executed www.    echo "a is bigger than b". This is what else is for.intellibitz.

if ($a > $b) { ● It extends an if statement to execute a different statement in case the original if    echo "a is bigger than b".intellibitz.    echo "a is smaller than b". it will execute that alternative expression only if the elseif    echo "a is equal to b". as its name suggests. conditional expression evaluates to } else { TRUE. expression evaluates to FALSE.com                                                                                                                     training@intellibitz. else if ● elseif. is a <?php combination of if and else. unlike else.com . } ?> www. } elseif ($a == $b) { ● However.

The syntactic meaning is slightly different (if you're familiar with C. this is the same behavior) but the bottom line is that both would result in exactly the same behavior.intellibitz. you can also write 'else if' (in two words) and the behavior would be identical to the one of 'elseif' (in a single word).com                                                                                                                     training@intellibitz. www. The first elseif expression (if any) that evaluates to TRUE would be executed.com . and the current elseif expression evaluated to TRUE. ● In PHP. ● The elseif statement is only executed if the preceding if expression and any preceding elseif expressions evaluated to FALSE. elseif statement ● There may be several elseifs within the same if statement.

com                                                                                                                     training@intellibitz. this value changes during the execution of the nested statement(s). increment) */ ?> www. while() ● While statements tells PHP to execute the nested while (expr) statement(s) repeatedly. execution will not stop while ($i <= 10) { until the end of the iteration (each time PHP    echo $i++.com . so even if $i = 1. if the while expression evaluates to /* the printed value would be $i  FALSE from the very beginning. as long as the while statement expression evaluates to TRUE.  runs the statements in the loop is one iteration). } ● Sometimes. the nested before the increment (post­ statement(s) won't even be run once. ● The value of the expression is checked each <?php time at the beginning of the loop.intellibitz.

<?php except the truth expression is checked at the $i = 0.intellibitz. guaranteed to run as the truth expression is only checked at the end of the iteration). } while ($i > 0). ● The main difference from regular while loops is that do { the first iteration of a do-while loop is    echo $i. do while ● do-while loops are very similar to while loops. if it evaluates to FALSE right from the beginning.com                                                                                                                     training@intellibitz. end of each iteration instead of in the beginning. ● whereas it's may not necessarily run with a regular ?> while loop the truth expression is checked at the beginning of each iteration.com . the loop execution would end immediately. www.

test condition. } ● At the end of each iteration. increment value is evaluated (executed). for ($i = 1. test condition statement is checked.intellibitz. execution of the loop ends. $i++) {    if ($i > 10) {        break. increment value) ● In the beginning of each iteration. for statement ● A variable can be initialised once for (initialise. the  echo $i.com                                                                                                                     training@intellibitz. .com . If it evaluates to TRUE.    }    echo $i. } www. the loop continues and the nested statement(s) are for ($i = 1. If it evaluates to FALSE. $i <= 10. unconditionally at the beginning of the loop. $i++) { executed.

com                                                                                                                     training@intellibitz. since often you'd want to end the loop using } a conditional break statement instead of for ($i = 1. ● This may not be as useless as you might think.intellibitz. contain multiple expressions separated by commas. for loop ● Each of the expressions can be empty or $i = 1. www.    $i++. for (. precedence than ||. ) { ● Comma separated expressions in test    if ($i > 10) { condition are treated similarly to being separated by the || operator but has a lower        break. $j  using the for truth expression. += $i. $i <= 10. $i++). .com . expr2 being empty    } means the loop should be run indefinitely (PHP implicitly considers it as TRUE. print $i. $j = 0. C). like    echo $i.

foreach loop ● PHP 4 introduced a foreach construct.com .com                                                                                                                     training@intellibitz. ● foreach works only on arrays. and will issue an error when you try to use it on a variable with a different data type or an uninitialized variable. ● There are two syntaxes.intellibitz. much like Perl ● This simply gives an easy way to iterate over arrays. the second is a minor but useful extension of the first: foreach (array_expression as $value) statement foreach (array_expression as $key => $value) statement www.

This will assign reference instead of copying the value. 4). 3. the internal array pointer is advanced by one foreach ($arr as &$value) { (so on the next loop. On each loop. ● The second form does the same thing.com . 2. 6. you'll be looking at the next element). 4.com                                                                                                                     training@intellibitz. except } that the current element's key will be assigned to the variable $key on each loop. // $arr is now array(2.intellibitz. foreach ● The first form loops over the array given by array_expression. } ?> www. 8) ● you can easily modify array's elements by foreach($arr as $key =>$val){ preceding $value with &. the value of <?php the current element is assigned to $value and $arr = array(1.    $value = $value * 2. print”$key=$val”.

● Unless the array is referenced.com                                                                                                                     training@intellibitz. www. the internal array pointer is automatically reset to the first element of the array.com . foreach ● When foreach first starts executing.intellibitz. foreach operates on a copy of the specified array and not the array itself. This means that you do not need to call reset() before a foreach loop.

 */ be broken out of.    } www.        break 2. foreach. do-while or    switch ($i) { switch structure.  /* Exit the switch and the  while.com                                                                                                                     training@intellibitz.intellibitz. argument which tells it how many nested enclosing structures are to        break 1.    case 10:        echo "At 10. break $i = 0.com } . quitting<br />\n". */    default:        break.  /* Exit only the switch. while.    case 5: ● break accepts an optional numeric        echo "At 5<br />\n".       while (++$i) { ● break ends execution of the current for.

com                                                                                                                     training@intellibitz. ● Note that in PHP the switch        while (1) { statement is considered a looping            echo "Inner<br />\n". } www.<br />\n". execution at the condition    while (1) { evaluation and then the beginning of the next iteration. structure for the purposes of continue. ● continue is used within looping while ($i++ < 5) { structures to skip the rest of the current loop iteration and continue    echo "Outer<br />\n".        echo "Middle<br />\n". ● continue accepts an optional numeric        } argument which tells it how many levels of enclosing loops it should   echo "This never gets output.<br />\n".    }    echo "Neither does this. skip to the end of. continue $i = 0.            continue 3.intellibitz.com .

   echo "i equals 0".com                                                                                                                     training@intellibitz. use continue 2.com ?> . depending on which value it equals to. next iteration of the outer loop. you may want to case 0: compare the same variable (or expression) with many different values. switch <?php ● The switch statement is similar to a series of IF statements on the same expression.    break. In switch ($i) { many occasions.intellibitz. If you have a switch case 2: inside a loop and wish to continue to the    echo "i equals 2". ● Note that unlike some other languages. continue statement applies to switch and acts similar to break. the    break. and execute a different piece of code    break.    echo "i equals 1". } www. This is exactly what the switch statement case 1: is for.

com                                                                                                                     training@intellibitz. until the end of the switch block. Only when a case statement is found with a case 0: value that matches the value of the switch    echo "i equals 0". statements to avoid mistakes. } ?> www.com . switch ● The switch statement executes line by line ?php (actually. or the first time it sees a break statement. expression does PHP begin to execute the statements. statement by statement). it is important not to forget break    echo "i equals 2". switch ($i) { ● In the beginning. no code is executed.intellibitz. case 2: ● Thus. case 1: ● PHP continues to execute the statements    echo "i equals 1".

   echo "a is neither 5 nor 6". the basic form of the alternate elseif ($a == 6): syntax is to change the    echo "a equals 6". endwhile. switch.com .".. else: endfor. namely.. foreach. if. opening brace to a colon (:) and the closing brace    echo "!!!".. to endif. respectively.. ?> www. ?>    echo ".intellibitz.    echo "a equals 5". for. or endswitch. In each case. endif. Alternative syntax <?php ● PHP offers an alternative <?php if ($a == 5): ?> syntax for some of its if ($a == 5): A is equal to 5 control structures. endforeach... and <?php endif. while..com                                                                                                                     training@intellibitz.

intellibitz.com . ● Eval() evaluates the string as PHP code.com                                                                                                                     training@intellibitz. ● return() will also end the execution of an eval() statement or script file. www. return ● If called from within a function. the return() statement immediately ends execution of the current function. and returns its argument as the value of the function call.

www. of course. but the result of the expression ($a) (which is. not the result of a statement.intellibitz. You can only return variables by reference. It is common to leave them out.com . If you use return ($a). return ● Note that since return() is a language construct and not a function. and you actually should do so as PHP has less work to do in this case. as this will not work. the value of $a). ● You should never use parentheses around your return variable when returning by reference.com                                                                                                                     training@intellibitz. then you're not returning a variable. the parentheses surrounding its arguments are not required.

require ('somefile. require $somefile.intellibitz. require() ● The require() statement includes <?php and evaluates the specific file. – Require() includes and require 'prepend.com                                                                                                                     training@intellibitz.php'.txt').com . evaluates a specific file. ?> www.

● use require() if you want a missing file to halt processing of the page.com . include() ● The include() statement includes and evaluates the specified file. www.intellibitz. the script will continue regardless. but require() results in a Fatal Errorand stops execution.com                                                                                                                     training@intellibitz. ● include() does not behave this way. ● They both produce a Warning. ● The difference between include() and require() The two constructs are identical in every way except how they handle failure.

with the only difference being that if the code from a file has already been included. ● require_once() should be used in cases where you want to be sure that it is included exactly once to avoid problems with function redefinitions. etc. require_once() ● This is a behavior similar to the require() statement.intellibitz. variable value reassignments.com                                                                                                                     training@intellibitz. it will not be included again.com . www.

php").php"). // this will include a.php require_once("A.com . that the behaviour of require_once() and include_once() may not be what you expect on a non case sensitive operating system (such as Windows).com                                                                                                                     training@intellibitz. // this will include  a. require_once() ● Be aware. <?php require_once("a.php //again on Windows! (PHP 4 only) ?> www.intellibitz.

com                                                                                                                     training@intellibitz. it will not be included again. include_once() ● This is a behavior similar to the include() statement. www. with the only difference being that if the code from a file has already been included.intellibitz.com .

com . ● The value for N is specified using ticks=N declare(ticks=1) { within the declare blocks's directive    // entire script here section. ● The event(s) that occur on each tick are } specified using the // or you can use this: register_tick_function() declare(ticks=1). The syntax of declare is similar to the <?php syntax of other flow control constructs ● A tick is an event that occurs for every N // these are the same: low-level statements executed by the // you can use this: parser within the declare block. declare ● The declare construct is used to set declare (directive) statement execution directives for a block of code. // entire script here ?> www.com                                                                                                                     training@intellibitz.intellibitz.

● This information can then be used to find the slow areas within particular segments of code.com .intellibitz. recording the time at which every second low- level statement in the block was executed. ticks ● The example profiles the PHP code within the 'declare' block. www. ● This process can be performed using other methods: using ticks is more convenient and easier to implement.com                                                                                                                     training@intellibitz.

function profile($dump = FALSE) // Initialize the function before the declare block { profile(). <?php ticks // Set up a tick handler // A function that records the time when it is called register_tick_function("profile"). ++$x) {        unset($profile).com ?> .    static $profile. // Run a block of code.". echo similar_text(md5($x). $x < 50. throw a tick every    // Return the times stored in profile.  for ($x = 1. then erase it 2nd statement    if ($dump) { declare(ticks=2) {        $temp = $profile.    }    } } $profile[] = microtime().        return $temp. www. "<br />.intellibitz. md5($x*$x)).com                                                                                                                     training@intellibitz. // Display the data stored in the profiler } print_r(profile(TRUE)).

com .com                                                                                                                     training@intellibitz. Building Complicated Decisions ● Complicated expressions can be put together with comparison and logical operators ● Beware of assignment versus comparison ● Beware of floating-point comparison ● Strings are compared like dictionary lookup ● Beware of strings containing numbers ● Use strcmp() to compare like dictionary for strings containing numbers www.intellibitz.

com                                                                                                                     training@intellibitz.com . its called looping ● Use while().intellibitz. for(). foreach() for looping ● Multiple expression in for() is allowed but only one test expression is possible www. Repeating Yourself ● When a program does something repeatedly.

elseif(). Chapter Summary ● Evaluating an expression's truth value: true or false ● Making a decision with if().com                                                                                                                     training@intellibitz. ● Extending if() with else ● Extending if() with elseif() ● Putting multiple statements inside an if().com .intellibitz. or else code block www.

less-than-or- equal-to (<=). ● Distinguishing between assignment (=) and equality comparison (==) ● Using the less-than (<). Chapter Summary ● Using the equality (==) and not-equals (!=) operators in test expressions.com . and greater-than-or-equal-to (>=) operators in test expressions www.com                                                                                                                     training@intellibitz.intellibitz. greater-than (>).

com                                                                                                                     training@intellibitz. Chapter Summary ● Comparing two floating-point numbers with abs() ● Comparing two strings with operators ● Comparing two strings with strcmp() or strcasecmp() ● Using the negation operator (!) in test expressions www.com .intellibitz.

Chapter Summary ● Using the logical operators (&& and ||) to build more complicated test expressions ● Repeating a code block with while () ● Repeating a code block with for () www.com                                                                                                                     training@intellibitz.com .intellibitz.

com .intellibitz. CHAPTER 4 WORKING WITH ARRAYS www.com                                                                                                                     training@intellibitz.

com .intellibitz.com                                                                                                                     training@intellibitz. Working with Arrays ● Creating an Array ● Creating a Numeric Array ● Looping through Arrays ● Modifying Arrays ● Sorting Arrays ● Using Multidimensional Arrays www.

number. it can also be another array www.com                                                                                                                     training@intellibitz. Only one element with a given key can exist.com . true or false. Array Basics and Creation ● An array is made up of elements.intellibitz. Each element has a key and a value. ● Any string or number can be the key ● An element value can be string.

com . specify a comma-delimited list of key/value pairs ● Beware of array and scalar name collision www. Creating an Array ● Assign a value to a particular array key to create an array ● Use array() language construct ● With array().intellibitz.com                                                                                                                     training@intellibitz.

com . instead of key/value pairs ● String keyed arrays are associative arrays ● PHP automatically uses incrementing numbers for array keys when array creation or add elements with empty brackets syntax ● Use count() to find the size of an array www.com                                                                                                                     training@intellibitz. Creating a Numeric Array ● Use array() with only a list of values.intellibitz.

Looping through Arrays ● Use foreach() to run a code block once for each element in the array ● Changing the loop variables like $key and $value inside foreach() doesn't affect array ● Inside foreach().intellibitz.com                                                                                                                     training@intellibitz.com . the elements are accessed in the order they were added to the array ● Use for() to access elements in numerical key order www.

com .com                                                                                                                     training@intellibitz.intellibitz. Looping through Arrays ● Use array_key_exists(). to check for an element with a certain key ● Use in_array(). to check for an element with a particular value ● in_array is case-sensitive ● Use array_search to find the element key for a given element value www.

 3. 6). "c" => "apple"). ?> www. 5. The parameters    "fruits"  => array("a" => "orange". 2. 5 => "second".intellibitz.] ) $fruits = array ( ● Returns an array of the parameters..    "holes"  => array("first". "b" =>  can be given an index with the "banana".  "third") ).com                                                                                                                     training@intellibitz.com . => operator.. array() ● Create an array <?php ● array array ( [mixed $.    "numbers" => array(1. 4.

 19. 8 => 1.    [1] => 1 print_r($array). 3 => 13).      [0] => 1 4 => 1. 1.intellibitz.  1. array Array <?php ( $array = array(1. 1. 1.    [2] => 1 ?>    [3] => 13    [4] => 1    [8] => 1    [9] => 19 ) www.com                                                                                                                     training@intellibitz.com .

array() 1­based index with array() <?php <?php $firstquarter = array(1 => 'January'. print_r($firstquarter). 'February'. // Hello baz! The above example will output: Array ( ?> [1] => January [2] => February [3] => March ) www. echo "Hello  ?> {$foo['bar']}!".  'March').com                                                                                                                     training@intellibitz.intellibitz.com . $foo = array('bar' =>  'baz').

  $sort_flags] ) "banana". will be arranged from lowest to highest when this function has foreach ($fruits as $key => $val) { completed. ● Returns TRUE on success or FALSE The above example will output: on failure. "apple"). $key . $val .com .com                                                                                                                     training@intellibitz. Elements sort($fruits).intellibitz. rather than just ?> reordering the keys. "orange". ● This function sorts an array. fruits[0] = apple fruits[1] = banana fruits[2] = lemon fruits[3] = orange www.    echo "fruits[" . for the elements in array. int $fruits = array("lemon". "] = " . sort ● Sort an array <?php ● Description ● bool sort ( array &$array [. It will remove any existing keys you may } have assigned.  ● Note: This function assigns new keys "\n".

rather than just reordering the keys. int $sort_flags] ) ● This function sorts an array in reverse order (highest to lowest). rsort ● Sort an array in reverse order ● bool rsort ( array &$array [.com . It will remove any existing keys you may have assigned. ● Returns TRUE on success or FALSE on failure. ● This function assigns new keys for the elements in array.com                                                                                                                     training@intellibitz.intellibitz. www.

com                                                                                                                     training@intellibitz. rsort <?php $fruits = array("lemon".com . } ?> The above example will output: 0 = orange 1 = lemon 2 = banana 3 = apple www. rsort($fruits). foreach ($fruits as $key => $val) {    echo "$key = $val\n". "banana". "orange".intellibitz. "apple").

This is used mainly when sorting associative arrays where the actual element order is significant. www.com .com                                                                                                                     training@intellibitz. ● ● Returns TRUE on success or FALSE on failure. int $sort_flags] ) ● ● This function sorts an array such that array indices maintain their correlation with the array elements they are associated with. asort ● Sort an array and maintain index association ● bool asort ( array &$array [.intellibitz.

com . The above example will output: c = apple b = banana d = lemon a = orange www. The  fruits  have  been  sorted  in  alphabetical  order.  and  the  index  } associated with each element has  ?> been maintained.com                                                                                                                     training@intellibitz. "a" => "orange". "c" => "apple").intellibitz. asort($fruits). asort <?php $fruits = array("d" => "lemon".  "b" => "banana". foreach ($fruits as $key => $val) {    echo "$key = $val\n".

intellibitz.com . arsort ● Sort an array in reverse order and maintain index association ● bool arsort ( array &$array [. int $sort_flags] ) ● ● This function sorts an array such that array indices maintain their correlation with the array elements they are associated with. ● ● Returns TRUE on success or FALSE on failure. www. This is used mainly when sorting associative arrays where the actual element order is significant.com                                                                                                                     training@intellibitz.

a = orange d = lemon b = banana c = apple www. "c" => "apple"). foreach ($fruits as $key => $val) {    echo "$key = $val\n". arsort <?php $fruits = array("d" => "lemon".intellibitz.  "b" => "banana". arsort($fruits). and the index  associated with each element has been  The above example will output: maintained. "a" => "orange". } The fruits have been sorted in reverse  ?> alphabetical order.com .com                                                                                                                     training@intellibitz.

 "c"=>"apple"). This is useful mainly for associative arrays. ● failure. "b"=>"banana". } ?> The above example will output: a = orange b = banana c = apple d = lemon www. Returns TRUE on success or FALSE on ksort($fruits). ksort ● Sort an array by key <?php ● bool ksort ( array &$array [.com .com                                                                                                                     training@intellibitz.  data correlations. foreach ($fruits as $key => $val) {    echo "$key = $val\n". "a"=>"orange".intellibitz. maintaining key to $fruits = array("d"=>"lemon". int $sort_flags] ) ● Sorts an array by key.

int $sort_flags] ) $fruits = array("d"=>"lemon". ● } ● ?> The above example will output: d = lemon c = apple b = banana a = orange www.com . krsort($fruits). krsort ● Sort an array by key in reverse order <?php ● bool krsort ( array &$array [. "b"=>"banana". maintaining key to data correlations. "c"=>"apple"). foreach ($fruits as $key => $val) { ● ● Returns TRUE on success or FALSE on    echo "$key = $val\n".intellibitz. "a"=>"orange".com                                                                                                                     training@intellibitz.  ● ● Sorts an array by key in reverse order. failure. This is useful mainly for associative arrays.

● natcasesort -. natsort ● Sort an array using a "natural order" algorithm ● bool natsort ( array &$array ) ● This function implements a sort algorithm that orders alphanumeric strings in the way a human being would while maintaining key/value associations.com . This is described as a "natural ordering".com                                                                                                                     training@intellibitz.intellibitz. An example of the difference between this algorithm and the regular computer string sorting algorithms (used in sort()) can be seen below: ● Returns TRUE on success or FALSE on failure. www.case insensitive.

png print_r($array2). The above example will output: sort($array1). [0] => img12.com .png".png [1] => img10. "img1.png").png". Array ( [3] => img1. <?php $array1 = $array2 = array("img12. Standard sorting Array ( echo "Standard sorting\n". [0] => img1.png [1] => img10.com                                                                                                                     training@intellibitz.png print_r($array1).png ) Natural order sorting natsort($array2).intellibitz. "img2.  natsort "img10.png echo "\nNatural order sorting\n".png [3] => img2. [2] => img2. [2] => img12.png".png ) ?> www.

or greater than the second.intellibitz. If the array you wish to sort needs to be sorted by some non-trivial criteria. equal to.com .com                                                                                                                     training@intellibitz. you should use this function. usort ● Sort an array by values using a user-defined comparison function ● Description ● bool usort ( array &$array. or greater than zero if the first argument is considered to be respectively less than. ● ● The comparison function must return an integer less than. equal to. www. callback $cmp_function ) ● ● This function will sort an array by its values using a user-supplied comparison function.

       return 0. 5.com                                                                                                                     training@intellibitz. } ?> The above example will output: 0: 1 1: 2 2: 3 3: 5 4: 6 www.    } usort($a. $b) { usort    if ($a == $b) { $a = array(3.    return ($a < $b) ? ­1 : 1.com . "cmp"). 1). 2. } foreach ($a as $key => $value) {    echo "$key: $value\n".intellibitz. <?php function cmp($a. 6.

6 the user defined functions would keep the original order for those elements.0 this is no longer the case as there is no solution to do so in an efficient way. their order in the sorted array is undefined. but with the new sort algorithm introduced with 4.intellibitz. usort ● Note: If two members compare as equal. It will remove any existing keys you may have assigned. ● ● Returns TRUE on success or FALSE on failure.com . Up to PHP 4. www. ● ● Note: This function assigns new keys for the elements in array. rather than just reordering the keys.com                                                                                                                     training@intellibitz.1.0.

uasort ● Sort an array with a user-defined comparison function and maintain index association ● bool uasort ( array &$array. This is used mainly when sorting associative arrays where the actual element order is significant.intellibitz.com                                                                                                                     training@intellibitz. The comparison function is user- defined. ● Returns TRUE on success or FALSE on failure.com . callback $cmp_function ) ● This function sorts an array such that array indices maintain their correlation with the array elements they are associated with. www.

● ● Function cmp_function should accept two parameters which will be filled by pairs of array keys. equal to. If the array you wish to sort needs to be sorted by some non-trivial criteria. The comparison function must return an integer less than.com                                                                                                                     training@intellibitz. uksort ● Sort an array by keys using a user-defined comparison function ● bool uksort ( array &$array. or greater than the second. equal to. or greater than zero if the first argument is considered to be respectively less than. www. you should use this function.intellibitz. callback $cmp_function ) ● ● uksort() will sort the keys of an array using a user-supplied comparison function.com . ● ● Returns TRUE on success or FALSE on failure.

   return strcasecmp($a. "a banana" => 4). ''. $b).com . "an apple" => 3. $b) uksort { $a = array("John" => 1. } foreach ($a as $key => $value) {    echo "$key: $value\n".intellibitz.com                                                                                                                     training@intellibitz. $a). "the Earth" => 2. $b).    $a = ereg_replace('^(a|an|the) '. uksort($a.    $b = ereg_replace('^(a|an|the) '. } ?> The above example will output: an apple: 3 a banana: 4 the Earth: 2 John: 1 www. "cmp"). <?php function cmp($a. ''.

com                                                                                                                     training@intellibitz.\n". $color.intellibitz. // Or let's skip to only the third one list( . list($drink. ) 'caffeine'). echo "$drink is $color and $power  ● makes it special. echo "I need $power!\n". $power) = $info. mixed $. 'brown'. list <?php ● Assign variables as if they were an array $info = array('coffee'.com ?> .  ● void list ( mixed $varname.. . ● ● Like array(). $power) = $info. ● Note: list() only works on numerical arrays and assumes the numerical // Listing some of them indices start at 0. echo "$drink has $power.\n". www. this is not really a // Listing all the variables function. variables in one operation.. list() is used to assign a list of list($drink. . $power) = $info. but a language construct.

intellibitz. It will remove any existing keys you may have assigned. } ?> www. foreach ($numbers as $number) {    echo "$number ".com .com                                                                                                                     training@intellibitz. <?php $numbers = range(1. 20). rather than just reordering the keys. shuffle ● Shuffle an array ● bool shuffle ( array &$array ) ● This function shuffles (randomizes the order of the elements in) an array. shuffle($numbers). Note: This function assigns new keys for the elements in array.

  ( array $input [. – array_change_key_case() changes the keys in the input print_r(array_change_key_case($input array to be all lowercase or _array. The default is [SECOND] => 4 ) CASE_LOWER. – The function will leave number indices as is. www.com                                                                                                                     training@intellibitz. ?> – The change depends on the last optional case parameter. uppercase. CASE_UPPER)). array_change_key_case ● Returns an array with all string keys lowercased or uppercased <?php – array array_change_key_case $input_array = array("FirSt" => 1. The above example will output: – You can pass two constants Array ( there.intellibitz.com . int $case] ) "SecOnd" => 4). CASE_UPPER and [FIRST] => 1 CASE_LOWER.

?> www.intellibitz. You get the arrays as members of a [1] => Array ( multidimensional array indexed with [0] => c numbers starting from zero. int $size [. array_chunk() ● Split an array into chunks The below example will output: – array array_chunk ( array $input. 'e'). 'd'. You may [0] => a [1] => b also have an array with less values at the ) end.com . [1] => d ) [2] => Array <?php ( [0] => e ) $input_array = array('a'. Array bool $preserve_keys] ) ( – array_chunk() splits the array into several [0] => Array ( arrays with size values in them.com                                                                                                                     training@intellibitz. 2)). 'b'. ) print_r(array_chunk($input_array. 'c'.

 true)). 'b'. ?> www. you can force PHP to ( [0] => a preserve the original keys from [1] => b the input array.com . 'c'.com                                                                                                                     training@intellibitz. 'd'. The default is [2] => Array ( FALSE. [4] => e ) <?php ) $input_array = array('a'. 'e').intellibitz. array_chunk() The below example will output: ● By setting the optional Array ( preserve_keys parameter to [0] => Array TRUE. print_r(array_chunk($input_array. 2. ) [1] => Array ● If you specify FALSE new number ( indices will be used in each [2] => c [3] => d resulting array with indices ) starting from zero.

● key() returns the        echo key($array). ● mixed key ( array while ($fruit_name = current($array)) {    'fruit2' => 'orange'. position.com                                                                                                                     training@intellibitz. &$array )    if ($fruit_name == 'apple') { ●    'fruit3' => 'grape'.com .'<br />'. key <?php / this cycle echoes all associative array $array = array( ● Fetch a key from an // key where value equals "apple" associative array    'fruit1' => 'apple'. / } ?> www.    'fruit4' => 'apple'.intellibitz.    next($array). index element of    } the current array    'fruit5' => 'apple').

This is particularly useful for counting all the elements of a multidimensional array. since anything else will have one element. count() does not detect infinite recursion.0.com                                                                                                                     training@intellibitz. if you have SPL installed. ● For objects. count ● Count elements in an array. ● If the optional mode parameter is set to COUNT_RECURSIVE (or 1). if var is NULL. 0 will be returned.com . The default value for mode is 0. ● The optional mode parameter is available as of PHP 4. which is typically an array. int $mode] ) ● Returns the number of elements in var. or properties in an object ● int count ( mixed $var [. www. There is one exception. you can hook into count() by implementing interface Countable. The interface has exactly one method. count(). count() will recursively count the array. which returns the return value for the count() function.intellibitz.2. ● If var is not an array or an object with implemented Countable interface. 1 will be returned.

com . $result = count(false). // $result == 0 $b[5]  = 9. $b[0]  = 7. $result = count(null). // $result == 1 // $result == 3 ?> sizeof — Alias of count() www.intellibitz. $a[1] = 3. <?php count $a[0] = 1. $result = count($a). // $result == 3 $b[10] = 11. $a[2] = 5.com                                                                                                                     training@intellibitz. $result = count($b).

It does not move the pointer in any way. ● ● The current() function simply returns the value of the array element that's currently being pointed to by the internal pointer.intellibitz.com . If the internal pointer points beyond the end of the elements list. current ● Return the current element in an array ● Description ● mixed current ( array &$array ) ● ● Every array has an internal pointer to its "current" element. current() returns FALSE.com                                                                                                                     training@intellibitz. ● Pos is alias of current www. which is initialized to the first element inserted into the array.

intellibitz. ● ● next() behaves like current().  ● 'bike'. If advancing the $mode = prev($transport). beyond the end of the element list. $mode = next($transport). $mode = end($transport).com                                                                                                                     training@intellibitz. next() returns FALSE.    //  difference. ● Returns the array value in the next place that's pointed to by the internal array $mode =  pointer. 'plane').    //  That means it returns the next array $mode = 'car'.com ?> . 'car'. next ● Advance the internal array pointer of an <?php array ● mixed next ( array &$array ) $transport = array('foot'. with one $mode = next($transport). = 'foot'. or FALSE if there are no current($transport). array pointer one place forward before returning the element value. value and advances the internal array pointer by one. // $mode  more elements.   internal array pointer results in going   // $mode = 'bike'. It advances the internal $mode = 'bike'. www.    //  $mode = 'plane'.

or FALSE if $mode = prev($transport). // $mode = 'foot'.com . ● ● Returns the array value in the previous place $mode = next($transport). ?> www. 'plane').    // $mode = 'plane'. there are no more elements. $mode = current($transport). 'car'. that's pointed to by the internal $mode = next($transport). $mode = end($transport).    // $mode = 'bike'. array pointer.com                                                                                                                     training@intellibitz. prev ● Rewind the internal array <?php pointer ● mixed prev ( array &$array )$transport = array('foot'.    // $mode = 'bike'. 'bike'.    // $mode = 'car'.intellibitz.

Elements 0 and key contain the key name of the array element. www. key.intellibitz.com . This pair is returned in a four-element array. each ● Return the current key and value pair from an array and advance the array cursor ● Description ● array each ( array &$array ) ● ● Returns the current key and value pair from the array array and advances the array cursor. each() returns FALSE. ● ● If the internal pointer for the array points past the end of the array contents. and value. 1. and 1 and value contain the data. with the keys 0.com                                                                                                                     training@intellibitz.

 "fred". print_r($bar). "jussi". each <?php <?php $foo = array("bob". ?> ?> $bar now contains the following  $bar now contains the following key/value pairs: key/value pairs: Array ( Array [1] => Bob ( [value] => Bob [1] => bob [0] => Robert [value] => bob [key] => Robert [0] => 0 ) [key] => 0 ) www. $bar = each($foo).com                                                                                                                     training@intellibitz. print_r($bar). $foo = array("Robert" => "Bob". "Seppo" => "Sepi"). $bar = each($foo).com . "egon".  "jouni". "marliese").intellibitz.

intellibitz. 'cranberry'). and returns its value. 'banana'. <?php $fruits = array('apple'.com                                                                                                                     training@intellibitz. end ● Set the internal pointer of an array to its last element ● mixed end ( array &$array ) ● ● end() advances array's internal pointer to the last element. // cranberry ?> www.com . echo end($fruits).

com .intellibitz. www. or FALSE if the array is empty.com                                                                                                                     training@intellibitz. reset ● Set the internal pointer of an array to its first element ● mixed reset ( array &$array ) ● reset() rewinds array's internal pointer to the first element and returns the value of the first array element.

 the pointer is on the first element // reset pointer. // "step one" reset($array).com . 'step  next($array). $array = array('step one'. "<br />\n". 'step four'). "<br />\n". reset <?php // skip two steps next($array). three'. 'step two'. echo current($array) . "<br />\n". start again on step one echo current($array) . // "step one" ?> www.com                                                                                                                     training@intellibitz.intellibitz. // "step three" // by default. echo current($array) .

com                                                                                                                     training@intellibitz. ● New parameter: The optional step parameter was added in 5. number $step] ) ● range() returns an array of elements from low to high. inclusive. step will default to 1. step should be given as a positive number. If low > high. it will be used as the increment between elements in the sequence.0. the sequence will be from high to low.com . mixed $high [. range ● Create an array containing a range of elements ● array range ( mixed $low. If not specified. www. ● If a step value is given.0.intellibitz.

 1. 10. } www. range ?php // array('a'. 12) as $number) {    echo $letter. 'a'). 7. 'g'.    echo $number. 'b'.com                                                                                                                     training@intellibitz. 'b'. 'i') as $letter) { foreach (range(0. 50. 'd'. 12) foreach (range('a'. 11.0. 30. 100) } foreach (range(0. } } // array('c'. 'h'. 4. 9. // array(0. 8. 90. 100. 10) as $number) { ?>    echo $number. 70. 3. 'f'. foreach (range('c'. 5. 40.0    echo $letter. 'a') as $letter) { // The step parameter was introduced in 5.com . 6. 80.intellibitz. 'c'. 10. 60. 2. 'i'). 20. // array(0. 'e'.

the comparison is done in a case-sensitive manner. FALSE otherwise.com                                                                                                                     training@intellibitz. ● Note: In PHP versions before 4. bool $strict] ) ● ● Searches haystack for needle and returns TRUE if it is found in the array. ● Note: If needle is a string.0 needle was not allowed to be an array. ● If the third parameter strict is set to TRUE then the in_array() function will also check the types of the needle in the haystack. array $haystack [.com .2. ● www. in_array() ● Checks if a value exists in an array ● bool in_array ( mixed $needle.intellibitz.

 "Irix". so the program above will display: Got Irix www. "Linux"). } if (in_array("mac". $os)) {    echo "Got mac".com .com                                                                                                                     training@intellibitz. $os)) {    echo "Got Irix". } ?> The second condition fails because in_array() is case­ sensitive.intellibitz. in_array <?php $os = array("Mac". "NT". if (in_array("Irix".

It takes an associative array var_array and treats keys as variable names and values as variable values.com . int $extract_type [. extract ● Import variables into the current symbol table from an array ● nt extract ( array $var_array [.intellibitz.com                                                                                                                     training@intellibitz. subject to extract_type and prefix parameters. www. string $prefix]] ) ● ● This function is used to import variables from an array into the current symbol table. For each key/value pair it will create a variable in the current symbol table.

[world] => 1 ) www. "hello").com . "hello". "world". array_count_values ● Counts all the values of an array <?php – array array_count_values ( array $input ) $array = array(1.com                                                                                                                     training@intellibitz. ● array_count_value print_r(array_count_values($array)). 1. s() returns an array using the ?> values of the The above example will output: input array as Array keys and their ( [1] => 2 frequency in [hello] => 2 input as values.intellibitz.

com                                                                                                                     training@intellibitz.2. echo "sum(a) = " . "b" => 2. "\n". array_sum ● Calculate the sum of values in an array ● number array_sum ( array $array ) ● array_sum() returns the sum of values in an array as an integer or float. 4.intellibitz.3. array_sum($b) . 6. array_sum($a) .9 www. <?php $a = array(2. ?> The above example will output: sum(a) = 20 sum(b) = 6.com . "c" => 3. 8). echo "sum(b) = " . $b = array("a" => 1.4). "\n".

indexes numerically the array.intellibitz.com                                                                                                                     training@intellibitz. array_values ● Return all the values of an array ● array array_values ( array $input ) <?php ● array_values() returns all the $array = array("size" => "XL". print_r(array_values($array)). "color" =>  values from the input array and "gold"). ?> The above example will output: Array (    [0] => XL    [1] => gold ) www.com .

 2. array_pad Pad array to the specified length <?php ● with a value. ● array array_pad ( array $input. 9. www. ­1). ­1. input padded to size specified // result is array(12. 0. If pad_size is positive then the array is $result = array_pad($input. 10. 9).com . 10. ­7. padding takes place.com                                                                                                                                 elements at a time. "noop"). padded on the right. 5. 0). 9) absolute value of pad_size is less than or equal to the length of the input then no $result = array_pad($input. $input = array(12. ­1. mixed $pad_value ) ● array_pad() returns a copy of the $result = array_pad($input.com                                                                                                                     training@intellibitz. If the // result is array(­1. It is // not padded possible to add most 1048576 ?> www.intellibitz.intellibitz. 10. 0) by pad_size with value pad_value.com training@intellibitz. int $pad_size. if it's negative then on the left. ­1. 12.

● array_pop() pops and returns the last value ?> of the array. "banana". "raspberry").com                                                                                                                     training@intellibitz. $stack will have only 3 elements: shortening the array by one element. "apple". array_pop <?php ● Pop the element off the $stack = array("orange". end of array ● mixed array_pop ( array $fruit = array_pop($stack). NULL will be returned. &$array ) print_r($stack).    [0] => orange    [1] => banana    [2] => apple ) and raspberry will be assigned to $fruit. www.com . If Array array is empty (or is ( not an array).intellibitz. After this.

. mixed $. and pushes the ?> passed variables onto the The above example will output: end of array. ● array_push() treats array as a stack. The length of array increases by the Array number of variables ( pushed. "raspberry").] ) print_r($stack). "apple". mixed $var [. array_push <?php ● Push one or more elements $stack = array("orange". onto the end of array ● int array_push ( array &$array..    [0] => orange    [1] => banana    [2] => apple    [3] => raspberry www.intellibitz.com ) . "banana"). array_push($stack.com                                                                                                                     training@intellibitz.

● Returns the new number of elements in the array. array_push ● array_push has the same effect as: ● <?php ● $array[] = $var. ● ?> ● repeated for each var. array_push() will raise a warning if the first argument is not an array.com .intellibitz. This differs from the $var[] behaviour where a new array is created. www.com                                                                                                                     training@intellibitz.

compact() looks for a variable with that name in the current symbol table and adds it to the output array such that the variable name becomes the key and the contents of the variable become the value for that key. In short. ● Any strings that are not set will simply be skipped. It returns the output array with all the variables added to it.com .intellibitz. Each parameter can be either a string containing the name of the variable. The array can contain other arrays of variable names inside it.] ) ● compact() takes a variable number of parameters. mixed $. it does the opposite of extract(). ● For each of these. compact() handles it recursively. compact ● Create array containing variables and their values ● array compact ( mixed $varname [..com                                                                                                                     training@intellibitz. www. or an array of variable names..

com                                                                                                                     training@intellibitz. ?> The above example will output: product(a) = 384 www.com . 8). <?php $a = array(2. "\n". 6. echo "product(a) = " .intellibitz. array_product($a) . array_product ● Calculate the product of values in an array ● number array_product ( array $array ) ● array_product() returns the product of values in an array as an integer or float. 4.

It takes an input array and an optional argument num_req which specifies how$rand_keys = array_rand($input. returns the key for a random entry. 2).if notecho $input[$rand_keys[0]] .  pick one or more random entries out of an "Trinity". array. "Cypher". specified. many entries you want to pick .com                                                                                                                     training@intellibitz. www.?> Otherwise. ● If you are picking only one entry. it defaults to 1. "\n". "Tank"). "Morpheus".com . int $num_req] ) <?php ● array_rand() is rather useful when you want to $input = array("Neo".intellibitz. This is done so that you can pick random keys as well as values out of the array. array_rand ● Pick one or more random entries out of an array ● mixed array_rand ( array $input [. it returns an array of keys for the random entries. array_rand()echo $input[$rand_keys[1]] . "\n".

array_walk ● Apply a user function to every member of an array ● bool array_walk ( array &$array. it will be passed as the third parameter to the callback funcname. callback $funcname [.intellibitz.com . The array parameter's value being the first. www. funcname takes on two parameters. If the optional userdata parameter is supplied. and the key/index second. Typically. mixed $userdata] ) ● ● Returns TRUE on success or FALSE on failure.com                                                                                                                     training@intellibitz. ● ● Applies the user-defined function funcname to each element of the array array.

. fruit: lemon    echo "$key. $item2<br />\n". banana ?> } c.com                                                                                                                     training@intellibitz. "b" => "banana". $key.intellibitz. 'fruit').. "a" =>  array_walk($fruits. orange array_walk($fruits.. $prefix) d. "c" => "apple"). lemon echo ". 'test_alter'. array_walk <?php echo "Before . fruit: orange } b. "orange".. fruit: banana c.. 'test_print'). apple function test_print($item2.    $item1 = "$prefix: $item1".. and after: { d. { a. and after:\n". fruit: apple www. $key) .. function test_alter(&$item1. This example will  output: $fruits = array("d" => "lemon".: array_walk($fruits.:\n". 'test_print'). b.com . a. Before ..

In words: when the string representation is the same. ● Note that keys are preserved. and ignore all following keys.com                                                                                                                     training@intellibitz. ● The first element will be used. array_unique ● Removes duplicate values from an array ● array array_unique ( array $array ) ● array_unique() takes input array and returns a new array without duplicate values. array_unique() sorts the values treated as string at first.intellibitz. www. ● Note: Two elements are considered equal if and only if (string) $elem1 === (string) $elem2.com . It does not mean that the key of the first related value from the unsorted array will be kept. then will keep the first key encountered for every value.

 "blue".com ) . "red"). "b"  $input = array(4. print_r($result). 4. "3".intellibitz. "3"). array_unique <?php <?php $input = array("a" => "green".com                                                                                                                     training@intellibitz. "red". $result = array_unique($input). ?> ?> The above example will output: The above example will output: array(2) { Array   [0] => int(4) (   [2] => string(1) "3"    [a] => green }    [0] => red    [1] => blue www. 3. => "green". "4". var_dump($result). $result = array_unique($input).

 5). [2] => 27 array $. The number of print_r($b). 2. one. $a)..] ) [3] => 64 ● array_map() returns an array } [4] => 125 ) containing all the elements $a = array(1. array_map ● Applies the callback to the ?php elements of the given This makes $b have: function cube($n) arrays Array ( ● array array_map ( callback { [0] => 1 $callback. parameters that the callback function accepts ?> should match the number of arrays passed to the array_map() www. array $arr1 [. [1] => 8    return($n * $n * $n).intellibitz.. 3.com . 4. of arr1 after applying the callback function to each $b = array_map("cube".com                                                                                                                     training@intellibitz.

} $d = array_reduce($x. 5). $c  containing 1200 (= 10*1*2*3*4*5).com                                                                                                                     training@intellibitz. $w) $a = array(1. 4.intellibitz. "rsum". 1). 2. "rmul".    return $v.    $v += $w. "rsum"). $c = array_reduce($a. function rsum($v.    return $v. array_reduce ● Iteratively reduce the array to a single value using a callback function ● mixed array_reduce ( array $input. $b = array_reduce($a. int $initial] ) <?php function rmul($v. and $d  containing 1. www. 10).com . {    $v *= $w. $w) { $x = array(). } ?> This will result in $b containing 15. 3. callback $function [.

so as to reduce the array to a single value. it will be used at the beginning of the process. or as a final result in case the array is empty. ● If the optional initial is available. array_reduce ● array_reduce() applies iteratively the function function to the elements of the array input.com . ● If the array is empty and initial is not passed.com                                                                                                                     training@intellibitz. www. array_reduce() returns NULL.intellibitz.

bool $preserve_keys] ) ● ● array_reverse() takes input array and returns a new array with the order of the elements reversed.intellibitz. array_reverse ● Return an array with elements in reverse order ● array array_reverse ( array $array [.com . preserving the keys if preserve_keys is TRUE. www.com                                                                                                                     training@intellibitz.

array_reverse $result will be $result_keyed will be: Array <?php Array ( $input  = array("php". "red")).intellibitz.0. true).com                                                                                                                     training@intellibitz.    [2] => Array        ( $result_keyed = array_reverse($input. array("green". 4.    [1] => 4    [2] => php    [0] => php ) ) www.com . (    [0] => Array $result = array_reverse($input).        (            [0] => green ?>            [0] => green            [1] => red            [1] => red This makes both $result and $result_keyed         )        ) have the same elements.    [1] => 4 but note the difference between the keys.

  // $key = 1. // $key = 2. the comparison is done in a case-sensitive manner.com ?> . array $haystack [.0. <?php $array = array(0 => 'blue'.2.com                                                                                                                     training@intellibitz. ● If needle is a string. bool $strict] ) ● Searches haystack for needle and returns the key if it is found in the array.intellibitz. array_search() returns NULL on failure instead of FALSE. ● Prior to PHP 4. $array). 1 => 'red'. $key = array_search('red'. 3 => 'red'). array_search ● Searches the array for a given value and returns the corresponding key if successful mixed array_search ( mixed $needle. www. 2 => 'green'. $array). ● If the optional third parameter strict is set to TRUE then the array_search() will also check the types of the needle in the haystack. $key = array_search('green'. FALSE otherwise.

If array is empty (or is not an array).intellibitz. www. NULL will be returned. ● This function will reset() the array pointer after use. array_shift ● Shift an element off the beginning of array ● mixed array_shift ( array &$array ) ● array_shift() shifts the first value of the array off and returns it. ● All numerical array keys will be modified to start counting from zero while literal keys won't be touched.com . shortening the array by one element and moving everything down.com                                                                                                                     training@intellibitz.

Array ?> (    [0] => banana    [1] => apple    [2] => raspberry ) and orange will be assigned to $fruit. $fruit = array_shift($stack). This would result in $stack having 3 elements left: print_r($stack).com .com                                                                                                                     training@intellibitz. www. "banana".intellibitz. array_shift <?php $stack = array("orange". "raspberry"). "apple".

mixed $var [. so that the Array prepended elements stay in the same order. array_unshift <?php ● Prepend one or more elements to $queue = array("orange"..] ) print_r($queue). ● int array_unshift ( array &$array.com . Note that the list of elements is The above example will output: prepended as a whole. the beginning of an array array_unshift($queue.. "banana").com                                                                                                                     training@intellibitz. "raspberry"). mixed $. ● array_unshift() prepends passed ?> elements to the front of the array. "apple". All numerical array ( keys will be modified to start    [0] => apple counting from zero while literal keys won't be touched.    [1] => raspberry ● Returns the new number of elements    [2] => orange in the array    [3] => banana ) www.intellibitz.

www. bool $preserve_keys]] ) ● ● array_slice() returns the sequence of elements from the array array as specified by the offset and length parameters. int $length [.com                                                                                                                     training@intellibitz. array_slice ● Extract a slice of the array ● rray array_slice ( array $array.intellibitz. int $offset [.com .

If length is given and is negative then the sequence will stop that many elements from the end of the array. then the sequence will have that many elements in it. If it is omitted. array_slice ● if offset is non-negative. ● If length is given and is positive. the sequence will start that far from the end of the array. If offset is negative. then the sequence will have everything from offset up until the end of the array.com .intellibitz.com                                                                                                                     training@intellibitz. www. the sequence will start at that offset in the array.

print_r(array_slice($input.intellibitz. ­1)). "d". 2. array_slice <?php $input = array("a". "b".  //  returns "a". Array ( [0] => c $output = array_slice($input. "d". www. and "e" ) Array $output = array_slice($input. "b". "c".  //  ( [2] => c returns "d" [3] => d ) $output = array_slice($input. and "c" // note the differences in the array keys print_r(array_slice($input. 3).com .      //  [1] => d returns "c". 0. ­2. 1). "e"). 2). 2. true)). ­1.com                                                                                                                     training@intellibitz.

 "yellow"). "green".com . ● array array_splice ( array &$input. array_splice($input. 2). array_splice($input. "blue". "green") $input = array("red". array_splice ● Remove a portion of the array <?php and replace it with something else $input = array("red". ­1). array $replacement]] ) // $input is now array("red". "yellow"). int $length [. // $input is now array("red".intellibitz.com                                                                                                                     training@intellibitz. "green". "yellow") www. "blue". 1. int $offset [.

unless the element is an array itself. then that many elements will be removed. www. then the elements from the replacement array are inserted in the place specified by the offset. If length is specified and is positive.intellibitz.com                                                                                                                     training@intellibitz. use count($input) for length. removes everything from offset to the end of the array. array_splice ● If offset is positive then the start of removed portion is at that offset from the beginning of the input array. ● If offset is negative then it starts that far from the end of the input array.com . then the removed elements are replaced with elements from this array. Tip: to remove everything from offset to the end of the array when replacement is also specified. ● If replacement array is specified. If replacement is just one element it is not necessary to put array() around it. If offset and length are such that nothing is removed. Note that keys in replacement array are not preserved. If length is specified and is negative then the end of the removed portion will be that many elements from the end of the array. ● If length is omitted.

then the later value "shape" =>  for that key will overwrite the "trapezoid". If.intellibitz. ● If the input arrays have the same "color" => "green". 4). It returns the "a". ( together so that the values of one are appended to the end of $array2 = array(    [color] => green the previous one. however. ) ?> www.     [shape] => trapezoid the later value will not overwrite $array2). array $array2 [. array_merge($array1.    [0] => 2 resulting array.com .. array_merge ● array array_merge ( array $array1 This example will  <?php output: [. but will be    [4] => 4 appended. 2.]] ) ● array_merge() merges the $array1 = array( Array elements of one or more arrays "color" => "red". "b".    [2] => a previous one. array $..4). the original value.     [1] => 4 string keys. the    [3] => b $result =  arrays contain numeric keys.com                                                                                                                     training@intellibitz. print_r($result).

array_merge_recursive Array ● If the input arrays have <?php ( the same string keys. done recursively. "blue")).        ( merged together into $ar2 = array(10. values is an array                    [1] => green itself.com                                                                                                                     training@intellibitz.com ) .intellibitz.   )     [0] => 5    [1] => 10 www. "color" =>             [favorite] => Array an array. 5). merge it with a                ) ?> corresponding entry            [0] => blue in another array too. $ar1 = array("color" =>    [color] => Array then the values for these keys are array("favorite" => "red"). and this is array("favorite" => "green". the function will print_r($result).  that if one of the                    [0] => red $ar2). so                ( $result = array_merge_recursive($ar1.

intellibitz. www. then only the keys for that value are returned. bool $strict]] ) ● array_keys() returns the keys. you can use strict parameter for comparison including type (===). numeric and string. array_key ● Return all the keys of an array ● array array_keys ( array $input [.com . from the input array. ● If the optional search_value is specified.com                                                                                                                     training@intellibitz. Otherwise. mixed $search_value [. all the keys from the input are returned. As of PHP 5.

[1] => color ) Array ( [0] => 0 $array = array("blue". array_key The above example will output: <?php Array $array = array(0 => 100. "red".intellibitz. "green". ( [0] => 0 print_r(array_keys($array)). "blue".com . "large")). "red". "color" => "red"). ?> www. ) Array ( [0] => color $array = array("color" => array("blue". "blue"). [1] => 3 [2] => 4 print_r(array_keys($array.com                                                                                                                     training@intellibitz. [1] => size )                "size"  => array("small". print_r(array_keys($array)). "blue")). "medium". "green").

array_key_exists ● Checks if the given key or index exists in the array ● bool array_key_exists ( mixed $key. $search_array).com .com                                                                                                                     training@intellibitz. isset($search_array['first']). <?php <?php $search_array = array('first' => null.intellibitz. 'second' =>  $search_array = array('first' => 1.6.0. $search_array)) { // returns false    echo "The 'first' element is in the array". ?> www. if (array_key_exists('first'. key can be any value possible for an array index. 'second' => 4). The name of this function is key_exists() in PHP 4. array_key_exists() also works on objects. array $search ) ● array_key_exists() returns TRUE if the given key is set in the array. } // returns true ?> array_key_exists('first'. 4).

entries of the value of the value ?> parameter.com . 'banana'). 6. int $a = array_fill(5. array_fill ● Fill an array with values ?php – array array_fill ( int $start_index. [6] => banana [7] => banana [8] => banana [9] => banana [10] => banana ) www. mixed $value ) – array_fill() fills an array with num print_r($a). $num. or PHP will throw a [5] => banana warning. keys starting at the start_index parameter. Note that $a now is: num must be a number greater Array ( than zero.com                                                                                                                     training@intellibitz.intellibitz.

● array_fill_keys() fills an array print_r($a). $a now is: Array ( [foo] => banana [5] => banana [10] => banana [bar] => banana ) www.com . using the values ?> of the keys array as keys. with the value of the value parameter. 'bar'). 10. mixed $value ) $a = array_fill_keys($keys. ● array array_fill_keys ( array $keys.com                                                                                                                     training@intellibitz. 'banana'). <?php specifying keys $keys = array('foo'. array_fill_keys ● Fill an array with values.intellibitz. 5.

com . the latest key( [1] => b will be used as its values. ) ● array_flip() returns FALSE if it fails. A warning will be emitted if a value has the wrong type.intellibitz. from trans become values and values from $trans = array_flip($trans). and all others will be [2] => c lost. array_flip ● Exchanges all keys with their associated values <?php in an array ● array array_flip ( array $trans ) $trans = array("a" => 1. trans become keys.e. Array ● If a value has several occurrences. they need to be either integer or ?> string. keys => 2). keys. "c"  ● array_flip() returns an array in flip order. and the key/value pair in now $trans is: question will not be flipped. i. www. ● Note that the values of trans need to be valid print_r($trans).e.com                                                                                                                     training@intellibitz. i. "b" => 1.

containing all the values of array1$result = array_intersect($array1. $array2). "red"). "blue"). In words: when the string ( representation is the    [a] => green same.com                                                                                                                     training@intellibitz. $array1 = array("a" => "green".] ) ● array_intersect() returns an array $array2 = array("b" => "green".    [0] => red ) www.intellibitz. ?> – Two elements are considered equal if and The above example will output: only if (string) $elem1 ===Array (string) $elem2. "yellow".. preserved. array_intersect ● Computes the intersection of arrays <?php ● array array_intersect ( array $array1.. that are present in all the arguments. Note that keys are print_r($result). array $array2 [. array $ . "red".com .

array $ .] ) – array_intersect_key() returns an array containing all the values of array1 which have matching keys that are present in all the arguments. array_intersect_key ● Computes the intersection of arrays using keys for comparison – array array_intersect_key ( array $array1.com . www.. array $array2 [..intellibitz.com                                                                                                                     training@intellibitz.

int(3) } www. A match still occurs because only the keys var_dump(array_intersect_key($array1.  Also notice that the values for the 'yellow' => 7. array_intersect_key <?php ● In our example you see that only the $array1 = array('blue'  => 1.com .intellibitz.  keys 'blue' and 'green' are present 'green'  => 3. are those of array1. in both arrays and thus returned. $array2 = array('green' => 5. 'cyan'  => 8).  are checked. In array(2) { other words a strict type check is ["blue"]=> executed so the string int(1) ["green"]=> representation must be the same. keys 'blue' and 'green' differ between the two arrays. The values returned $array2)). 'blue' => 6. 'purple' => 4). ● The two keys from the key => value ?> pairs are considered equal only if The above example will output: (string) $key1 === (string) $key2 .com                                                                                                                     training@intellibitz. 'red'  => 2.

 "yellow".intellibitz. It must return an integer less than. compares indexes by $array1 = array("a" => "green". or greater The above example will output: than zero if the first argument is Array considered to be respectively less than.. array $array2 [. – The index comparison is done by a user ?> supplied callback function. "B"  $array1.com .com                                                                                                                     training@intellibitz. "red"). callback $key_compare_func] ) => "brown"... array_intersect_uassoc <?php ● Computes the intersection of arrays with additional index check. unlike in array_intersect(). ( equal to. Note print_r(array_intersect_uassoc($array that the keys are used in the comparison 1. "b" =>  a callback function "brown". – array array_intersect_uassoc ( array $array2 = array("a" => "GREEN". array $ . "strcasecmp")). $array2. [b] => brown ) www. "c" => "blue". "red"). – array_intersect_uassoc() returns an array containing all the values of array1 that are present in all the arguments. equal to. or greater than the second.

intellibitz.com                                                                                                                     training@intellibitz. The above example will output: Array ( [a] => green ) www. "c" => "blue". array $ "red"). "b" =>  check "brown".. array containing all the values of array1 that are present in all the print_r($result_array). $array2). ● array array_intersect_assoc ( array $array2 = array("a" => "green". "red"). array $array2 [.com . arguments..] ) $result_array =  ● array_intersect_assoc() returns an array_intersect_assoc($array1. . "yellow". array_intersect_assoc <?php ● Computes the intersection of arrays with additional index $array1 = array("a" => "green". Note that the keys ?> are used in the comparison unlike in array_intersect().  $array1.

www.com                                                                                                                     training@intellibitz. ● The two values from the key => value pairs are considered equal only if (string) $elem1 === (string) $elem2 . array_intersect_assoc ● In our example you see that only the pair "a" => "green" is present in both arrays and thus is returned.intellibitz. The value "red" is not returned because in $array1 its key is 0 while the key of "red" in $array2 is 1.com . In other words a strict type check is executed so the string representation must be the same.

.intellibitz. array $array2 [.com .. equal to.com                                                                                                                     training@intellibitz. equal to.. It must return an integer less than. ● This comparison is done by a user supplied callback function. or greater than zero if the first key is considered to be respectively less than. array_intersect_ukey ● Computes the intersection of arrays using a callback function on the keys for comparison ● array array_intersect_ukey ( array $array1. callback $key_compare_func] ) ● array_intersect_ukey() returns an array containing all the values of array1 which have matching keys that are present in all the arguments. array $. or greater than the second. www.

 'blue' => 6.  'key_compare_func')). 'green'  => 3. array_intersect_ukey $array1 = array('blue'  => 1. ["blue"]=> int(1) } ["green"]=> int(3) } www. $array2.  { 'cyan'  => 8).com . var_dump(array_intersect_ukey($array1.intellibitz. 'red'  => 2.    else The above example will output: array(2) {        return ­1.    if ($key1 == $key2)        return 0.com                                                                                                                     training@intellibitz. function key_compare_func($key1. 'yellow' => 7.    else if ($key1 > $key2) ?>        return 1. $key2) $array2 = array('green' => 5.  <?php 'purple' => 4).

● array array_uintersect ( array $array1. $data_compare_func] ) ● array_uintersect() returns an array containing all the print_r(array_uintersect($array1..com . array $array2 [. "strcasecmp")).. The data is The above example will output: compared by using a Array callback function. "yellow".$array2 = array("a" => "GREEN". "red"). "red"). compares data by a callback function "c" => "blue". "b" => "brown".intellibitz. values of array1 that are ?> present in all the arguments. array_uintersect <?php ● Computes the intersection of $array1 = array("a" => "green". array $ . arrays. $array2. callback "B" => "brown".com                                                                                                                     training@intellibitz. ( [a] => green [b] => brown [0] => red ) www..

  ● array_uintersect_assoc() returns $array2. array $array2 [. compares data by a "brown"... "strcasecmp")). "yellow".com . "red"). "red").. "c" => "blue". "b" =>  check.intellibitz. . Array ( [a] => green ) www. callback $data_compare_func] ) ● print_r(array_uintersect_assoc($array1. array_uintersect_assoc ● Computes the intersection of <?php arrays with additional index $array1 = array("a" => "green". callback function ● rray array_uintersect_assoc ( array $array2 = array("a" => "GREEN". an array containing all the ?> values of array1 that are The above example will output: present in all the arguments. array $ "brown".com                                                                                                                     training@intellibitz. "B" =>  $array1.

 $array2. "red"). "red"). callback $data_compare_func.intellibitz. The above example will output: Array ( [a] => green [b] => brown ) www. arguments. "strcasecmp"))... Note that the keys are ?> used in the comparison unlike in array_uintersect().com                                                                                                                     training@intellibitz. array_uintersect_uassoc <?php ● Computes the intersection of arrays with additional index check.  ● array containing all the values of array1 that are present in all the "strcasecmp".com . callback $key_compare_func] ) ● array_uintersect_uassoc() returns an print_r(array_uintersect_uassoc($array1. "B" => "brown".  $array1. array $array2 [.. "b" => "brown". "yellow". array $ . ● array array_uintersect_uassoc ( array $array2 = array("a" => "GREEN". compares $array1 = array("a" => "green". "c"  data and indexes by a callback functions => "blue".

 "blue".com                                                                                                                     training@intellibitz. $array1. array_diff ● Computes the difference of arrays <?php – array array_diff ( array $array1 = array("a" => "green".. other arguments. "red"). "red". array $ .intellibitz.] ) $array2 = array("b" => "green". array $array2 [. "yellow". ?> This will output : Array ( [1] => blue ) www. array containing all the values of array1 that are not present in any of the print_r($result).com . $array2). Note that keys are preserved. – array_diff() returns an $result = array_diff($array1. "red")..

["red"]=> int(2) ["purple"]=> int(4) } var_dump(array_diff_key($array1. array $array2 [.] ) ● array_diff_key() returns an array containing all the values of array1 that have keys that are not present in any of the other arguments. 'blue' => 6. Note that the associativity is preserved.com                                                                                                                     training@intellibitz. This example will  output   array(2) { $array2 = array('green' => 5. 'purple' => 4).intellibitz. This function is like array_diff() except the comparison is done on the keys instead of the values. 'yellow' => 7. $array1 = array('blue'  => 1. array $ .com . – The two keys from the key => value pairs are considered equal only if (string) $key1 === (string) $key2 .. $array2)). array_diff_key ● Computes the difference of arrays using keys for comparison – array array_diff_key ( array $array1. 'cyan'  => 8). 'red'  => 2. In other words a <?php strict type check is executed so the string representation must be the same.. 'green'  => 3. ?> www.

  output: "red").] ) – array_diff_assoc() returns an array containing all the values from array1 that are not present in any of the other arguments.  ( [b] => $array2). "yellow".. This example will  $array2 = array("a" => "green". blue [0] => red ?> ) www.. "b" =>  "brown". Array $result = array_diff_assoc($array1.intellibitz. array $ . brown [c] => print_r($result). array_diff_assoc ● Computes the difference of arrays with additional index check – array array_diff_assoc ( array $array1. $array1 = array("a" => "green". "red").com . "c" => "blue". array $array2 [. <?php – Note that the keys are used in the comparison unlike array_diff().com                                                                                                                     training@intellibitz.

com . Note that keys are preserved. array $array2 [.com                                                                                                                     training@intellibitz.intellibitz.. callback $data_compare_func] ) ● ● array_udiff() returns an array containing all the values of array1 that are not present in any of the other arguments. www... array_udiff ● Computes the difference of arrays by using a callback function for data comparison ● array array_udiff ( array $array1. array $ .

 $array2.    if ($a === $b) { $result = array_diff_uassoc($array1. print_r($result). "yellow". ( [b] => brown } [c] => blue [0] => red ) www. "red").intellibitz. function key_compare_func($a.com . $b) $array1 = array("a" => "green". { $array2 = array("a" => "green".        return 0. "b" => "brown".com                                                                                                                     training@intellibitz. array_diff_uassoc Computes the difference of arrays with additional index check which is ● performed by a user supplied callback function – array_diff_uassoc() returns an array containing all the values from <?php array1 that are not present in any of the other arguments. "c" => "blue".    } The above example will output: ?> Array    return ($a > $b)? 1:­1. "red"). "key_compare_func").

– This is unlike array_diff_assoc() where an internal function for comparing the indices is used.intellibitz. www. array_diff_uassoc ● Note that the keys are used in the comparison unlike array_diff(). equal to.com . equal to.com                                                                                                                     training@intellibitz. or greater than zero if the first argument is considered to be respectively less than. – This comparison is done by a user supplied callback function. It must return an integer less than. or greater than the second.

equal to. callback $key_compare_func] ) ● array_diff_ukey() returns an array containing all the values of array1 that have keys that are not present in any of the other arguments.. array_diff_ukey ● Computes the difference of arrays using a callback function on the keys for comparison – array array_diff_ukey ( array $array1. It must return an integer less than.. or greater than the second. or greater than zero if the first key is considered to be respectively less than.com                                                                                                                     training@intellibitz. ● This comparison is done by a user supplied callback function. This function is like array_diff() except the comparison is done on the keys instead of the values. array $array2 [. www..intellibitz. array $ . equal to. Note that the associativity is preserved.com .

com .  . array_diff_ukey <?php $array1 = array('blue'  => 1. 'cyan'  => 8). $key2) 'yellow' => 7. 'red'  => 2.com                                                                                                                     training@intellibitz. 'blue' => 6. ?>    else if ($key1 > $key2) The above example will output:        return 1. array(2) { ["red"]=>    else int(2) ["purple"]=>        return ­1.        return 0. {    if ($key1 == $key2) var_dump(array_diff_ukey($array1.  $array2.intellibitz. 'purple' => 4). int(4) } } www. 'key_compare_func')). function  key_compare_func($key1 $array2 = array('green' => 5.  'green'  => 3.

array $array2 [. ● In this aspect the behaviour is opposite to the behaviour of array_diff_assoc() which uses internal function for comparison.. www..com                                                                                                                     training@intellibitz. array_udiff_assoc ● Computes the difference of arrays with additional index check. array $ .intellibitz. The comparison of arrays' data is performed by using an user-supplied callback.. callback $data_compare_func] ) ● array_udiff_assoc() returns an array containing all the values from array1 that are not present in any of the other arguments.com . compares data by a callback function ● array array_udiff_assoc ( array $array1. ● Note that the keys are used in the comparison unlike array_diff() and array_udiff().

array_udiff_uassoc ● Computes the difference of arrays with additional index check. Note that the keys are used in the comparison unlike array_diff() and array_udiff(). callback $key_compare_func] ) ● array_udiff_uassoc() returns an array containing all the values from array1 that are not present in any of the other arguments.. callback $data_compare_func.. array $ .intellibitz.. compares data and indexes by a callback function ● array array_udiff_uassoc ( array $array1. array $array2 [. www.com                                                                                                                     training@intellibitz.com .

Modifying Arrays

Array elements operate just like regular scalar variables
using operators

Don't put quotes around element key when interpolating
array elements in strings

If array key has whitespace or other punctuation, use curly
braces

www.intellibitz.com                                                                                                                     training@intellibitz.com

Modifying Arrays

Use unset() to remove elements from array

Use implode() to quickly print all array values as a string

Use explode() to turn a string into an array

www.intellibitz.com                                                                                                                     training@intellibitz.com

Sorting Arrays

Use sort() only on numeric arrays, because it resets the
keys of the array when it sorts

Use asort() to sort an associative array

Use ksort() to sort arrays by key

The reverse sorting functions are rsort(), arsort() and
krsort()

www.intellibitz.com                                                                                                                     training@intellibitz.com

Using Multidimensional Arrays

Use array() construct to create arrays that have more
arrays as element values

Access element in multidimensional arrays by using more
sets of square brackets to identify elements

Use nested foreach() to iterate through each dimension of a
multidimensional array

www.intellibitz.com                                                                                                                     training@intellibitz.com

Chapter Summary

Understanding the components of an array: elements, keys
and values

Defining an array in your programs two ways: with array()
and with square brackets

Understanding the shortcuts PHP provide for arrays with
numeric keys

Counting the number of elements in array

www.intellibitz.com                                                                                                                     training@intellibitz.com

Chapter Summary

Visiting each element of array with foreach()

Modifying array element values inside a foreach() code
block

Visiting each element of a numeric key with for()

Understanding the order in which foreach() and for() visit
array elements

www.intellibitz.com                                                                                                                     training@intellibitz.com

Chapter Summary

Checking for an array element with a particular key

Checking for an array element with a particular value

Interpolating array element values in strings

Removing an element from an array

Generating a string from array with implode()

Generating array from string with explode()

www.intellibitz.com                                                                                                                     training@intellibitz.com

Chapter Summary

Sorting an array with sort(), asort(), or ksort()

Sorting an array in reverse

Defining a multidimensional array

Accessing individual elements of a multidimensional array

Visiting each element in a multidimensional array with
foreach() or for()

Interpolating multidimensional array elements

www.intellibitz.com                                                                                                                     training@intellibitz.com

CHAPTER 5

FUNCTIONS

www.intellibitz.com                                                                                                                     training@intellibitz.com

Functions

Declaring and Calling Functions

Passing Arguments to Functions

Returning Values from Functions

Understanding Variable Scope

www.intellibitz.com                                                                                                                     training@intellibitz.com

Functions

Functions allows you to reuse code

Functions are named set of statements that you can
execute by invoking the function name instead of
retyping the statements

Functions can take arguments as well return value

Variables inside a function and outside a function live in two
separate worlds

www.intellibitz.com                                                                                                                     training@intellibitz.com

Declaring and Calling Functions

Function names follow the same rules as variable names

Functions can be defined before or after they are called

Avoid using the same name for a function and a variable

www.intellibitz.com                                                                                                                     training@intellibitz.com

com .intellibitz.com                                                                                                                     training@intellibitz. and not variables www. Passing Arguments to Functions ● The input values supplied to a function are called arguments ● Functions can take optional argument by specifying a default in the declaration ● Optional arguments must come after mandatory arguments ● Default values for arguments must be literals.

intellibitz. Passing Arguments to Functions ● Changes made to a variable passed as an argument don't affect the variable outside the function ● Modifying arguments doesn't affect variables outside the function even if the argument has the same name as a variable outside the function www.com                                                                                                                     training@intellibitz.com .

use an array as return value ● A test expression can consist just a function call with no comparison or other operator www.intellibitz. Returning values from Functions ● Functions can also compute a value.com . called the return value ● Return value of a function can be used in assignment just like number or a string ● To return more than one value from a function.com                                                                                                                     training@intellibitz.

but local variables of a function are not accessible outside that function www.intellibitz.com .com                                                                                                                     training@intellibitz. Understanding Variable Scope ● Variables defined outside of a function are called global variables ● Variables defined inside of a function are called local variables ● Global variables can be accessed from inside a function.

com                                                                                                                     training@intellibitz.com .intellibitz. called an auto-global ● The auto-globals are always arrays that are automatically populated with data www. Understanding Variable Scope ● Two ways to access a global variable from inside a function: use $GLOBALS ● Use the global keyword to “bring a variable into local scope” inside the function ● $GLOBALS is a special kind of pre-defined variable.

com                                                                                                                     training@intellibitz. Chapter Summary ● Defining your own functions and calling them in your programs ● Defining a function with mandatory arguments ● Defining a function with optional arguments ● Returning a value from a function ● Understanding variable scope ● Using global variables inside a function www.com .intellibitz.

com                                                                                                                     training@intellibitz.com .intellibitz. CHAPTER 6 HTML AN INTRODUCTION TO WEB FORMS www.

intellibitz.com                                                                                                                          training@intellibitz.com . HTML ● HTML stands for Hyper Text Markup Language ● An HTML file is a text file containing small markup tags ● The markup tags tell the Web browser how to display the page www.

intellibitz.Netscafe.com                                                                                                                          training@intellibitz.com . ● Fire fox. HTML File ● An HTML file must have an htm or html file extension ● An HTML file can be created using a simple text editor ● The html files are viewed in a web browser. opera are few well known web browsers. Internet Explorer. www.

com . ● The web browser has to be refreshed to view the changes made in the html file www.intellibitz.com                                                                                                                          training@intellibitz. correct path of the html file has to be typed into the address box of the web browser . Viewing outputs in browsers ● To view the output.

● Html tags normally come in pair s like <b></b>. ● <html> </html> are the starting and ending tags.intellibitz.<b>means the same as <B>. ● Html tags are not case sensitive . HTML Tags ● The tags in HTML are enclosed by angle brackets(<.com .>). www.com                                                                                                                          training@intellibitz.

www.com                                                                                                                          training@intellibitz. Head ● Html files has two major parts.intellibitz.com . ● <title> </title>tags are the major tag used with in <head></head> tags ● <title> tag tells the browser what has to be displayed in the title bar of the web browser.head and body.

com .intellibitz. Use <del> instead ● <u> Deprecated.com                                                                                                                          training@intellibitz. Use styles instead www. Formatting ● <strong> Defines strong text ● <sub> Defines subscripted text ● <sup> Defines superscripted text ● <ins> Defines inserted text ● <del> Defines deleted text ● <s> Deprecated. Use <del> instead ● <strike> Deprecated.

www.intellibitz.com                                                                                                                          training@intellibitz.com . ● <p> tag encloses the paragraph. BODY ● <BODY> encloses the content that has to be displayed in the browser.

com . ● Attributes are always specified in the start tag of an HTML element.com                                                                                                                          training@intellibitz.intellibitz. Attribute ● Attributes provide additional information to an HTML element. ● Attributes always come in name/value pairs like this: name="value". www.

you can tell the browser that the table should have no borders: <table border="0"> ● Attribute values should always be enclosed in quotes. With an added border attribute.com                                                                                                                          training@intellibitz.com . Double style quotes are the most common. Attribute ● The following tag defines an HTML table: <table>.intellibitz. www. but single style quotes are also allowed.

it is necessary to use single quotes: – name='John "ShotGun" Nelson' www. like when the attribute value itself contains quotes.intellibitz. Attribute ● In some rare situations.com                                                                                                                          training@intellibitz.com .

● HTML automatically adds an extra blank line before and after a headings and paragraph. Headings ● Headings are defined with the <h1> to <h6> tags.com . <h1> defines the largest heading. ● Paragraphs are defined with the <p> tag. www.intellibitz. <h6> defines the smallest heading.com                                                                                                                          training@intellibitz.

com . but don't want to start a new paragraph. It has no closing tag.intellibitz. www.com                                                                                                                          training@intellibitz. The <br> tag forces a line break wherever you place it. Line break ● The <br> tag is used when you want to end a line. ● The <br> tag is an empty tag.

You can use comments to explain your code. ● <!-. which can help you when you edit the source code at a later date.This is a comment --> ● Note that you need an exclamation point after the opening bracket.intellibitz.com .com                                                                                                                          training@intellibitz. but not before the closing bracket. www. Comments ● The comment tag is used to insert a comment in the HTML source code. A comment will be ignored by the browser.

Formatting ● HTML defines a lot of elements for formatting output.com                                                                                                                          training@intellibitz.com . like bold or italic text.intellibitz. ● <b> Defines bold text ● <big> Defines big text ● <em> Defines emphasized text ● <i> Defines italic text ● <small> Defines small text www.

Use <pre> instead www.com                                                                                                                          training@intellibitz. Use <pre> instead ● <plaintext> Deprecated. Use <pre> instead ● <xmp> Deprecated. Formatting ● <code> Defines computer code text ● <kbd> Defines keyboard text ● <samp> Defines sample computer code ● <tt> Defines teletype text ● <var> Defines a variable ● <pre> Defines preformatted text ● <listing> Deprecated.intellibitz.com .

Formatting ● <abbr> Defines an abbreviation ● <acronym> Defines an acronym ● <address> Defines an address element ● <bdo> Defines the text direction ● <blockquote> Defines a long quotation ● <q> Defines a short quotation ● <cite> Defines a citation ● <dfn> Defines a definition term www.intellibitz.com                                                                                                                          training@intellibitz.com .

intellibitz.com . ● To display a less than sign (<) in HTML. and therefore cannot be used in the text. www. we have to use a character entity.com                                                                                                                          training@intellibitz. have a special meaning in HTML. Html entities ● Some characters like the < character.

intellibitz. www.).com                                                                                                                          training@intellibitz.com . and finally a semicolon (. – To display a less than sign in an HTML document we must write: &lt. Html entities ● A character entity has three parts: an ampersand (&). an entity name or a # and an entity number. or &#60.

use the &nbsp. www.com . If you write 10 spaces in your text HTML will remove 9 of them. ● To add spaces(non breaking space) to your text.com                                                                                                                          training@intellibitz.intellibitz. character entity. Html entities ● Normally HTML will truncate spaces in your text.

www.com                                                                                                                          training@intellibitz. &#60. &#62. ● & ampersand &amp. ● " quotation mark &quot. &#39. Html entities ● non-breaking space &nbsp. &#34.intellibitz. ● < less than &lt. ● > greater than &gt.com . ● ' apostrophe &apos. &#38. &#160.

&#163. &#165. www. ● × multiplication &times.com . ● ® registered trademark &reg. Html entities ● ¢ cent &cent. ● £ pound &pound. &#215. &#167.intellibitz. &#174. &#162. ● © copyright &copy.com                                                                                                                          training@intellibitz. ● ÷ division &divide. &#247. &#169. ● ¥ yen &yen. ● § section &sect.

www.com . and the words between the open and close of the anchor tag will be displayed as a hyperlink.com                                                                                                                          training@intellibitz. ● The <a> tag is used to create an anchor to link from.intellibitz. Links ● HTML uses a hyperlink to link to another document on the Web. the href attribute is used to address the document to link to.

com                                                                                                                          training@intellibitz.intellibitz.com/" ● target="_blank">Visit IntelliBitz!</a> www.com . Link ● With the target attribute.IntelliBitz. ● ● <a href="http://www. you can define where the linked document will be opened.

com . Link ● The name attribute is used to create a named anchor.intellibitz. ● When using named anchors we can create links that can jump directly into a specific section on a page.com                                                                                                                          training@intellibitz. instead of letting the user scroll around to find what he/she is looking for. www.

com                                                                                                                          training@intellibitz. Frames ● With frames. you can display more than one Web page in the same browser window.intellibitz.com . ● The disadvantages of using frames are: – The web developer must keep track of more HTML documents – It is difficult to print the entire page www.

intellibitz.com                                                                                                                          training@intellibitz.com . Frames ● The <frameset> tag defines how to divide the window into frames ● Each frameset defines a set of rows or columns ● The values of the rows/columns indicate the amount of screen area each row/column will occupy www.

htm">    <frame src="frame_b.intellibitz.com .com                                                                                                                          training@intellibitz.htm"> </frameset> www.75%">    <frame src="frame_a. Frames ● The <frame> tag defines what HTML document to put into each frame <frameset cols="25%.

com . you will have to enclose the text in <body></body> tags! www.com                                                                                                                          training@intellibitz. Frames ● if you add a <noframes> tag containing some text for browsers that do not support frames.intellibitz.

www. lists. forms. etc. ● A data cell can contain text. Tables ● Tables are defined with the <table> tag. tables.intellibitz. ● A table is divided into rows (with the <tr> tag) ● Each row is divided into data cells (with the <td> tag).com . paragraphs. horizontal rules.com                                                                                                                          training@intellibitz. images.

cell 2</td> </tr> </table> www.com .com                                                                                                                          training@intellibitz. cell 1</td> <td>row 2. cell 1</td> <td>row 1.intellibitz. cell 2</td> <td>row 1. cell 1</td> <th>Heading</th> <td>row 1. Tables <table border="1"> <table border="1"> <tr> <tr> <td>row 1. cell 2</td> </tr> </tr> </table> <tr> <td>row 2. cell 1</td> <td>row 2. cell 2</td> <th>Another Heading</th> </tr> </tr> <tr> <tr> <td>row 2.

● A definition list is not a list of items.intellibitz.com . ● An ordered list is also a list of items. This is a list of terms and explanation of the terms.com                                                                                                                          training@intellibitz. www. The list items are marked with numbers. List ● An unordered list is a list of items. The list items are marked with bullets (typically small black circles).

List <dl> <ul> <ol> <dt>Coffee</dt> <li>Coffee</li> <li>Coffee</li> <dd>Black hot drink</dd> <li>Milk</li> <li>Milk</li> <dt>Milk</dt> </ul> </ol> <dd>White cold drink</dd> </dl> www.com .com                                                                                                                          training@intellibitz.intellibitz.

com                                                                                                                          training@intellibitz.gif" alt="Big Boat"> www. ● Img tag has no closing tag. <img src="boat. Image ● With HTML you can display images in a document.com .intellibitz. ● The src attribute of img tag should be assigned with the path of the file.

to improve the display www.com                                                                                                                          training@intellibitz. ● The browser will then display the alternate text instead of the image.intellibitz. ● It is a good practice to include the "alt" attribute for each image on a page.com . Image ● The "alt" attribute tells the reader what he or she is missing on a page if the browser can't load images.

– The bgcolor attribute specifies a background-color for an HTML page. www. Background ● The <body> tag has two attributes where you can specify backgrounds.intellibitz.com                                                                                                                          training@intellibitz. – The background attribute specifies a background- image for an HTML page.com . ● The background can be a color or an image.

com .intellibitz.that is there is a physical break ● between it and elements above and below it ● A <span> isn't block level instead its inline so you can apply it to for instance a single phrase within a sentence. www.com                                                                                                                          training@intellibitz. <div> <span> ● A <div> is a block value element .

radio buttons.com                                                                                                                                 training@intellibitz. Web form ● Web form are used to get data from the user.intellibitz. www. textarea fields. ● Form elements are elements that allow the user to enter information (like text fields.com www. etc.com .com                                                                                                                          training@intellibitz. checkboxes.) in a form.intellibitz. drop-down menus.

intellibitz. www.com www.com                                                                                                                                 training@intellibitz.com                                                                                                                          training@intellibitz. <form> tag ● <form> tag serves to define the section of HTML document that contain form fields ● Attributes – Action ● The URL that the form is submitted to – Method ● The method under which the form is submitted(GET or POST) – Enctype ● The encoding type to use(miltipart/formdata).com .intellibitz.

● <input type = “text”> tag can be used to define a textbox ● Attributes – Name ● The name assigned to the textbox.intellibitz. www.this will be the key to $_POST[ ] .com                                                                                                                          training@intellibitz. Text box ● Text box is a single line text field.com . – Size ● The size of the text fields in browser in character.

– Value ● The default value of the textbox. ● This value will be displayed inside the textbox on the browser.com www. www.com                                                                                                                                 training@intellibitz.intellibitz.com                                                                                                                          training@intellibitz.com .intellibitz. Textbox – Maxlength ● The maximum number of character to accept in the textfields.

com .intellibitz. www. ● The attributes of password field are same as text field.com                                                                                                                                 training@intellibitz.com www. Password fields ● Password field masks the input so that it cannot be read on the screen.intellibitz.com                                                                                                                          training@intellibitz.

intellibitz.com                                                                                                                          training@intellibitz.intellibitz.the name attribute of option button must have the same value. www.com .com                                                                                                                                 training@intellibitz.com www. Option button ● Option button allows the user to select the single item from the list of options. ● The option button can be created in HTML can be created by setting type attribute of <input> tag to radio ● For a group of option buttons to function properly.

intellibitz.com .com www. Option button ● The value attribute will not be diaplayed in the browser but but instead the value submitted when the form is submitted. ● The checked value will be the default selected value and only one checked attribute can exist .com                                                                                                                          training@intellibitz.com                                                                                                                                 training@intellibitz.intellibitz. www.

intellibitz. ● Unlike an option button it is not required that each check box require same name and there is no restriction on how many checked value can exist www. Check box ● The check box allows the user to select the any number of the provided option.com                                                                                                                          training@intellibitz.com .com                                                                                                                                 training@intellibitz.com www.intellibitz.

intellibitz. ● Drop-down lists – A list can be displayed as single line and user clicks the arrow button to see all the choices www.com .intellibitz. Lists and drop-down lists ● Lists A list can be in a standard scrollable box where one – or more items can be selected.com                                                                                                                                 training@intellibitz.com                                                                                                                          training@intellibitz.com www.

intellibitz.com . ● Attributes – Name ● The name given to the list. Lists and drop-down lists ● A <select> tag defines a list.com                                                                                                                          training@intellibitz. – Multiple ● A flag indicating whether multiple items can be selected www. – Size ● The number of items to display at once in the lists (a value of one indicates a dropdown lists).

– Selected ● A flag indicating if this item is selected by default. www.com .com                                                                                                                          training@intellibitz.intellibitz. Lists and drop-down lists ● <option> tag is used to represent items in the lists ● Attributes – Value ● The value to submit if selected.

com                                                                                                                          training@intellibitz.intellibitz. Lists and drop-down lists www.com .

com .intellibitz. www.com                                                                                                                          training@intellibitz. submit ● For any form data to be sent from client to server it must be submitted. ● Submit defines a button which enables the user to submit a form.

com                                                                                                                          training@intellibitz. www. Image ● <input type = “image”> is identical to <input type = “submit”>except thet instead of displaying a button it displays a specific image.com .intellibitz.

Hidden ● Along with user editable data.HTML also allows to send uneditable hidden data to the server.intellibitz.com .com                                                                                                                          training@intellibitz. www.

Textarea ● Textarea is the multiline text field. ● Attributes – Name ● Name of the field – Cols ● Number of columns wide (in characters)of the text field – Rows ● Number of rows long www.intellibitz.com .com                                                                                                                          training@intellibitz.

● It will run past the edge of the text field. ● Text will be sent exactly as typed.com .intellibitz.com                                                                                                                          training@intellibitz. www. Textarea – Wrap Determines how the text should be submitted ● in relation to how it was typed in text area ● Wrap attribute accepts one of the following values – Off ● The text field will not wrap at all.

Textarea – Soft ● Text will be wrap to text field but sent exactly as typed – Hard ● Text will wrap to text field ● The submission will contain new character at every wrapping point. www.com                                                                                                                          training@intellibitz.com .intellibitz.

intellibitz. File upload ● <input type = “file”> tag allows the client browser(user) to browse the local file system and select a file to uplooad to the web server.com                                                                                                                          training@intellibitz. ● Attributes – Name ● Name of the file field – Size ● Size of the file field (in characters) – Maxlength ● Maximum length of the text field www.com .

and save it all in a text file that any browser can read and display. input forms.com                                                                                                                          training@intellibitz. ● The key to HTML is the tags. create links. which indicates what content is coming up.com .. etc.intellibitz. add graphics. www. ● HTML lets you format text. Summary ● HTML is the universal markup language for the Web. frames and tables.

com .com                                                                                                                          training@intellibitz.intellibitz. CHAPTER 7 PHP AND WEB FORMS www.

com                                                                                                                     training@intellibitz.intellibitz.com . Making Web Forms ● Useful Server Variables ● Accessing Form Parameters ● Form Processing with Functions ● Validating Data ● HTML and JavaScript ● Displaying Default Values ● Putting it all together www.

www. ● $_GET and $_POST auto global array ● $_SERVER holds request and server information. ● Beware of submitted form parameter.com . Making Web Forms ● Forms are how users communicate with your web server.com                                                                                                                     training@intellibitz. can contain embedded HTML or JavaScript.intellibitz.

Accessing Form Parameters ● A form element with multiple values needs to have a name that ends in [] ● Forms can be made flexible by putting the display code and processing code in separate functions ● Data validation is also made easy by using form processing functions www.com                                                                                                                     training@intellibitz.intellibitz.com .

intellibitz.com . www. Validating Data ● Use regular expressions to match text patterns.com                                                                                                                     training@intellibitz. ● Use intval() and floatval() to ensure number. ● Use strlen() when checking a required. ● Take advantage of the fact that an empty array evaluates to false. element instead of testing the value itself in an if() statement.

Validating Form Data ● Use trim() when validating string elements.intellibitz. ● Beware of making changes to $_POST auto-global inside your validation functions. www.com . ● Use arrays for display and validation of <select> menus.com                                                                                                                     training@intellibitz.

intellibitz. www. HTML and JavaScript ● Beware of cross-site scripting attack ● To prevent cross-site scripting attacks. ● Use strip_tags() and htmlentities().com                                                                                                                     training@intellibitz.com . never display unmodified external input. ● Always use htmlentities() to sanitize external input use strip_tags() only when you are absolutely sure.

com .com                                                                                                                     training@intellibitz.intellibitz. Displaying Default Values ● Use default values to display prepopulated form. www. ● Use the previous values entered by user to redisplay a form because of an error ● For <select> menus. add a check to the loop that prints out the <option> tags that prints a selected=”selected” attribute when appropriate.

● Processing the submitted data if it is valid.intellibitz. the form with error messages and preserved user input if the submitted data isn't valid. Putting It All Together ● Displaying a form. www. including default values ● Validating the submitted data. ● Redisplaying.com .com                                                                                                                     training@intellibitz.

com                                                                                                                     training@intellibitz. Chapter Summary ● Understanding the conversation between the web browser and web server that displays a form.com . processes the submitted form parameters. and then displays a result ● Making the connection between the <form> tag's action attribute and the URL to which form parameters are submitted www.intellibitz.

intellibitz. Chapter Summary ● Using values from the $_SERVER auto-global array ● Accessing submitted form parameters in the $_GET and $_POST auto-global arrays ● Accessing multivalued submitted form parameters ● Using show_form(). and process_form() functions for form handling www.com .com                                                                                                                     training@intellibitz. validate_form().

Chapter Summary ● Using a hidden form element to check whether a form has been submitted ● Displaying error messages with a form ● Validating form elements: required elements. and <select> menus www.com . strings.com                                                                                                                     training@intellibitz. email addresses. floating-point numbers. integers.intellibitz. date ranges.

com                                                                                                                     training@intellibitz.intellibitz. ● Displaying default values for form elements.com . ● Using helper functions to display form elements. www. Chapter Summary ● Removing submitted HTML and JavaScript before displaying it.

CHAPTER 8 PHP AND DATABASE www.intellibitz.com .com                                                                                                                     training@intellibitz.

Databases ● Organizing Data in a Database ● Connecting to a Database Program ● Putting Data into the Database ● Inserting Form Data Safely ● Generating Unique ID's ● A Complete Data Insertion Form ● Retrieving Data from a Database ● MySQL without PEAR DB www.intellibitz.com .com                                                                                                                     training@intellibitz.

com                                                                                                                     training@intellibitz.com . PEAR DB ● PEAR DB is an add-on to PHP that simplifies communication between PHP and Database ● PEAR (PHP Extension and Application Repository) is a collection of useful modules and libraries for PHP ● DB module is one of the most popular PEAR modules and is bundled with PHP www.intellibitz.

DELETE.com                                                                                                                     training@intellibitz. which have rows and columns ● Tables are like Spreadsheet. UPDATE. except the rows in a database table have no inherent order ● SQL is a language to ask questions of and give instruction to the database program ● SQL keywords are not case sensitive ● INSERT. Organizing Data in a Database ● Information in your database is organized in tables.com .intellibitz. SELECT www.

● DB::isError () checks if object contains error information www.php'.com . ● Use include in place of require if you want strict checking ● DSN is passed to DB::connect () ● $db = DB::connect ('db://user:pass@host/schema'). Connecting to a Database ● Use require 'DB.intellibitz.com                                                                                                                     training@intellibitz.

intellibitz. ● price DECIMAL(4.2).com . Creating a Table ● CREATE TABLE dishes ( ● dish_id INT.com                                                                                                                     training@intellibitz. ● is_spicy INT ● ) ● DROP TABLE dishes www. ● dish_name VARCHAR(255).

intellibitz. ● Use setErrorHandling() to have your program automatically print an error message and exit if a query fails www...com                                                                                                                     training@intellibitz. Putting Data into Database ● Pass an INSERT statement to the object's query() function ● $q = $db->query(“INSERT here.”).com .

intellibitz. Inserting Form Data Safely ● Beware of SQL injection attack ● Some databases let you pass multiple queries seperated by semicolons in one call of query() ● Escape special characters (apostrophe) ● PEAR DB provides a helpful feature called placeholders www.com .com                                                                                                                     training@intellibitz.

com . give them each a unique identifier ● PEAR DB helps you generate unique integer Ids with its support for sequences ● Use nextID() to get the next value from a sequence www.intellibitz.com                                                                                                                     training@intellibitz. Generating Unique IDs ● To identify individual database records.

com . fetchRow() returns false ● Use numrows() to find number of rows returned by a SELECT query ● Wildcards _ matches one character and the % sign matches any number including zero www. when no rows left. Retrieving Data from Database ● Use fetchRow() to get the next row returned from the query.intellibitz.com                                                                                                                     training@intellibitz.

com                                                                                                                     training@intellibitz.com .intellibitz. www. mysqli extension can be used ● $db = mysqli_connect ('db. MySQL without PEAR DB ● A program that uses the built-in PHP functions tailored to a particular database is faster than the one that uses PEAR DB ● For database access without PEAR DB. 'pass'.intellibitz. 'schema'). 'user'.com'.

com .intellibitz.com                                                                                                                     training@intellibitz. Chapter Summary ● Figuring out what kinds of information belong in a database ● Understanding how data is organized in a database ● Loading an external file with require ● Establishing a database connection ● Creating a table in the database ● Removing a table from the database www.

com .com                                                                                                                     training@intellibitz. Chapter Summary ● Using the SQL INSERT command ● Inserting data into the database with query () ● Checking for database errors with DB::isError() ● Setting up automatic error handling with setErrorHandling() ● Using the SQL UPDATE and DELETE commands www.intellibitz.

com                                                                                                                     training@intellibitz.com . Chapter Summary ● Changing or deleting data with query() ● Counting the number of rows affected by a query ● Using placeholders to insert data safely ● Generating unique ID values with sequences ● Using the SQL SELECT command ● Retrieving data from the database with query() and fetchRow() www.intellibitz.

and getOne() ● Using the SQL ORDER BY and LIMIT keywords with SELECT ● Retrieving rows as string-keyed arrays or objects www.com                                                                                                                     training@intellibitz. getRow().intellibitz. Chapter Summary ● Counting the number of rows retrieved by query() ● Retrieving data with getAll().com .

com .intellibitz.com                                                                                                                     training@intellibitz. Chapter Summary ● Using the SQL wildcards with LIKE % and _ ● Escaping SQL wildcards in SELECT ● Saving submitted form parameters in the database ● Using data from the database in form elements ● Using the mysqli functions instead of PEAR DB www.

com                                                                                                                     training@intellibitz.com .intellibitz. CHAPTER 9 PHP AND MySQL FUNCTIONS www.

com . resource $link_identifier] ) ● mysql_query() sends an unique query (multiple queries are not supported) to the currently active database on the server that's associated with the specified link_identifier.com                                                                                                                     training@intellibitz. www. mysql_query ● Send a MySQL query ● resource mysql_query ( string $query [.intellibitz.

www. the last link opened by mysql_connect() is assumed. If the link identifier is not specified.intellibitz. If no such link is found.com                                                                                                                     training@intellibitz. mysql_query ● Parameters – query A SQL query ● ● The query string should not end with a semicolon. an E_WARNING level warning is generated. – link_identifier ● The MySQL connection. If by chance no connection is found or established. it will try to create one as if mysql_connect() was called with no arguments.com .

● Use mysql_num_rows() to find out how many rows were returned for a SELECT statement or mysql_affected_rows() to find out how many rows were affected by a DELETE.com                                                                                                                     training@intellibitz. DROP. INSERT. DESCRIBE or EXPLAIN statements. UPDATE. mysql_query() returns TRUE on success or FALSE on error.intellibitz.com . ● The returned result resource should be passed to mysql_fetch_array(). SHOW. ● mysql_query() will also fail and return FALSE if the user does not have permission to access the table(s) referenced by the query. to access the returned data. REPLACE. DELETE. www. ● For other type of SQL statements. etc. or UPDATE statement. or FALSE on error. mysql_query ● Return Values ● For SELECT. and other functions for dealing with result tables. mysql_query() returns a resource on success.

note that specifying a numeric offset for the field argument is much quicker than specifying a fieldname or tablename.intellibitz. www. As these functions return the contents of multiple cells in one function call.fieldname argument. they're MUCH quicker than mysql_result().com                                                                                                                     training@intellibitz. mysql_result ● Get result data ● string mysql_result ( resource $result.com . Also. int $row [. ● When working on large result sets. you should consider using one of the functions that fetch an entire row (specified below). mixed $field] ) ● Retrieves the contents of one cell from a MySQL result set.

the field's name. If undefined. mysql_result ● Parameters – result ● The result resource that is being evaluated.com . use the alias instead of the column name.fieldname). – row ● The row number from the result that's being retrieved. Row numbers start at 0..intellibitz. the first field is retrieved. or the field's table dot field name (tablename. www. This result comes from a call to mysql_query(). – field ● The name or offset of the field being retrieved. ● It can be the field's offset. If the column name has been aliased ('select foo as bar from.com                                                                                                                     training@intellibitz..').

com                                                                                                                     training@intellibitz. mysql_error()). } echo mysql_result($result. 'mysql_password').intellibitz. failure. mysql_error()). or if (!$result) { FALSE on    die('Could not query:' . MySQL } result set on $result = mysql_query('SELECT name FROM work. of one cell if (!$link) { from a    die('Could not connect: ' . 'mysql_user'.com .employee'). mysql_result ● Return Values <?php ● The contents $link = mysql_connect('localhost'. success. ?> www. // outputs third employee's name mysql_close($link). 2).

resource $link_identifier] ) ● Sets the current active database on the server that's associated with the specified link identifier.com                                                                                                                     training@intellibitz. www. Every subsequent call to mysql_query() will be made on the active database. mysql_selest_db ● Select a MySQL database ● bool mysql_select_db ( string $database_name [.intellibitz.com .

If no such link is found. – link_identifier ● The MySQL connection.com                                                                                                                     training@intellibitz. an E_WARNING level warning is generated. If the link identifier is not specified.intellibitz. the last link opened by mysql_connect() is assumed. it will try to create one as if mysql_connect() was called with no arguments. mysql_select_db ● Parameters – database_name ● The name of the database that is to be selected.com . If by chance no connection is found or established. www.

 'mysql_password'). } // make foo the current db $db_selected = mysql_select_db('foo'.com                                                                                                                     training@intellibitz. mysql_error()).com . } ?> www. if (!$db_selected) {    die ('Can\'t use foo : ' . success or FALSE on if (!$link) { failure.    die('Not connected : ' . 'mysql_user'. mysql_error()).intellibitz. $link). mysql_select_db ● Return Values <?php ● Returns TRUE on $link = mysql_connect('localhost'.

mysql_affected_rows ● mysql_affected_rows — Get number of affected rows in previous MySQL operation ● int mysql_affected_rows ( [resource $link_identifier] ) ● Get the number of affected rows by the last INSERT.com . www.intellibitz. UPDATE.com                                                                                                                     training@intellibitz. REPLACE or DELETE query associated with link_identifier.

mysql_affected_rows ● Parameters ● link_identifier – The MySQL connection.com                                                                                                                     training@intellibitz.intellibitz. If no such link is found. it will try to create one as if mysql_connect() was called with no arguments. the last link opened by mysql_connect() is assumed. If the link identifier is not specified. ● www. If by chance no connection is found or established. an E_WARNING level warning is generated.com .

This function returns the number of deleted records plus the number of inserted records. and -1 if the last query failed. only the number of rows that were literally affected by the query.com                                                                                                                     training@intellibitz. www. This creates the possibility that mysql_affected_rows() may not actually equal the number of rows matched. mysql_affected_rows ● Return Values ● Returns the number of affected rows on success.1.2. all of the records will have been deleted from the table but this function will return zero with MySQL versions prior to 4. ● When using UPDATE. ● The REPLACE statement first deletes the record with the same primary key and then inserts the new record.com .intellibitz. MySQL will not update columns where the new value is the same as the old value. ● If the last query was a DELETE query with no WHERE clause.

 'mysql_user'. it should return  } 0 */ mysql_select_db('mydb'). Records deleted: 0 www. mysql_error()). /* with a where clause that is never true.com . mysql_affected_rows()). mysql_affected_rows()). 'mysql_password'). /* this should return the correct numbers of deleted records */?> mysql_query('DELETE FROM mytable WHERE id < 10').com                                                                                                                     training@intellibitz. printf("Records deleted: %d\n". if (!$link) {    die('Could not connect: ' . The above example will output something similar to: Records deleted: 10 printf("Records deleted: %d\n". mysql_affected_row <?php $link = mysql_connect('localhost'.intellibitz. mysql_query('DELETE FROM mytable WHERE 0').

 mysql_error()).    die('Could not connect: ' . mysql_query("UPDATE mytable SET used=1 WHERE id  < 10"). The above example will output something similar to: Updated Records: 10 www. if (!$link) { printf ("Updated records: %d\n". mysql_affected_rows()). mysql_query("COMMIT").com                                                                                                                     training@intellibitz. mysql_affected_rows <?php /* Update records */ $link = mysql_connect('localhost'.com .  'mysql_password').intellibitz. 'mysql_user'. } ?> mysql_select_db('mydb').

string $password [. the current connected user stays active. string $database [. ● This function is deprecated and no longer exists in PHP.intellibitz.com                                                                                                                     training@intellibitz. this will be the current database after the user has been changed. www. If a database is specified.com . or the connection given by the optional link_identifier parameter. resource $link_identifier]] ) ● mysql_change_user() changes the logged in user of the current active connection. If the new user and password authorization fails. mysql_change_user ● mysql_change_user — Change logged in user of the active connection ● int mysql_change_user ( string $user.

mysql_change_user ● Parameters ● user ● The new MySQL username.com                                                                                                                     training@intellibitz. an E_WARNING level warning is generated. – password ● The new MySQL password. – database ● The MySQL database. If no such link is found. If by chance no connection is found or established. it will try to create one as if mysql_connect() was called with no arguments. If not specified. If the link identifier is not specified. the last link opened by mysql_connect() is assumed. the current selected database is used. www.intellibitz.com . – link_identifier ● The MySQL connection. ● Return Values – Returns TRUE on success or FALSE on failure.

If by chance no connection is found or established. If no such link is found. mysql_client_encoding ● mysql_client_encoding — Returns the name of the character set ● string mysql_client_encoding ( [resource $link_identifier] ) ● Retrieves the character_set variable from MySQL. www.com                                                                                                                     training@intellibitz. an E_WARNING level warning is generated. the last link opened by mysql_connect() is assumed.com . ● Parameters – link_identifier ● The MySQL connection. it will try to create one as if mysql_connect() was called with no arguments.intellibitz. If the link identifier is not specified.

mysql_client_encoding <?php $link = mysql_connect('localhost'. 'mysql_password'). echo "The current character set is: $charset\n".com . $charset = mysql_client_encoding($link).com                                                                                                                     training@intellibitz. 'mysql_user'.intellibitz. ?> The above example will output something similar to: The current character set is: latin1 www.

If by chance no connection is found or established.com                                                                                                                     training@intellibitz. an E_WARNING level warning is generated.com . the last link opened by mysql_connect() is assumed. www. ● Using mysql_close() isn't usually necessary. ● Parameters – link_identifier ● The MySQL connection. the last opened link is used. mysql_close ● mysql_close — Close MySQL connection ● Description ● bool mysql_close ( [resource $link_identifier] ) ● mysql_close() closes the non-persistent connection to the MySQL server that's associated with the specified link identifier. ● Return Values ● Returns TRUE on success or FALSE on failure. See also freeing resources. it will try to create one as if mysql_connect() was called with no arguments. If the link identifier is not specified. If link_identifier isn't specified. If no such link is found. as non-persistent open links are automatically closed at the end of the script's execution.intellibitz.

intellibitz.com . 'mysql_user'. mysql_close($link). <?php mysql_close $link = mysql_connect('localhost'. } echo 'Connected successfully'. 'mysql_password'). mysql_error()). ?> The above example will output: Connected successfully www.com                                                                                                                     training@intellibitz. if (!$link) { die('Could not connect: ' .

www. string $password [.intellibitz. bool $new_link [. mysql_connect ● mysql_connect — Open a connection to a MySQL Server ● resource mysql_connect ( [string $server [.com . int $client_flags]]]]] ) ● Opens or reuses a connection to a MySQL server. string $username [.com                                                                                                                     training@intellibitz.

– username ● The username.intellibitz. this parameter is ignored and value 'localhost:3306' is always used.g. ● If the PHP directive mysql. then the default value is 'localhost:3306'. e. "hostname:port" or a path to a local socket e.default_host is undefined (default).default_user. It can also include a port number. this parameter is ignored and the name of the user that owns the server process is used. mysql_connect ● Parameters – server ● The MySQL server.com                                                                                                                     training@intellibitz. www. ":/path/to/socket" for the localhost. In SQL safe mode.com .g. In SQL safe mode. Default value is defined by mysql.

The new_link parameter modifies this behavior and makes mysql_connect() always open a new link.intellibitz. the link identifier of the already opened link will be returned.com . but instead.com                                                                                                                     training@intellibitz. even if mysql_connect() was called before with the same parameters. – new_link ● If a second call is made to mysql_connect() with the same arguments. mysql_connect ● password ● The password. no new link will be established. Default value is defined by mysql. this parameter is ignored and empty password is used. In SQL safe mode. – www. this parameter is ignored. In SQL safe mode.default_password.

Read the section about Table 173. In SQL safe mode. or FALSE on failure. “MySQL client constants” for further information. MYSQL_CLIENT_IGNORE_SPACE or MYSQL_CLIENT_INTERACTIVE.com                                                                                                                     training@intellibitz. MYSQL_CLIENT_COMPRESS. – Return Values ● Returns a MySQL link identifier on success.intellibitz. mysql_connect ● client_flags The client_flags parameter can be a combination of ● the following constants: MYSQL_CLIENT_SSL.com . www. this parameter is ignored.

com .0.com:3307'. } echo 'Connected successfully'. 'mysql_user'. // we connect to localhost at port 3307 mysql_close($link).com                                                                                                                     training@intellibitz.intellibitz. mysql_close($link). mysql_error()). 'mysql_password'). if (!$link) {    die('Could not connect: ' . mysql_error()). ?> www. $link = mysql_connect('127. mysql_connect <?php // we connect to example.1:3307'.com and port 3307 $link = mysql_connect('example. if (!$link) {    die('Could not connect: ' . 'mysql_password').0. 'mysql_user'. }echo 'Connected successfully'.

it will try to create one as if mysql_connect() was called with no arguments. mysql_connect ● Parameters – database_name ● The name of the database being created.intellibitz.com                                                                                                                     training@intellibitz. www. – link_identifier ● The MySQL connection. an E_WARNING level warning is generated. If the link identifier is not specified. ● Return Values – Returns TRUE on success or FALSE on failure. If no such link is found. the last link opened by mysql_connect() is assumed.com . If by chance no connection is found or established.

com                                                                                                                     training@intellibitz.com . resource $link_identifier] ) ● mysql_create_db() attempts to create a new database on the server associated with the specified link identifier. www.intellibitz. mysql_create_db ● Create a MySQL database ● bool mysql_create_db ( string $database_name [.

if (mysql_query($sql. 'mysql_user'. if (!$link) {    die('Could not connect: ' . } else {    echo 'Error creating database: ' . <?php mysql_create_db $link = mysql_connect('localhost'. "\n".com                                                                                                                     training@intellibitz.intellibitz. mysql_error() . 'mysql_password').com . } $sql = 'CREATE DATABASE my_db'. } ?> The above example will output something similar to: Database my_db created successfully www. mysql_error()). $link)) {    echo "Database my_db created successfully\n".

would return that row. a seek to 0 will fail with a E_WARNING and mysql_data_seek() will return FALSE. www. ● row_number starts at 0. The row_number should be a value in the range from 0 to mysql_num_rows() . However if the result set is empty (mysql_num_rows() == 0). int $row_number ) ● mysql_data_seek() moves the internal row pointer of the MySQL result associated with the specified result identifier to point to the specified row number. such as mysql_fetch_assoc(). The next call to a MySQL fetch function. mysql_data_seek ● Move internal result pointer ● bool mysql_data_seek ( resource $result.intellibitz.1.com                                                                                                                     training@intellibitz.com .

intellibitz.com                                                                                                                     training@intellibitz. – row_number ● The desired row number of the new result pointer. This ● result comes from a call to mysql_query(). ● Return Values – Returns TRUE on success or FALSE on failure. www. mysql_data_seek ● Parameters – result The result resource that is being evaluated.com .

mixed $field] ) ● ● Retrieve the database name from a call to mysql_list_dbs().com                                                                                                                     training@intellibitz. int $row [.com . mysql_db_name ● Get result data ● Description ● string mysql_db_name ( resource $result.intellibitz. www.

www. mysql_db_name ● Parameters – result ● The result pointer from a call to mysql_list_dbs().intellibitz.com                                                                                                                     training@intellibitz. ● – Return Values ● Returns the database name on success.com . use mysql_error() to determine the nature of the error. – row ● The index into the result set. If FALSE is returned. and FALSE on failure. – field The field name.

mysql_db_name <?php error_reporting(E_ALL). $cnt = mysql_num_rows($db_list). 'username'. } www. 'password').com ?> . $link = mysql_connect('dbhost'. $db_list = mysql_list_dbs($link).intellibitz. $i = 0.    $i++.com                                                                                                                     training@intellibitz. $i) . while ($i < $cnt) {    echo mysql_db_name($db_list. "\n".

or FALSE on error. mysql_db_query ● Send a MySQL query ● resource mysql_db_query ( string $database. an E_WARNING level warning is generated. string $query [. and executes a query on it. ● Parameters – database ● The name of the database that will be selected.com                                                                                                                     training@intellibitz. – link_identifier ● ● The MySQL connection. If by chance no connection is found or established. resource $link_identifier] ) ● mysql_db_query() selects a database. it will try to create one as if mysql_connect() was called with no arguments.com . If the link identifier is not specified. the last link opened by mysql_connect() is assumed. www. – query ● The MySQL query. ● Return Values ● Returns a positive MySQL result resource to the query result. If no such link is found.intellibitz. The function also returns TRUE/FALSE for INSERT/UPDATE/DELETE queries to indicate success/failure.

}    exit. could not query the database\n". mysql_db_query $sql    = 'SELECT foo FROM bar WHERE id = 42'. <?php $result = mysql_query($sql.com .    echo 'MySQL Error: ' .    echo 'Could not select database'. mysql_error().    exit.  'mysql_user'. if (!$result) { if (!$link = mysql_connect('mysql_host'. mysql_free_result($result).    exit.    echo 'Could not connect to mysql'.intellibitz. $link). $link)) {    echo $row['foo']. 'mysql_password')) {    echo "DB Error. } } while ($row = mysql_fetch_assoc($result)) { if (!mysql_select_db('mysql_dbname'. } ?> www.com                                                                                                                     training@intellibitz.

it is preferable to use mysql_query() to issue a sql DROP DATABASE statement instead.intellibitz. This function is deprecated. www.com                                                                                                                     training@intellibitz. resource $link_identifier] ) ● mysql_drop_db() attempts to drop (remove) an entire database from the server associated with the specified link identifier. mysql_drop_db ● Drop (delete) a MySQL database ● bool mysql_drop_db ( string $database_name [.com .

com . If by chance no connection is found or established. If no such link is found. the last link opened by mysql_connect() is assumed. If the link identifier is not specified. – Return Values ● Returns TRUE on success or FALSE on failure. – link_identifier ● The MySQL connection. www. an E_WARNING level warning is generated.com                                                                                                                     training@intellibitz.intellibitz. it will try to create one as if mysql_connect() was called with no arguments. mysql_drop_db ● Parameters – database_name ● The name of the database that will be deleted.

com ?> . "\n". } www. $link)) {    echo "Database my_db was successfully dropped\n". mysql_drop_db mysql_drop_db() alternative example <?php $link = mysql_connect('localhost'. } else {    echo 'Error dropping database: ' .com                                                                                                                     training@intellibitz. if (!$link) {    die('Could not connect: ' . mysql_error() . if (mysql_query($sql. } $sql = 'DROP DATABASE my_db'.  'mysql_password'). 'mysql_user'. mysql_error()).intellibitz.

com . so if you want to use it.com                                                                                                                     training@intellibitz. ● Errors coming back from the MySQL database backend no longer issue warnings. www.intellibitz. make sure you check the value before calling another MySQL function. Note that this function only returns the error code from the most recently executed MySQL function (not including mysql_error() and mysql_errno()). mysql_errno ● Returns the numerical value of the error message from previous MySQL operation ● int mysql_errno ( [resource $link_identifier] ) ● Returns the error number from the last MySQL function. Instead. use mysql_errno() to retrieve the error code.

nonexistenttable' doesn't exist www. $link)) {    echo mysql_errno($link) . "mysql_user". if (!mysql_select_db("nonexistentdb". mysql_error($link) . mysql_error($link). ": " . mysql_errno <?php $link = mysql_connect("localhost". $link)) {    echo mysql_errno($link) . if (!mysql_query("SELECT * FROM nonexistenttable".com . } The above example will output something similar to: ?> 1049: Unknown database 'nonexistentdb' 1146: Table 'kossu.com                                                                                                                     training@intellibitz. $link). ": " . } mysql_select_db("kossu". "\n". "\n".intellibitz.  "mysql_password").

www. Note that this function only returns the error text from the most recently executed MySQL function (not including mysql_error() and mysql_errno()). so if you want to use it.intellibitz. use mysql_error() to retrieve the error text. make sure you check the value before calling another MySQL function.com .com                                                                                                                     training@intellibitz. Errors coming back from the MySQL database backend no longer issue warnings. mysql_error ● Returns the text of the error message from previous MySQL operation ● string mysql_error ( [resource $link_identifier] ) ● Returns the error text from the last MySQL function. Instead.

If the link identifier is not specified. www. If by chance no connection is found or established. the last link opened by mysql_connect() is assumed.com                                                                                                                     training@intellibitz. or '' (empty string) if no error occurred. it will try to create one as if mysql_connect() was called with no arguments. mysql_error ● Parameters ● link_identifier – The MySQL connection.intellibitz. ● Return Values – Returns the error text from the last MySQL function. If no such link is found.com . an E_WARNING level warning is generated.

mysql_select_db("kossu".intellibitz. ?> The above example will output something similar to: 1049: Unknown database 'nonexistentdb' 1146: Table 'kossu. echo mysql_errno($link) . mysql_error($link). "\n". mysql_query("SELECT * FROM nonexistenttable". "\n". ": " . mysql_error <?php $link = mysql_connect("localhost". mysql_select_db("nonexistentdb". $link). "mysql_password").nonexistenttable' doesn't exist www. echo mysql_errno($link) .com . ": " . $link).com                                                                                                                     training@intellibitz. mysql_error($link) . "mysql_user". $link).

● This function is identical to mysql_real_escape_string() except that mysql_real_escape_string() takes a connection handler and escapes the string according to the current character set. www. so that it is safe to place it in a mysql_query().com                                                                                                                     training@intellibitz. This function is deprecated.intellibitz.com . mysql_escape_string() does not take a connection argument and does not respect the current charset setting. mysql_escape_string ● Escapes a string for use in a mysql_query ● string mysql_escape_string ( string $unescaped_string ) ● This function will escape the unescaped_string.

  $escaped_item). ● Return Values – Returns the escaped string.com                                                                                                                     training@intellibitz. mysql_escape_string ● Parameters – unescaped_string ● The string that is to be escaped.com . printf("Escaped string: %s\n". ?> The above example will output: Escaped string: Zak\'s Laptop www.intellibitz. $escaped_item =  mysql_escape_string($item). <?php $item = "Zak's Laptop".

It's a constant and can take the following values: MYSQL_ASSOC. MYSQL_NUM.com                                                                                                                     training@intellibitz. ● result_type ● The type of array that is to be fetched. int $result_type] ) ● Returns an array that corresponds to the fetched row and moves the internal data pointer ahead. www. mysql_fetch_array ● Fetch a result row as an associative array.intellibitz. ● Parameters ● result ● The result resource that is being evaluated. a numeric array. or both ● array mysql_fetch_array ( resource $result [. This result comes from a call to mysql_query(). and the default value of MYSQL_BOTH.com .

com . The type of returned array depends on how result_type is defined. For aliased columns. you only get number indices (as mysql_fetch_row() works). ● If two or more columns of the result have the same field names. www. you cannot access the contents with the original column name. By using MYSQL_BOTH (default). mysql_fetch_array ● Return Values ● Returns an array that corresponds to the fetched row. or FALSE if there are no more rows. you only get associative indices (as mysql_fetch_assoc() works). you must use the numeric index of the column or make an alias for the column.intellibitz. To access the other column(s) of the same name. using MYSQL_NUM.com                                                                                                                     training@intellibitz. the last column will take precedence. you'll get an array with both associative and number indices. Using MYSQL_ASSOC.

 "mysql_user". $result = mysql_query("SELECT id.intellibitz. MYSQL_NUM)) {    printf("ID: %s  Name: %s". $row[0].  } mysql_free_result($result).com                                                                                                                     training@intellibitz. while ($row = mysql_fetch_array($result. $row[1]).com . mysql_fetch_array <?php mysql_connect("localhost". mysql_error()). name FROM mytable"). mysql_select_db("mydb"). ?> www. "mysql_password") or    die("Could not connect: " .

www. mysql_fetch_assoc ● Fetch a result row as an associative array ● array mysql_fetch_assoc ( resource $result ) ● Returns an associative array that corresponds to the fetched row and moves the internal data pointer ahead. mysql_fetch_assoc() is equivalent to calling mysql_fetch_array() with MYSQL_ASSOC for the optional second parameter. It only returns an associative array.com                                                                                                                     training@intellibitz.com .intellibitz.

com about aliases. you either need to access the result with numeric indices by using mysql_fetch_row() or add alias names. This result comes from a call to mysql_query().com                                                                                                                     training@intellibitz. the last column will take precedence. See the example at the mysql_fetch_array() description www. .intellibitz. To access the other column(s) of the same name. ● If two or more columns of the result have the same field names. mysql_fetch_assoc ● Parameters – result ● The result resource that is being evaluated. or FALSE if there are no more rows. – Return Values ● Returns an associative array that corresponds to the fetched row.

com                                                                                                                     training@intellibitz.    echo "No rows found. fullname.  mysql_error().        WHERE  userstatus = 1".  mysql_error(). } www. <?php array_fetch_assoc $sql = "SELECT id as userid.  mysql_error().    echo "Unable to connect to DB: " .intellibitz. if (mysql_num_rows($result) == 0) {    exit. nothing to print so am exiting". "mysql_password").    echo "Could not successfully run query ($sql) from DB: " .         FROM  sometable "mysql_user". }    exit. if (!$conn) { $result = mysql_query($sql).   if (!mysql_select_db("mydbname")) { }    echo "Unable to select mydbname: " . }    exit.com . if (!$result) {    exit. userstatus $conn = mysql_connect("localhost".

int $field_offset] ) ● Returns an object containing field information. This result comes from a call to mysql_query(). The field_offset starts at 0.com                                                                                                                     training@intellibitz.com . This function can be used to obtain information about fields in the provided query result. mysql_fetch_field ● Get column information from a result and return as an object ● object mysql_fetch_field ( resource $result [.intellibitz. – field_offset ● The numerical field offset. ● Parameters – result ● The result resource that is being evaluated. the next field that was not yet retrieved by this function is retrieved. If the field offset is not specified. www.

intellibitz. The properties of the object are:  * name ­ column name ●     * table ­ name of the table the column belongs to     * def ­ default value of the column     * max_length ­ maximum length of the column     * not_null ­ 1 if the column cannot be NULL     * primary_key ­ 1 if the column is a primary key     * unique_key ­ 1 if the column is a unique key     * multiple_key ­ 1 if the column is a non­unique  key     * numeric ­ 1 if the column is numeric     * blob ­ 1 if the column is a BLOB     * type ­ the type of the column www.com     * unsigned ­ 1 if the column is unsigned .com                                                                                                                     training@intellibitz. mysql_fetch_fields ● Return Values ● Returns an object containing field information.

   $i++.intellibitz. mysql_fetch_fields $i = 0. $i). not_null:    $meta­>not_null while ($i < mysql_num_fields($result)) { numeric:      $meta­>numeric    echo "Information for column $i:<br />\n".com . primary_key:  $meta­>primary_key echo "<pre>    $meta = mysql_fetch_field($result. table:        $meta­>table blob:        $meta­>blob    if (!$meta) { type:        $meta­>type max_length:  $meta­>max_length        echo "No information available<br />\n".com                                                                                                                     training@intellibitz. } www. default:      $meta­>def    } multiple_key: $meta­>multiple_key unique_key:  $meta­>unique_key    name:        $meta­>name unsigned:    $meta­>unsigned zerofill:    $meta­>zerofill </pre>".

● mysql_fetch_lengths() stores the lengths of each result column in the last row returned by mysql_fetch_row().intellibitz.com                                                                                                                     training@intellibitz. mysql_fetch_length ● Get the length of each output in a result ● array mysql_fetch_lengths ( resource $result ) ● Returns an array that corresponds to the lengths of each field in the last row fetched by MySQL. www. and mysql_fetch_object() in an array. mysql_fetch_array().com . mysql_fetch_assoc(). starting at offset 0.

or FALSE on failure. <?php mysql_fetch_length $result = mysql_query("SELECT id. ( resource that [id] => 42 is being    exit. ?> www. [email] => evaluated. print_r($lengths). ( ● Return Values [0] => 2 – An array of lengths on $lengths = mysql_fetch_lengths($result).com                                                                                                                     training@intellibitz.email  FROM people WHERE id = '42'"). ● Parameters if (!$result) { – result Array ● The result    echo 'Could not run query: ' . print_r($row).intellibitz.com result comes } ) from a call to Array mysql_query(). $row    = mysql_fetch_assoc($result). This user@example.com . [1] => 16 ) success. mysql_error().

array $params]] ) ● Returns an object with properties that correspond to the fetched row and moves the internal data pointer ahead. string $class_name [.com                                                                                                                     training@intellibitz. www.intellibitz.com . mysql_fetch_object ● Fetch a result row as an object ● object mysql_fetch_object ( resource $result [.

com                                                                                                                     training@intellibitz. a stdClass object is returned. If not specified. – Params ● An optional array of parameters to pass to the constructor for class_name objects. mysql_fetch_object ● Parameters – Result The result resource that is being evaluated.com .intellibitz. ● This result comes from a call to mysql_query(). set the properties of and return. – class_name ● The name of the class to instantiate. www.

mysql_fetch_object ● Return Values – Returns an object with properties that correspond to the fetched row.com                                                                                                                     training@intellibitz. Each result column is stored in an array offset. www. or FALSE if there are no more rows. – mysql_fetch_row() fetches one row of data from the result associated with the specified result identifier.intellibitz.com . The row is returned as an array. starting at offset 0.

com                                                                                                                     training@intellibitz. /* this is valid */ while ($row =  echo $row­>field. $row = mysql_fetch_object($result). "user". // echo $row­>0.    echo $row­>fullname.intellibitz.com . mysql_fetch_object <?php <?php mysql_connect("hostname". ?> www.  "password"). mysql_select_db("mydb"). mysql_fetch_object($result)) { /* this is invalid */    echo $row­>user_id. $result = mysql_query("select * from  mytable"). } ?> mysql_free_result($result).

● Parameters ● result ● The result resource that is being evaluated.com                                                                                                                     training@intellibitz.com .intellibitz. www. mysql_fetch_row ● Get a result row as an enumerated array ● array mysql_fetch_row ( resource $result ) ● Returns a numerical array that corresponds to the fetched row and moves the internal data pointer ahead. This result comes from a call to mysql_query().

Each result column is stored in an array offset.com . or FALSE if there are no more rows. mysql_fetch_row ● Return Values ● Returns an numerical array that corresponds to the fetched row. starting at offset 0. The row is returned as an array. ● mysql_fetch_row() fetches one row of data from the result associated with the specified result identifier.com                                                                                                                     training@intellibitz.intellibitz. www.

 // the email value ?> www. mysql_error().com                                                                                                                     training@intellibitz.    exit. if (!$result) {    echo 'Could not run query: ' . mysql_fetch_row <?php $result = mysql_query("SELECT id.intellibitz. // 42 echo $row[1]. echo $row[0].com . } $row = mysql_fetch_row($result).email FROM people WHERE id = '42'").

intellibitz.com                                                                                                                     training@intellibitz. www. mysql_field_flags ● Get the flags associated with the specified field in a result ● string mysql_field_flags ( resource $result. The flags are reported as a single word per flag separated by a single space. so that you can split the returned value using explode(). int $field_offset ) ● mysql_field_flags() returns the field flags of the specified field.com .

com . – field_offset ● The numerical field offset. The field_offset starts at 0. mysql_field_flags ● Parameters – Result The result resource that is being evaluated. www.intellibitz.com                                                                                                                     training@intellibitz. ● This result comes from a call to mysql_query(). If field_offset does not exist. an error of level E_WARNING is also issued.

"auto_increment" and "timestamp". "enum". if your version of MySQL is current enough to support them: "not_null". "unique_key".intellibitz. or FALSE on failure. "binary". "multiple_key". www. "blob". – The following flags are reported.com                                                                                                                     training@intellibitz.com . "zerofill". "primary_key". mysql_field_flags ● Return Values – Returns a string of flags associated with the result. "unsigned".

 $flags)). if (!$result) { not_null primary_key    echo 'Could not run query: ' . [0] => not_null [1] => } primary_key [2] => $flags = mysql_field_flags($result.com . auto_increment ) echo $flags.intellibitz.com                                                                                                                     training@intellibitz. mysql_error(). print_r(explode(' '. <?php mysql_field_flags $result = mysql_query("SELECT id. ?> www. 0). auto_increment Array (    exit.email  FROM people WHERE id = '42'").

www.intellibitz. int $field_offset ) ● mysql_field_len() returns the length of the specified field. The field_offset starts at 0. – field_offset ● The numerical field offset. ● Return Values – The length of the specified field index on success. an error of level E_WARNING is also issued. If field_offset does not exist. or FALSE on failure. ● Parameters – result ● The result resource that is being evaluated. mysql_field_len ● Returns the length of the specified field ● int mysql_field_len ( resource $result.com . This result comes from a call to mysql_query().com                                                                                                                     training@intellibitz.

intellibitz. ?> www.email FROM people WHERE id = '42'"). if (!$result) {    echo 'Could not run query: ' . mysql_field_len <?php $result = mysql_query("SELECT id.    exit. } // Will get the length of the id field as specified in the database // schema. 0).com . mysql_error().com                                                                                                                     training@intellibitz. echo $length. $length = mysql_field_len($result.

if (!$result) {    echo 'Could not run query: ' .com ?> . mysql_field_len <?php $result = mysql_query("SELECT id. 0). } // Will get the length of the id field as specified in the database // schema. www.com                                                                                                                     training@intellibitz. mysql_error().intellibitz. $length = mysql_field_len($result.    exit. echo $length.email FROM people WHERE id =  '42'").

This result comes from a call to mysql_query().com                                                                                                                     training@intellibitz. ● Return Values – The name of the specified field index on success. www. int $field_offset ) ● mysql_field_name() returns the name of the specified field index. ● Parameters – result ● The result resource that is being evaluated. If field_offset does not exist. mysql_field_name ● Get the name of the specified field in a result ● string mysql_field_name ( resource $result.com . The field_offset starts at 0. an error of level E_WARNING is also issued. or FALSE on failure. – field_offset ● The numerical field offset.intellibitz.

/* The users table consists of three fields: $db_selected = mysql_select_db($dbname.com                                                                                                                     training@intellibitz. mysql_error()). 0) . *  user_id if (!$db_selected) { *  username    die("Could not set $dbname: " .com . $link). The above example will output: user_id } password www. 'mysql_password'). *  password. $link = @mysql_connect('localhost'. $link). } */ $res = mysql_query('select * from users'. if (!$link) { ?>    die('Could not connect to MySQL server: ' . mysql_field_name <?php $dbname = 'mydb'. 'mysql_user'. echo mysql_field_name($res.intellibitz.  mysql_error()).  echo mysql_field_name($res. 2). "\n".

intellibitz. the field offset specified in mysql_field_seek() will be returned. mysql_field_seek ● Set result pointer to a specified field offset ● bool mysql_field_seek ( resource $result. If the next call to mysql_fetch_field() doesn't include a field offset.com                                                                                                                     training@intellibitz. www.com . int $field_offset ) ● Seeks to the specified field offset.

The field_offset starts at 0.com . mysql_field_seek ● Parameters – result The result resource that is being ● evaluated. This result comes from a call to mysql_query(). ● Return Values – Returns TRUE on success or FALSE on failure. an error of level E_WARNING is also issued.intellibitz. www. – field_offset ● The numerical field offset.com                                                                                                                     training@intellibitz. If field_offset does not exist.

mysql_field_table ● Get name of the table the specified field is in ● string mysql_field_table ( resource $result. int $field_offset ) ● Returns the name of the table that the specified field is in. www.intellibitz.com .com                                                                                                                     training@intellibitz.

This result comes from a call to mysql_query(). an error of level E_WARNING is also issued. www. mysql_field_table ● Parameters – result The result resource that is being ● evaluated.com .intellibitz. The field_offset starts at 0.com                                                                                                                     training@intellibitz. ● Return Values – The name of the table on success. – field_offset ● The numerical field offset. If field_offset does not exist.

com .    exit. mysql_error(). } // Assuming name is in the people table $table = mysql_field_table($result.comments").com                                                                                                                     training@intellibitz. // people ?> www.intellibitz. echo $table. if (!$result) {    echo 'Could not run query: ' .comment FROM people. 'name'). mysql_field_table <?php $result = mysql_query("SELECT  name.

mysql_field_type ● Get the type of the specified field in a result ● string mysql_field_type ( resource $result.com                                                                                                                     training@intellibitz. but the field type is returned instead.com .intellibitz. www. The arguments are identical. int $field_offset ) ● mysql_field_type() is similar to the mysql_field_name() function.

If field_offset does not exist. – field_offset ● The numerical field offset. ● This result comes from a call to mysql_query(). "blob". ● Return Values – The returned field type will be one of "int". mysql_field_type ● Parameters – result The result resource that is being evaluated. The field_offset starts at 0. and others as detailed in the » MySQL documentation.intellibitz. an error of level E_WARNING is also issued. "real". "string".com                                                                                                                     training@intellibitz. www.com .

intellibitz. " " . $i). $i).    $len  = mysql_field_len($result. mysql_close(). $i++) { $result = mysql_query("SELECT * FROM func").  "mysql_password"). $fields .    $type  = mysql_field_type($result. $rows  = mysql_num_rows($result). $table  = mysql_field_table($result. mysql_select_db("mysql").    $name  = mysql_field_name($result. "     echo $type . echo "The table has the following fields:\n".com . $i). "\n". $len . " record(s)\n". "mysql_username".com                                                                                                                     training@intellibitz. for ($i=0. echo "Your '" . " " . $table . $name . ?> www. " " . <?php mysql_field_type mysql_connect("localhost". 0). fields and " . $fields = mysql_num_fields($result).    $flags = mysql_field_flags($result. $i < $fields. $rows . $i). $flags . } mysql_free_result($result). "' table has " .

com . mysql_field_type Your 'func' table has 4 fields and 1 record(s) The table has the following fields: string name 64 not_null primary_key binary int ret 1 not_null string dl 128 not_null string type 9 not_null enum www.com                                                                                                                     training@intellibitz.intellibitz.

● Return Values – Returns TRUE on success or FALSE on failure. This result comes from a call to mysql_query().com . ● mysql_free_result() only needs to be called if you are concerned about how much memory is being used for queries that return large result sets. ● Parameters – result ● The result resource that is being evaluated. mysql_free_result ● Free result memory ● bool mysql_free_result ( resource $result ) ● mysql_free_result() will free all memory associated with the result identifier result. All associated result memory is automatically freed at the end of the script's execution.intellibitz.com                                                                                                                     training@intellibitz. www.

www.    exit. echo $row['id']. assuming we're done with it afterwords */ $row = mysql_fetch_assoc($result).email FROM people WHERE id = '42'"). } /* Use the result.com                                                                                                                     training@intellibitz.intellibitz. mysql_error(). echo $row['email']. if (!$result) {    echo 'Could not run query: ' . /* Now we free up the result and continue on with our script */ mysql_free_result($result). mysql_free_result <?php $result = mysql_query("SELECT id.com ?> .

com                                                                                                                     training@intellibitz.39 www. ● Return Values ● The MySQL client version. <?php printf("MySQL client info: %s\n".  mysql_get_client_info()).intellibitz.com . ?> The above example will output something similar  to: MySQL client info: 3. mysql_client_info ● Get MySQL client info ● string mysql_get_client_info ( void ) ● mysql_get_client_info() returns a string that represents the client library version.23.

www.com .com                                                                                                                     training@intellibitz. mysql_host_info ● Get MySQL host info ● string mysql_get_host_info ( [resource $link_identifier] ) ● Describes the type of connection in use for the connection. including the server host name.intellibitz.

com                                                                                                                     training@intellibitz. an E_WARNING level warning is generated. If no such link is found. www. If by chance no connection is found or established. ● Return Values – Returns a string describing the type of MySQL connection in use for the connection or FALSE on failure. mysql_host_info ● Parameters – link_identifier ● The MySQL connection. it will try to create one as if mysql_connect() was called with no arguments.intellibitz. the last link opened by mysql_connect() is assumed.com . If the link identifier is not specified.

 mysql_error()). mysql_host_info <?php $link = mysql_connect('localhost'.intellibitz.com . } printf("MySQL host info: %s\n". ?> The above example will output something similar to: MySQL host info: Localhost via UNIX socket www. 'mysql_user'.com                                                                                                                     training@intellibitz. mysql_get_host_info()). if (!$link) {    die('Could not connect: ' . 'mysql_password').

mysql_get_proto_info ● Get MySQL protocol info ● int mysql_get_proto_info ( [resource $link_identifier] ) ● Retrieves the MySQL protocol. If the link identifier is not specified. the last link opened by mysql_connect() is assumed. ● Parameters – link_identifier ● The MySQL connection.intellibitz. If by chance no connection is found or established.com . www. it will try to create one as if mysql_connect() was called with no arguments.com                                                                                                                     training@intellibitz. If no such link is found. an E_WARNING level warning is generated.

com                                                                                                                     training@intellibitz. 'mysql_user'.com . mysql_error()). ?> The above example will output something similar to: MySQL protocol version: 10 www. } printf("MySQL protocol version: %s\n". if (!$link) {    die('Could not connect: ' .intellibitz. <?php $link = mysql_connect('localhost'. or FALSE on failure. mysql_get_proto_info ● Return Values – Returns the MySQL protocol on success. mysql_get_proto_info()). 'mysql_password').

the last link opened by mysql_connect() is assumed.com .com                                                                                                                     training@intellibitz. If the link identifier is not specified. an E_WARNING level warning is generated. If by chance no connection is found or established. If no such link is found.intellibitz. it will try to create one as if mysql_connect() was called with no arguments. mysql_get_server_info ● Get MySQL server info ● string mysql_get_server_info ( [resource $link_identifier] ) ● Retrieves the MySQL server version. www. ● Parameters – link_identifier ● The MySQL connection.

 mysql_error()). 'mysql_password').0.com                                                                                                                     training@intellibitz. mysql_get_server_info ● Return Values – Returns the MySQL server version on success.intellibitz. if (!$link) {    die('Could not connect: ' . } printf("MySQL server version: %s\n". or FALSE on failure. <?php $link = mysql_connect('localhost'. 'mysql_user'.1-alpha www. ?> The above example will output something similar to: MySQL server version: 4. mysql_get_server_info()).com .

the last link opened by mysql_connect() is assumed.com                                                                                                                     training@intellibitz.intellibitz. ● Parameters – link_identifier ● The MySQL connection. If by chance no connection is found or established. mysql_info ● Get information about the most recent query ● string mysql_info ( [resource $link_identifier] ) ● Returns detailed information about the last query.com . www. If no such link is found. it will try to create one as if mysql_connect() was called with no arguments. If the link identifier is not specified. an E_WARNING level warning is generated.

www. mysql_info ● Return Values – Returns information about the statement on success. Statements that are not listed will return FALSE. or FALSE on failure.intellibitz.com                                                                                                                     training@intellibitz. and what the returned value may look like. See the example below for which statements provide information.com .

it will try to create one as if mysql_connect() was called with no arguments. If no such link is found.com                                                                                                                     training@intellibitz.com . mysql_insert_id ● Get the ID generated from the previous INSERT operation ● int mysql_insert_id ( [resource $link_identifier] ) ● Retrieves the ID generated for an AUTO_INCREMENT column by the previous INSERT query. www. If the link identifier is not specified. the last link opened by mysql_connect() is assumed. an E_WARNING level warning is generated. If by chance no connection is found or established. ● Parameters – link_identifier ● The MySQL connection.intellibitz.

www. or FALSE if no MySQL connection was established.intellibitz. mysql_insert_id ● Return Values ● The ID generated for an AUTO_INCREMENT column by the previous INSERT query on success.com .com                                                                                                                     training@intellibitz. 0 if the previous query does not generate an AUTO_INCREMENT value.

 mysql_error()).com . } mysql_select_db('mydb'). mysql_query("INSERT INTO mytable (product) values ('intelli')"). ?> www. mysql_insert_id()). 'mysql_password'). printf("Last inserted record has id %d\n". 'mysql_user'.intellibitz. if (!$link) {    die('Could not connect: ' .com                                                                                                                     training@intellibitz. mysql_insert_id <?php $link = mysql_connect('localhost'.

or any function for result tables. ● function to traverse this result pointer.com                                                                                                                     training@intellibitz. www. mysql_list_dbs ● List databases available on a MySQL server ● resource mysql_list_dbs ( [resource $link_identifier] ) ● Returns a result pointer containing the databases available from the current mysql daemon. such as mysql_fetch_array().com .intellibitz.

If no such link is found. ● Return Values – Returns a result pointer resource on success.com .com                                                                                                                     training@intellibitz. it will try to create one as if mysql_connect() was called with no arguments. mysql_list_dbs ● Parameters – link_identifier ● The MySQL connection. If by chance no connection is found or established. If the link identifier is not specified. the last link opened by mysql_connect() is assumed. www. or FALSE on failure.intellibitz. an E_WARNING level warning is generated.

intellibitz. $db_list = mysql_list_dbs($link). while ($row = mysql_fetch_object($db_list)) {      echo $row­>Database . "\n".com                                                                                                                     training@intellibitz.com . mysql_list_dbs <?php $link = mysql_connect('localhost'. } ?> The above example will output something similar to: database1 database2 database3 www.  'mysql_password'). 'mysql_user'.

intellibitz. resource $link_identifier] ) ● Retrieves information about the given table name. It is preferable to use mysql_query() to issue a SQL SHOW COLUMNS FROM table [LIKE 'name'] statement instead. ● This function is deprecated. mysql_list_fields ● List MySQL table fields ● resource mysql_list_fields ( string $database_name.com                                                                                                                     training@intellibitz. string $table_name [. www.com .

● Return Values ● A result pointer resource on success. – link_identifier – The MySQL connection. If by chance no connection is found or established.com                                                                                                                     training@intellibitz. If no such link is found. If the link identifier is not specified.com . an E_WARNING level warning is generated. or FALSE on failure.intellibitz. the last link opened by mysql_connect() is assumed. www. it will try to create one as if mysql_connect() was called with no arguments. – table_name ● The name of the table that's being queried. mysql_list_fields ● Parameters – database_name ● The name of the database that's being queried.

mysql_list_fields Alternate to deprecated mysql_list_fields() <?php This example will output something  similar to: $result = mysql_query("SHOW COLUMNS FROM sometable"). Array if (!$result) { ( [Field] => id [Type] => int(7)    echo 'Could not run query: ' . [Null] => [Key] => PRI    exit. [Key] => [Default] =>    } [Extra] => ) } ?> www.com . [Default] => [Extra] => } auto_increment ) if (mysql_num_rows($result) > 0) { Array (    while ($row = mysql_fetch_assoc($result)) { [Field] => email [Type] => varchar(100) [Null] =>        print_r($row).com                                                                                                                     training@intellibitz. mysql_error().intellibitz.

If no such link is found. If by chance no connection is found or established. mysql_list_process ● List MySQL processes ● resource mysql_list_processes ( [resource $link_identifier] ) ● Retrieves the current MySQL server threads. ● Parameters – link_identifier ● The MySQL connection. an E_WARNING level warning is generated. www.intellibitz. it will try to create one as if mysql_connect() was called with no arguments. the last link opened by mysql_connect() is assumed.com                                                                                                                     training@intellibitz. If the link identifier is not specified.com .

} The above example will output something similar  to: mysql_free_result($result). $row["Id"]. 'mysql_user'. 1 localhost test Processlist 0 4 localhost mysql sleep 5 ?> www. $row["db"]. $row["Host"]. $row["Time"]). <?php $link = mysql_connect('localhost'. $result = mysql_list_processes($link).com                                                                                                                     training@intellibitz. 'mysql_password'). while ($row = mysql_fetch_assoc($result)){    printf("%s %s %s %s %s\n".intellibitz. mysql_list_processes ● Return Values – A result pointer resource on success.        $row["Command"]. or FALSE on failure.com .

com . It is preferable to use mysql_query() to issue a SQL SHOW TABLES [FROM db_name] [LIKE 'pattern'] statement instead.intellibitz.com                                                                                                                     training@intellibitz. www. resource $link_identifier] ) ● Retrieves a list of table names from a MySQL database. mysql_list_tables ● List tables in a MySQL database ● resource mysql_list_tables ( string $database [. ● This function is deprecated.

If the link identifier is not specified. the last link opened by mysql_connect() is assumed. If no such link is found. ● Return Values – A result pointer resource on success.com                                                                                                                     training@intellibitz. or FALSE on failure. it will try to create one as if mysql_connect() was called with no arguments.intellibitz. www. an E_WARNING level warning is generated.com . If by chance no connection is found or established. msql_list_tables ● Parameters – database ● The name of the database – link_identifier ● The MySQL connection.

$result = mysql_query($sql). } } $sql = "SHOW TABLES FROM $dbname". mysql_list_tables mysql_list_tables() alternative example if (!$result) { <?php    echo "DB Error. mysql_error(). could not list tables\n".    echo 'MySQL Error: ' . mysql_free_result($result).com .     exit. 'mysql_user'. 'mysql_password')) { }    echo 'Could not connect to mysql'. while ($row = mysql_fetch_row($result)) {    exit.intellibitz. ?> www. $dbname = 'mysql_dbname'. if (!mysql_connect('mysql_host'.    echo "Table: {$row[0]}\n".com                                                                                                                     training@intellibitz.

● Parameters ● result ● The result resource that is being evaluated. This result comes from a call to mysql_query(). mysql_num_fields ● Get number of fields in result ● int mysql_num_fields ( resource $result ) ● Retrieves the number of fields from a query. ● Return Values ● Returns the number of fields in the result set resource on success.com                                                                                                                     training@intellibitz. www.com .intellibitz. or FALSE on failure.

email FROM people WHERE id = '42'").intellibitz.    exit.com . mysql_num_fields <?php $result = mysql_query("SELECT id.com                                                                                                                     training@intellibitz. if (!$result) {    echo 'Could not run query: ' . } /* returns 2 because id. mysql_error().email === two fields */ echo mysql_num_fields($result). ?> www.

mysql_num_rows ● Get number of rows in result ● int mysql_num_rows ( resource $result ) ● Retrieves the number of rows from a result set. www. This command is only valid for statements like SELECT or SHOW that return an actual result set. To retrieve the number of rows affected by a INSERT. UPDATE.com                                                                                                                     training@intellibitz. REPLACE or DELETE query. use mysql_affected_rows().intellibitz.com .

intellibitz. ● Return Values – The number of rows in a result set on success. or FALSE on failure.com                                                                                                                     training@intellibitz. ● This result comes from a call to mysql_query(). mysql_num_rows ● Parameters – result The result resource that is being evaluated. www.com .

?> www.com                                                                                                                     training@intellibitz. mysql_select_db("database".intellibitz. mysql_num_rows <?php $link = mysql_connect("localhost". $result = mysql_query("SELECT * FROM table1". "mysql_user". $link). $num_rows = mysql_num_rows($result). $link).com . echo "$num_rows Rows\n". "mysql_password").

If one is found. int $client_flags]]]] ) ● Establishes a persistent connection to a MySQL server. when connecting. ● First. username and password. ● Second. an identifier for it will be returned instead of opening a new connection. mysql_pconnect ● Open a persistent connection to a MySQL server ● resource mysql_pconnect ( [string $server [. string $password [. the link will remain open for future use (mysql_close() will not close links established by mysql_pconnect()).intellibitz. ● This type of link is therefore called 'persistent'. Instead. the connection to the SQL server will not be closed when the execution of the script ends.com . www. the function would first try to find a (persistent) link that's already open with the same host. string $username [. ● mysql_pconnect() acts very much like mysql_connect() with two major differences.com                                                                                                                     training@intellibitz.

"hostname:port" or a path to a local socket e. .com password. Default value is an empty www. mysql_pconnect ● Parameters – server The MySQL server. ":/path/to/socket" for the localhost.default_host is undefined (default). Default value is the name of the user that owns the server process. e. It can also include a port ● number. ● If the PHP directive mysql.g.g. then the default value is 'localhost:3306' – username ● The username.com                                                                                                                     training@intellibitz. – password ● The password.intellibitz.

com                                                                                                                     training@intellibitz. mysql_pconnect ● client_flags The client_flags parameter can be a ● combination of the following constants: MYSQL_CLIENT_SSL. ● Return Values – Returns a MySQL persistent link identifier on success. or FALSE on failure. MYSQL_CLIENT_COMPRESS.com . www.intellibitz. MYSQL_CLIENT_IGNORE_SPACE or MYSQL_CLIENT_INTERACTIVE.

com                                                                                                                     training@intellibitz.com .intellibitz. mysql_ping ● Ping a server connection or reconnect if there is no connection ● bool mysql_ping ( [resource $link_identifier] ) ● Checks whether or not the connection to the server is working. to check whether or not the server has closed the connection and reconnect if necessary. www. This function can be used by scripts that remain idle for a long while. If it has gone down. an automatic reconnection is attempted.

com                                                                                                                     training@intellibitz. the last link opened by mysql_connect() is assumed. If the link identifier is not specified. otherwise FALSE. If by chance no connection is found or established.com .intellibitz. ● Return Values ● Returns TRUE if the connection to the server MySQL server is working. If no such link is found. mysql_ping ● Parameters – link_identifier ● The MySQL connection. it will try to create one as if mysql_connect() was called with no arguments. an E_WARNING level warning is generated. www.

     echo 'Lost connection. try to  <?php reconnect */ set_time_limit(0). exiting after query #1'. $db  = mysql_select_db('mydb'). time */ /* So the connection is still alive. 'mypass').com .    exit.com                                                                                                                     training@intellibitz. } /* Assuming this query will take a long  mysql_free_result($result). $result2 = mysql_query($sql2). exiting. } www. if (!$result) { ?>    echo 'Query #1 failed. mysql_ping /* Make sure the connection is still alive.'.    exit. if not.intellibitz. if (!mysql_ping($conn)) { $conn = mysql_connect('localhost'. 'mysqluser'. let's run another query */ $result = mysql_query($sql).

com                                                                                                                     training@intellibitz.intellibitz. mysql_real_escape_string ● Escapes special characters in a string for use in a SQL statement ● string mysql_real_escape_string ( string $unescaped_string [. \n. \. " and \x1a. www. ● mysql_real_escape_string() calls MySQL's library function mysql_real_escape_string. this function must be used. taking into account the current character set of the connection so that it is safe to place it in a mysql_query(). If binary data is to be inserted.com . ● This function must always (with few exceptions) be used to make data safe before sending a query to MySQL. which prepends backslashes to the following characters: \x00. resource $link_identifier] ) ● Escapes special characters in the unescaped_string. \r. '.

intellibitz. an E_WARNING level warning is generated.com . mysql_real_escape_string ● Parameters – unescaped_string ● The string that is to be escaped. www. If no such link is found. ● Return Values – Returns the escaped string. If the link identifier is not specified. or FALSE on error. the last link opened by mysql_connect() is assumed. it will try to create one as if mysql_connect() was called with no arguments. – link_identifier – The MySQL connection.com                                                                                                                     training@intellibitz. If by chance no connection is found or established.

// Query $query = sprintf("SELECT * FROM users WHERE user='%s' AND  password='%s'".intellibitz. ?> www.com                                                                                                                     training@intellibitz.            mysql_real_escape_string($password)). 'mysql_password')    OR die(mysql_error()). 'mysql_user'. mysql_real_escape_string <?php // Connect $link = mysql_connect('mysql_host'.            mysql_real_escape_string($user).com .

com                                                                                                                     training@intellibitz. www.com .intellibitz. mysql_stat ● Get current system status ● string mysql_stat ( [resource $link_identifier] ) ● mysql_stat() returns the current server status.

it will try to create one as if mysql_connect() was called with no arguments. www. If no such link is found. If the link identifier is not specified. an E_WARNING level warning is generated. the last link opened by mysql_connect() is assumed.com                                                                                                                     training@intellibitz. If by chance no connection is found or established.intellibitz.com . mysql_stat ● Parameters – link_identifier ● The MySQL connection.

  'mysql_password').com returned. open ?> tables. 'mysql_user'. NULL is www. mysql_stat <?php $link  = mysql_connect('localhost'. . mysql_stat($link)).com                                                                                                                     training@intellibitz.595 ) link_identifier is invalid. uptime. If 245. flush tables The above example will output something similar to: and queries per Array second. you [3] => Slow queries: 0 [4] => Opens: 26 have to use the [5] => Flush tables: 1 [6] => Open tables: 17 SHOW STATUS [7] => Queries per second avg: SQL command. For a ( complete list of [0] => Uptime: 5380 [1] => Threads: 2 other status [2] => Questions: 1321299 variables. threads. Return Values ● – Returns a string with $status = explode('  '.intellibitz. the status for print_r($status). queries.

● Parameters – result ● A result pointer resource that's returned from mysql_list_tables().intellibitz.com . mysql_tablename ● Get table name of field ● string mysql_tablename ( resource $result. – i ● The integer index (row/table number) www. It is preferable to use mysql_query() to issue a SQL SHOW TABLES [FROM db_name] [LIKE 'pattern'] statement instead.com                                                                                                                     training@intellibitz. ● This function deprecated. int $i ) ● Retrieves the table name from a result.

for ($i = 0. "mysql_user".com .  on success. mysql_tablename($result. $num_rows = mysql_num_rows($result). $i < $num_rows.intellibitz. $i++) {    echo "Table: ". ?> www. $result = mysql_list_tables("mydb"). or "mysql_password").  "\n". } mysql_free_result($result). mysql_tablename ● Return Values <?php – The name of the table mysql_connect("localhost". FALSE on failure. $i).com                                                                                                                     training@intellibitz.

intellibitz. mysql_thread_id ● Return the current thread ID ● int mysql_thread_id ( [resource $link_identifier] ) ● Retrieves the current thread ID. www.com . If the connection is lost. the thread ID will change.com                                                                                                                     training@intellibitz. and a reconnect with mysql_ping() is executed. This means only retrieve the thread ID when needed.

If the link identifier is not specified.intellibitz. ● Return Values – The thread ID on success. it will try to create one as if mysql_connect() was called with no arguments. or FALSE on failure. the last link opened by mysql_connect() is assumed. mysql_thread_id ● Parameters – link_identifier ● The MySQL connection.com .com                                                                                                                     training@intellibitz. If no such link is found. If by chance no connection is found or established. an E_WARNING level warning is generated. www.

com . 'mysql_user'. } ?> The above example will output something similar to: current thread id is 73 www.intellibitz. 'mysql_password').com                                                                                                                     training@intellibitz. mysql_thread_id <?php $link = mysql_connect('localhost'. $thread_id). $thread_id = mysql_thread_id($link). if ($thread_id){    printf("current thread id is %d\n".

com .intellibitz. without fetching and buffering the result rows ● resource mysql_unbuffered_query ( string $query [. resource $link_identifier] ) ● mysql_unbuffered_query() sends a SQL query query to MySQL. On the one hand. as mysql_query() does. mysql_unbuffered_query ● Send an SQL query to MySQL. this saves a considerable amount of memory with SQL queries that produce large result sets. you can start working on the result set immediately after the first row has been retrieved: you don't have to wait until the complete SQL query has been performed.com                                                                                                                     training@intellibitz. without fetching and buffering the result rows automatically. www. When using multiple DB-connects. On the other hand. you have to specify the optional parameter link_identifier.

www. it will try to create one as if mysql_connect() was called with no arguments. If the link identifier is not specified. ● Return Values – For SELECT. mysql_unbuffered_query() returns a resource on success. mysql_unbuffered_query ● Parameters – query A SQL query ● – link_identifier ● The MySQL connection. SHOW. the last link opened by mysql_connect() is assumed. ● For other type of SQL statements.com . If by chance no connection is found or established. mysql_unbuffered_query() returns TRUE on success or FALSE on error. DROP.com                                                                                                                     training@intellibitz. DELETE. etc.intellibitz. or FALSE on error. DESCRIBE or EXPLAIN statements. an E_WARNING level warning is generated. UPDATE. If no such link is found.

intellibitz. CHAPTER 10 PHP AND PEAR DB www.com .com                                                                                                                     training@intellibitz.

● PEAR DB databse program abstraction layer is an add on to php that simplifies communication between your PHP program and database program. www.intellibitz.com                                                                                                                          training@intellibitz. PEAR ● PEAR(PHP Extention and Application Repository)is a collection of useful modules and libraries for PHP.com .

PHP databse abstraction layer ● Web browser ● ● Apache/IIS ● PHP engine ● Pear DB ● DB extension ● Mysql .com                                                                                                                          training@intellibitz.com .intellibitz.sqlite ● ● DB server www.

● To use PEAR DB in a PHP program.intellibitz. PEAR ● The DB module is one of the most popular pear modules and is bundled with recent versions of PHP.com                                                                                                                          training@intellibitz.com .php //case-sensitive www. ● require DB.first you have to load the DB module. ● To load DB module use require construct.

php www. ● DB::connect().DB::isError().php is the main file of the PEAR DB package.php ● DB.com . disconnect().getMessage().query().intellibitz. ● It defines the functions that u use to talk to your database.fetchRow() are some of the functions defined by DB. DB.com                                                                                                                          training@intellibitz.

www. require and include ● The require construct tells the PHP interpreter to execute all the code in the file DB.php.com .com                                                                                                                          training@intellibitz. ● The require and include are simillar but differ in how they handle errors.intellibitz.

t exists.intellibitz. include reports a warning allowing your program to continue running. ● If you try to include a file that doesn.com . www.com                                                                                                                          training@intellibitz.require consider that as fatal error and your php program ends. require and include ● If you try to require a file that dosen't exists.

com .(DSN) ● Its genral form is dbProgram://user:pass@hostname/database ● disconnect() is used to terminate connection with database.com                                                                                                                          training@intellibitz. www.intellibitz. ● The string pssed to DB::connect () is called a Data Source Network. DB:: connect() ● You pass DB::connect() a string as argument.

Error handling in PEAR ● DB::isError () returns true if error occurred in database operations.com . www. ● Instead of calling DB::isError () after every query to check its succeeded or failed .intellibitz.com                                                                                                                          training@intellibitz.you can use setErrorHandling () to establish default error handling behavior. ● Pass the constant PEAR_ERROR_DIE to setErrorHandling() to print error message and exit if a query fails.

● So the fetchRow () can be iterated using while loop. www.intellibitz. fetchRow() ● The fetchRow() function all field data in a record.com                                                                                                                          training@intellibitz. ● This data can be assigned to an array variable.com . ● This fetchRow () function returns false if all row resulted by the query is fetched.

com                                                                                                                          training@intellibitz.php. ● Establishing ans terminating connections with databases. ● Requiring DB.com . ● Error handling ● Retriving data from database using PEAR. www.intellibitz. Chapter Summary ● Understanding PEAR helps the programmer in database operations.

com .com                                                                                                                          training@intellibitz. CHAPTER 11 COOKIES AND SESSIONS www.intellibitz.

● Storing and retrieving information.intellibitz. ● Why setcookie() and session_start() want to be at the top of the page.com                                                                                                                     training@intellibitz. www.com . ● Activating Sessions. Cookies and Sessions ● Working with Cookies. ● Login and User identification.

com                                                                                                                     training@intellibitz. www. ● PHP session capabilities keeps track of multiple piece of information under one cookie. Cookies and Sessions ● Cookie identifies a web client to web server ● Cookie has a name and a value.intellibitz.com . ● Session uses cookie to persist data across requests.

com                                                                                                                     training@intellibitz.com . www.intellibitz. Working with Cookies ● Use setcookie() function to set a cookie. ● Cookies show up in $_COOKIE only when the web client sends them with the request. ● Call setcookie() before the page generates any output. ● Path to setcookie() must match the server . ● Cookies are only sent back with requests for pages in the same directory.

Fourth and fifth are path and domain. Second is the value of the cookie. www.intellibitz. ● The default lifetime of the cookie is the lifetime of the web client. Third argument specifies the life time of the cookie. First argument is the name of the cookie.com . when you quit internet explorer or Mozilla Firefox the cookie is automatically deleted.com                                                                                                                     training@intellibitz. Cookies ● Setcookie() can take five arguments.

com . www.intellibitz. Activating Sessions ● Sessions use a cookie called PHPSESSID ● The value of PHPSESSID is a random alphanumeric string ● Use session_start() at the beginning of your script to use a Session ● Like setcookie(). session_start() must be called before any output is sent.com                                                                                                                     training@intellibitz.

Storing and Using Information ● Session data is stored in the $_SESSION auto-global array ● The PHP interpreter tracks the contents of the $_SESSION separately for each session ● Call session_start() or set session.auto_start to on.intellibitz. to access a user's session data ● Session data is not restricted to string and numbers.com .com                                                                                                                     training@intellibitz. its like any other array www.

or call ini_set() function from your program to configure idle time to keep a session active ● Use ini_set() before session_start() www.gc_maxlifetime configuration directive.intellibitz. Configuring Sessions ● Sessions work great with no additional tweak ● Session default timeout is 24 minutes ● Use session.com .com                                                                                                                     training@intellibitz.

intellibitz. cookie and session functions www. Request Headers ● All of the headers in the response from the web server to the web client have to be at the beginning of the response ● Functions like setcookie() and session_start() add headers to the response ● Output buffering lets you mix print statements.com .com                                                                                                                     training@intellibitz.

intellibitz.com . Chapter Summary ● Understanding why cookies are necessary to identify a particular web browser to a web server ● Setting a cookie in a PHP program ● Reading a cookie value in a PHP program ● Modifying cookie parameters such as expiration time. and domain ● Deleting a cookie in a PHP program www.com                                                                                                                     training@intellibitz. path.

validating. and processing a validation form www.com                                                                                                                     training@intellibitz. Chapter Summary ● Turning on sessions from PHP program or in the PHP interpreter configuration ● Storing information in session ● Reading information from a session ● Saving form data in a session ● Configuring session expiration and cleanup ● Displaying.intellibitz.com .

www.com .intellibitz. Chapter Summary ● Using encrypted passwords ● Understanding why setcookie() and session_start() must be called before anything is printed ● Cookie can't be an array or more complicated data structure.com                                                                                                                     training@intellibitz.

com .intellibitz.com                                                                                                                     training@intellibitz. CHAPTER 12 WORKING WITH DATES AND TIMES www.

com                                                                                                                     training@intellibitz.com . ● Dates and Times in Forms. ● Parsing a Date or Time.intellibitz. www. Handling Dates And Times ● Displaying the Date or Time.

● The first argument controls how the date or time string is formatted. ● The second argument controls what date or time is used. www. ● Both strftime( ) and date( )take two arguments. Displaying Date or Time ● Use the date( ) or strftime( ) functions to display the date and time.com .intellibitz.com                                                                                                                     training@intellibitz.

Displaying Date or Time ● In date ( ) function / can't be used for escaping. www.intellibitz. ● With strftime ( ) the things in the format string that get replaced by time and date values are set off percentage signs. ● The strftime( ) format strings are different from printf( ) format strings.com                                                                                                                     training@intellibitz.com .

com . ● Date ( ) is better because it supports leap year indicator and trims leading zeros from some values. ● Strftime( ) is better because we don't want to worry about letters with out percentage sign turning into time or date values. www.intellibitz. Displaying Date and Time ● The date( ) and strftime( )functions have their strong points.com                                                                                                                     training@intellibitz.

com . ● The strftime( ) is a php function that relies on underlying operating system functions. www. Displaying Date and Time ● Date( ) is php specific function. It operates on any OS.intellibitz.com                                                                                                                     training@intellibitz.

com                                                                                                                     training@intellibitz. Parsing Date or Time ● Epoch timestamp: The number of seconds that have elapsed since midnight on January 1. second. minute. ● If you have discrete date or time parts then use mktime ( ) ● The mktime ( ) accepts an hour. www.1970.intellibitz.com .month.days and year and returns the corresponding epoch time stamps.

● Strtotime( ) understands English description of relative times and returns an appropriate epoch time stamp. www.intellibitz.when you want the epoch timestamp for something relative to a time you know.com .com                                                                                                                     training@intellibitz. Parsing Date and Time ● Use strtotime( ).

com                                                                                                                     training@intellibitz.com .intellibitz.strtotime() also accept an epoch time stamp second argument to use as the starting point for its calculation www. Parsing Date and Time – Like date() and strftime().

intellibitz.the best thing to do is to <select> menus – This restricts the possible input to what ever you display in the menus. www.com .com                                                                                                                     training@intellibitz. Dates and Time in Form – When you need a user to input a date in a form .

Chapter Summary ● Defining some time and date handling vocabulary such as epoch timestamp. www. time and date parts and formatted date and time string.intellibitz. ● Printing formatted time and date string with strftime( ) and date( ). ● Making an epoch timestamp with mktime ( ).com .com                                                                                                                     training@intellibitz.

● Displaying form elements to allow for date or time input. www. Chapter summary ● Making an epoch timestamp with strtotime().com                                                                                                                     training@intellibitz.intellibitz.com .

intellibitz. CHAPTER 13 DATE AND TIME FUNTIONS www.com .com                                                                                                                     training@intellibitz.

www. A date is considered valid if each parameter is properly defined.com                                                                                                                          training@intellibitz. ● Parameters – month ● The month is between 1 and 12 inclusive.com . int $year ) ● Checks the validity of the date formed by the arguments. checkdate ● Validate a Gregorian date ● bool checkdate ( int $month. Leap years are taken into consideration. – day ● The day is within the allowed number of days for the given month.intellibitz. int $day.

 31.intellibitz.com                                                                                                                          training@intellibitz. ● ● Return Values – Returns TRUE if the date given is valid.com . 29. ?> The above example will output: bool(true) bool(false) www. otherwise returns FALSE <?php var_dump(checkdate(12. checkdate – year The year is between 1 and 32767 inclusive. 2001)). 2000)). var_dump(checkdate(2.

com .intellibitz. date_create ● Returns new DateTime object ● DateTime date_create ( [string $time [. DateTimeZone $timezone]] ) ● DateTime DateTime::__construct ( [string $time [.com                                                                                                                          training@intellibitz. DateTimeZone $timezone]] ) www.

● Return Values – Returns DateTime object on success or FALSE on failure. date_create ● Parameters – time String in a format accepted by strtotime().com                                                                                                                          training@intellibitz. – timezone ● Time zone of the time.intellibitz. www.com . ● defaults to "now".

intellibitz. int $day ) www.com . int $month. int $month. date_date_set ● Sets the date ● void date_date_set ( DateTime $object. int $year. int $day ) ● void DateTime::setDate ( int $year.com                                                                                                                          training@intellibitz.

www. ● ● Return Values ● Returns NULL on success or FALSE on failure.com . – year ● Year of the date.intellibitz. – month ● Month of the date. date_date_set ● Parameters – object ● DateTime object. – day Day of the date.com                                                                                                                          training@intellibitz.

com                                                                                                                          training@intellibitz.intellibitz.com . date_default_timezone_get ● Gets the default timezone used by all date/time functions in a script ● string date_default_timezone_get ( void ) www.

timezone ini option (if set) – "magical" guess (if the operating system supports it) – If none of the above options succeeds. date_default_timezone_get The TZ environment variable (if non empty) – – The date. return UTC ● Return Values – Returns a string www.com                                                                                                                          training@intellibitz.com .intellibitz.

intellibitz. www.com                                                                                                                          training@intellibitz.com . date_default_timezone_set ● Sets the default timezone used by all date/time functions in a script ● bool date_default_timezone_set ( string $timezone_identifier ) ● date_default_timezone_set() sets the default timezone used by all date/time functions.

like UTC or Europe/Lisbon. The list of valid identifiers is available in the Appendix I. date_default_timezone_set ● Parameters – timezone_identifier ● The timezone identifier. www.com .com                                                                                                                          training@intellibitz.intellibitz. or TRUE otherwise. List of Supported Timezones. ● Return Values – This function returns FALSE if the timezone_identifier isn't valid.

com .com                                                                                                                          training@intellibitz. date_format ● Returns date formatted according to given format ● string date_format ( DateTime $object.intellibitz. string $format ) ● string DateTime::format ( string $format ) www.

com                                                                                                                          training@intellibitz.intellibitz. ● Return Values – Returns formatted date on success or FALSE on failure. www. date_format ● Parameters – object ● DateTime object.com . format – – Format accepted by date().

date_modify ● Alters the timestamp ● void date_modify ( DateTime $object. ● Return Values – Returns NULL on success or FALSE on failure.com                                                                                                                          training@intellibitz. – modify ● String in a relative format accepted by strtotime().com . string $modify ) ● void DateTime::modify ( string $modify ) ● Parameters – object ● DateTime object. www.intellibitz.

www.com . ● Return Values – Returns DST offset in seconds on success or FALSE on failure.intellibitz.com                                                                                                                          training@intellibitz. date_offset_get ● Returns the daylight saving time offset ● int date_offset_get ( DateTime $object ) ● int DateTime::getOffset ( void ) ● Parameters – object ● DateTime object.

intellibitz.com                                                                                                                          training@intellibitz.com . www. date_parse ● date_parse — Returns associative array with detailed info about given date ● array date_parse ( string $date ) ● Parameters – date – Date in format accepted by strtotime(). ● Return Values ● Returns array on success or FALSE on failure.

5")).com                                                                                                                          training@intellibitz.5 [warning_count] => 0 [warnings] => Array() [error_count] => 0 [errors] => Array() [is_localtime] => www. ?> The above example will output: Array ( [year] => 2006 [month] => 12 [day] => 12 [hour] => 10 [minute] => 0 [second] => 0 [fraction] => 0. date_parse <?php print_r(date_parse("2006­12­12 10:00:00.intellibitz.com .

com                                                                                                                          training@intellibitz. www. float $latitude. – latitude ● Latitude in degrees. date_sun_info ● Returns an array with information about sunset/sunrise and twilight begin/end ● array date_sun_info ( int $time. – longitude ● Longitude in degrees.com .intellibitz. float $longitude ) ● Parameters – time ● Timestamp.

com                                                                                                                          training@intellibitz. 35. <?php $sun_info = date_sun_info(strtotime("2006­12­12"). 31. "\n". $val) .7667. get_sun_info ● Return Values – Returns array on success or FALSE on failure.com . foreach ($sun_info as $key => $val) { The above example will output:    echo "$key: " .2333). sunrise: 05:52:11 sunset: 15:41:21 } transit: 10:46:46 civil_twilight_begin: 05:24:08 ?> civil_twilight_end: 16:09:24 nautical_twilight_begin: 04:52:25 nautical_twilight_end: 16:41:06 astronomical_twilight_begin: 04:21:32 astronomical_twilight_end: 17:12:00 www.intellibitz. date("H:i:s".

com                                                                                                                          training@intellibitz.com . date_sunrise ● Returns time of sunrise for a given day and location ● mixed date_sunrise ( int $timestamp [. int $format [. float $zenith [. float $latitude [. www. float $longitude [.intellibitz. float $gmt_offset]]]]] ) ● date_sunrise() returns the sunrise time for a given day (specified as a timestamp) and location.

com                                                                                                                          training@intellibitz. – latitude ● Defaults to North. See also: date. See also: date. pass in a negative value for West.com .intellibitz. date_sunrise ● Parameters – timestamp ● The timestamp of the day from which the sunrise time is taken.default_longitude www. pass in a negative value for South.default_latitude – longitude ● Defaults to East.

intellibitz. date_sunrise ● zenith Default: date.sunrise_zenith ● – gmtoffset ● Specified in hours. www. ● Return Values – Returns the sunrise time in a specified format on success.com . or FALSE on failure.com                                                                                                                          training@intellibitz.

com                                                                                                                          training@intellibitz.intellibitz.78243132 SUNFUNCS_RET_TIMESTAMP      returns the result as integer (timestamp)      1095034606 www. date_sunrise Constant                                             description                                                   example SUNFUNCS_RET_STRING             returns the result as string                            16:46 SUNFUNCS_RET_DOUBLE            returns the result as float                              16.com .

4.date_sunrise(time(). date_sunrise <?php /* calculate the sunrise time for Lisbon.com .com                                                                                                                          training@intellibitz. Portugal Latitude: 38. sunrise time : ' . ?> The above example will output something similar to: Mon Dec 20 2004. ­9. 1). 90.4 North Longitude: 9 West Zenith ~= 90 offset: +1 GMT */ echo date("D M d Y"). 38. sunrise time : 08:54 www. '.intellibitz. SUNFUNCS_RET_STRING.

www.com                                                                                                                          training@intellibitz. float $zenith [. float $gmt_offset]]]]] ) ● date_sunset() returns the sunset time for a given day (specified as a timestamp) and location. float $longitude [. int $format [. date_sunset ● Returns time of sunset for a given day and location ● mixed date_sunset ( int $timestamp [. float $latitude [.intellibitz.com .

sunrise_zenith – gmtoffset – Specified in hours. See also: date. – latitude ● Defaults to North.com                                                                                                                          training@intellibitz.default_longitude – zenith – Default: date.intellibitz.com . pass in a negative value for South. pass in a negative value for West. date_sunset ● Parameters – timestamp ● The timestamp of the day from which the sunset time is taken. See also: date. www.default_latitude – longitude ● Defaults to East.

date_sunset(time(). 38. '. ?> The above example will output something similar to: Mon Dec 20 2004. sunset time : 18:13 www. sunset time : ' .com                                                                                                                          training@intellibitz. date_sunset <?php /* calculate the sunset time for Lisbon.4 North Longitude: 9 West Zenith ~= 90 offset: +1 GMT */ echo date("D M d Y"). ­9.4. 1).  SUNFUNCS_RET_STRING. Portugal Latitude: 38.com .intellibitz. 90.

com                                                                                                                          training@intellibitz. date_time_set ● Sets the time ● void date_time_set ( DateTime $object. int $minute [. int $second] ) www.intellibitz. int $second] ) ● void DateTime::setTime ( int $hour. int $hour. int $minute [.com .

date_time_set ● Parameters – object ● DateTime object. – hour ● Hour of the time.com                                                                                                                          training@intellibitz.intellibitz. ● Return Values – Returns NULL on success or FALSE on failure. ● – second ● Second of the time. www. – minute Minute of the time.com .

intellibitz.com .com                                                                                                                          training@intellibitz. www. ● Return Values – Returns DateTimeZone object on success or FALSE on failure. date_timezone_get ● Return time zone relative to given DateTime ● DateTimeZone date_timezone_get (DateTime $object) ● DateTimeZone DateTime::getTimezone(void) ● Parameters ● object – DateTime object.

. DateTimeZone $timezone ) ● void DateTime::setTimezone ( DateTimeZone $timezone ) ● Parameters – Object . – Timezone .com                                                                                                                          training@intellibitz.Desired time zone. date_timezone_set ● Sets the time zone for the DateTime object ● void date_timezone_set ( DateTime $object. www..DateTime object.intellibitz. ● Return Values – Returns NULL on success or FALSE on failure.com .

www. ● Parameters ● format – The format of the outputted date string. timestamp is optional and defaults to the value of time().com                                                                                                                          training@intellibitz. In other words.com .intellibitz. date ● Format a local time/date ● string date ( string $format [. int $timestamp] ) ● Returns a string formatted according to the given format string using the given integer timestamp or the current time if no timestamp is given.

com . rd or th. three letters                            Mon through Sun j                                  Day of the month without leading zeros                                                 1 to 31 l (lowercase 'L')         A full textual representation of the day of the week               Sunday through  Saturday N                              ISO­8601 numeric representation of the day                     1 (for Monday) through 7 of the week (added in PHP 5. Works well  with j www. date format character                     Description                                                               Example returned  values Day                                              ­­­                                                                                            ­­­ d                                 Day of the month. nd. 2 digits with leading zeros                                       01 to 31 D                                A textual representation of a day.intellibitz.             st.1.0)                                        (for  sunday) S                               English ordinal suffix for the day of the month.com                                                                                                                          training@intellibitz.

getdate ● Get date/time information ● array getdate ( [int $timestamp] ) ● Returns an associative array containing the date information of the timestamp.intellibitz.com . or the current local time if no timestamp is given. www.com                                                                                                                          training@intellibitz.

www.com . In other words. ● Return Values – Returns an associative array of information related to the typestamp. getdate ● Parameters – timestamp ● The optional timestamp parameter is an integer Unix timestamp that defaults to the current local time if a timestamp is not given.intellibitz. it defaults to the value of time().com                                                                                                                          training@intellibitz.

com .intellibitz.com                                                                                                                          training@intellibitz. ?> The above example will output something similar to: Array ( [seconds] => 40 [minutes] => 58 [hours] => 21 [mday] => 17 [wday] => 2 [mon] => 6 [year] => 2003 [yday] => 167 [weekday] => Tuesday [month] => June [0] => 1055901520 ) www. print_r($today). getdate <?php $today = getdate().

gettimeofday

Get current time

mixed gettimeofday ( [bool $return_float] )

This is an interface to gettimeofday(2). It returns an
associative array containing the data returned from the
system call.

www.intellibitz.com                                                                                                                          training@intellibitz.com

gettimeofday

Parameters
– return_float

When set to TRUE, a float instead of an array
is returned.

Return Values
– By default an array is returned. If return_float is set,
then a float is returned.

Array keys:
– "sec" - seconds since the Unix Epoch
– "usec" - microseconds
– "minuteswest" - minutes west of
Greenwich
– "dsttime" - type of dst correction

www.intellibitz.com                                                                                                                          training@intellibitz.com

gettimeofday
<?php

print_r(gettimeofday());

echo gettimeofday(true);

?>

The above example will output something similar to:
Array
(
[sec] => 1073504408
[usec] => 238215
[minuteswest] => 0
[dsttime] => 1
)
1073504408.23910

www.intellibitz.com                                                                                                                          training@intellibitz.com

gmdate

Format a GMT/UTC date/time

string gmdate ( string $format [, int $timestamp] )

Identical to the date() function except that the time returned
is Greenwich Mean Time (GMT).

www.intellibitz.com                                                                                                                          training@intellibitz.com


Parameters
gmdate
– format
The format of the outputted date string. See

the formatting options for the date() function.
– timestamp

The optional timestamp parameter is an
integer Unix timestamp that defaults to the
current local time if a timestamp is not
given. In other words, it defaults to the value
of time().

Return Values
– Returns a formatted date string. If a non-numeric value is
used for timestamp, FALSE is returned and an
E_WARNING level error is emitted.

www.intellibitz.com                                                                                                                          training@intellibitz.com

gmdate

When run in Finland (GMT +0200), the first line below prints "Jan 01 1998 00:00:00", while the second 
prints "Dec 31 1997 22:00:00".

<?php

echo date("M d Y H:i:s", mktime(0, 0, 0, 1, 1, 1998));

echo gmdate("M d Y H:i:s", mktime(0, 0, 0, 1, 1, 1998));

?>

www.intellibitz.com                                                                                                                          training@intellibitz.com

CHAPTER 14

CALENDER FUNCTIONS

www.intellibitz.com                                                                                                                          training@intellibitz.com

Calendar functions

The calendar extension presents a series of functions to
simplify converting between different calendar formats.

The intermediary or standard it is based on is the Julian
Day Count. The Julian Day Count is a count of days
starting from January 1st, 4713 B.C.

To convert between calendar systems, you must first
convert to Julian Day Count, then to the calendar system
of your choice. Julian Day Count is very different from the
Julian Calendar!

www.intellibitz.com                                                                                                                     training@intellibitz.com

cal_days_in_month

cal_days_in_month —
Return the number of <?php

days in a month for a $num = 
cal_days_in_month(CAL_GREGORIA
given year and calendar
N, 8, 2003); // 31

int cal_days_in_month ( int
echo "There was $num days in August 
$calendar, int $month, int 2003";
$year )
?>

This function will return the
number of days in the
month of year for the
specified calendar.

www.intellibitz.com                                                                                                                     training@intellibitz.com

cal_from_jd
<?php

cal_from_jd — Converts from
$today = unixtojd(mktime(0, 0, 0, 8, 16, 2003));
Julian Day Count to a
supported calendar print_r(cal_from_jd($today, 

array cal_from_jd ( int $jd, int CAL_GREGORIAN));

$calendar ) ?>

cal_from_jd() converts the The above example will output:
Julian day given in jd into Array
(
a date of the specified [date] => 8/16/2003
calendar. Supported [month] => 8
[day] => 16
calendar values are [year] => 2003
[dow] => 6
CAL_GREGORIAN, [abbrevdayname] => Sat
[dayname] => Saturday
CAL_JULIAN, [abbrevmonth] => Aug
[monthname] => August
CAL_JEWISH and )
CAL_FRENCH.
www.intellibitz.com                                                                                                                     training@intellibitz.com

cal_info

cal_info — Returns information about a particular calendar

Description

array cal_info ( [int $calendar] )

cal_info() returns information on the specified calendar.

Calendar information is returned as an array containing the elements
calname, calsymbol, month, abbrevmonth and maxdaysinmonth.
The names of the different calendars which can be used as calendar
are as follows:

* 0 or CAL_GREGORIAN - Gregorian Calendar

* 1 or CAL_JULIAN - Julian Calendar

* 2 or CAL_JEWISH - Jewish Calendar

* 3 or CAL_FRENCH - French Revolutionary Calendar

If no calendar is specified information on all supported calendars is
returned as an array. This functionality is available beginning with
PHP 5.

www.intellibitz.com                                                                                                                     training@intellibitz.com

call_info
Array
(
<?php [months] => Array
(
$info = cal_info(0); [1] => January [abbrevmonths] => Array
[2] => February (
print_r($info); [3] => March [1] => Jan
[4] => April [2] => Feb
?> [5] => May [3] => Mar
[6] => June [4] => Apr
[7] => July [5] => May
[8] => August [6] => Jun
[9] => September [7] => Jul
[10] => October [8] => Aug
[11] => November [9] => Sep
[12] => December [10] => Oct
) [11] => Nov
[12] => Dec
)
[maxdaysinmonth] => 31
[calname] => Gregorian
[calsymbol] =>
CAL_GREGORIAN
)

www.intellibitz.com                                                                                                                     training@intellibitz.com

com . Supported calendars are CAL_GREGORIAN. int $month. int $day. CAL_JULIAN. www.intellibitz. int $year ) ● cal_to_jd() calculates the Julian day count for a date in the specified calendar.com                                                                                                                     training@intellibitz. CAL_JEWISH and CAL_FRENCH. cal_to_jd ● cal_to_jd — Converts from a supported calendar to Julian Day Count ● int cal_to_jd ( int $calendar.

intellibitz.        //  corresponding to midnight on Apr­23­2000 Easter of the given year. easter_date(2001)). easter_date(1999)). the year Apr­15­2001 parameter is optional and defaults to the current year according to the localtime if ?> omitted. www.3.0.com                                                                                                                     training@intellibitz.        //  ● Since PHP 4. echo date("M­d­Y".com . easter_date(2000)). easter_date ● easter_date — Get Unix <?php timestamp for midnight on Easter of a given year echo date("M­d­Y".        //  ● int easter_date ( [int $year] ) Apr­04­1999 ● Returns the Unix timestamp echo date("M­d­Y".

intellibitz.0 and allows to calculate easter dates based on the Gregorian calendar during the years 1582 .e.0. before 1970 or after 2037).com                                                                                                                     training@intellibitz.1752 when set to CAL_EASTER_ROMAN. See the calendar constants for more valid constants. If no year is specified. the year parameter is optional and defaults to the current year according to the localtime if omitted.3. easter_days ● easter_days — Get number of days after March 21 on which Easter falls for a given year ● int easter_days ( [int $year [. int $method]] ) ● Returns the number of days after March 21 on which Easter falls for a given year.com . ● This function can be used instead of easter_date() to calculate Easter for years which fall outside the range of Unix timestamps (i. the current year is assumed. ● Since PHP 4. www.3. ● The method parameter was also introduced in PHP 4.

 i. i.        // 32. March 23 ?> www.        // 14.        //  2.e. April 22 echo easter_days(1913).e.intellibitz.com .com                                                                                                                     training@intellibitz.e. easter_days <?php echo easter_days(1999). i. April 4 echo easter_days(1492).

● These routines only convert dates in years 1 through 14 (Gregorian dates 22 September 1792 through 22 September 1806). FrenchToJD ● FrenchToJD — Converts a date from the French Republican Calendar to a Julian Day Count ● int frenchtojd ( int $month.intellibitz.com . This more than covers the period when the calendar was in use. www. int $year ) ● Converts a date from the French Republican Calendar to a Julian Day Count. int $day.com                                                                                                                     training@intellibitz.

1582 in the Julian calendar).com . The Gregorian calendar was not instituted until October 15. 1582 (or October 5.C. For example.C. ● Although this function can handle dates all the way back to 4714 B. to 9999 A. GregorianToJD ● GregorianToJD — Converts a Gregorian date to Julian Day Count ● int gregoriantojd ( int $month. www. The USSR in 1918 and Greece in 1923. Britain converted in 1752.com                                                                                                                     training@intellibitz.intellibitz. Some countries did not accept it until much later. such use may not be meaningful.D.. Most European countries used the Julian calendar prior to the Gregorian. int $year ) ● Valid Range for Gregorian Calendar 4714 B. int $day.

 1=Monday. Can return a string or an integer depending on the mode. etc) 1                        Returns string containing the day of week (English­Gregorian) 2                       Returns a string containing the abbreviated day of week (English­Gregorian) www.com . int $mode] ) ● Returns the day of the week.com                                                                                                                     training@intellibitz. JDDayOfWeek ● JDDayOfWeek — Returns the day of the week ● mixed jddayofweek ( int $julianday [.intellibitz. MODE              MEANING 0 (Default)        Returns the day number as an int (0=Sunday.

intellibitz. JDMonthName ● JDMonthName — Returns a month name ● string jdmonthname ( int $julianday. mode tells this function which calendar to convert the Julian Day Count to.com                                                                                                                     training@intellibitz. and what type of month names are to be returned. www.com . int $mode ) ● Returns a string containing a month name.

com                                                                                                                     training@intellibitz. Fructidor. Elul 5             French Republican            Vendemiaire.                                                            Germinal. April. August. December 2             Julian ­ abbreviated              Jan. May. March. March. Mar. Nisan. String functions Mode         Meaning                                    Values 0              Gregorian – abbreviated               Jan. Feb. Pluviose. June. Jul. Jul.                                                                                       October. Floreal.intellibitz. June. Aug. Nov. Oct. April. February. August. November. Dec 3                       Julian                         January. Mar. Frimaire.Nov. Feb. July. Oct.                                                                                                            Sivan. February. September. Kislev. May. Jun. Shevat. AdarII. Aug. November. Av. Thermidor. May. Jun. Apr. Sep.                                                                                                          September. December 4                         Jewish                        Tishri. Prairial. Iyyar. Tammuz. May. Ventose. Heshvan. October. Nivose. Extra www. July. AdarI. Apr. Messidor. Sep. Dec                                                                                                                                                   1              Gregorian                                January.com . Brumaire. Tevet.

intellibitz. JDToFrench ● JDToFrench — Converts a Julian Day Count to the French Republican Calendar ● string jdtofrench ( int $juliandaycount ) ● Converts a Julian Day Count to the French Republican Calendar.com .com                                                                                                                     training@intellibitz. www.

com                                                                                                                     training@intellibitz. www. JDToGregorian ● JDToGregorian — Converts Julian Day Count to Gregorian date ● string jdtogregorian ( int $julianday ) ● Converts Julian Day Count to a string containing the Gregorian date in the format of "month/day/year".intellibitz.com .

com . The available formats are: CAL_JEWISH_ADD_ALAFIM_GERESH.CAL_JEWISH_ADD_GER ESHAYIM.0. string based.intellibitz.com                                                                                                                     training@intellibitz. jdtojewish ● jdtojewish — Converts a Julian day count to a Jewish calendar date ● string jdtojewish(int $juliandaycount[. CAL_JEWISH_ADD_ALAFIM. the fl parameter is used for Hebrew.0 ● If the hebrew parameter is set to TRUE. int $fl]] ) ● Converts a Julian Day Count to the Jewish Calendar. ● The optional hebrew and fl parameters became available in PHP 5. www. output format.bool$hebrew [.

www.com                                                                                                                     training@intellibitz.com . JDToJulian ● JDToJulian — Converts a Julian Day Count to a Julian Calendar Date ● string jdtojulian ( int $julianday ) ● Converts Julian Day Count to a string containing the Julian Calendar Date in the format of "month/day/year".intellibitz.

intellibitz. jdtounix ● jdtounix — Convert Julian Day to Unix timestamp ● int jdtounix ( int $jday ) ● This function will return a Unix timestamp corresponding to the Julian Day given in jday or FALSE if jday is not inside the Unix epoch (Gregorian years between 1970 and 2037 or 2440588 <= jday <= 2465342 ).com                                                                                                                     training@intellibitz. www. The time returned is localtime (and not GMT).com .

com                                                                                                                     training@intellibitz. but in the early days there was no formula to determine the start of a month. int $day. int $year ) ● Although this function can handle dates all the way back to the year 1 (3761 B.intellibitz.). www. such use may not be meaningful. JewishToJD ● JewishToJD — Converts a date in the Jewish Calendar to Julian Day Count ● int jewishtojd ( int $month.C. A new month was started when the new moon was first observed. The Jewish calendar has been in use for several thousand years.com .

D.C.C. to 9999 A. int $year ) ● Valid Range for Julian Calendar 4713 B. and perhaps as late at the 4th century...com                                                                                                                     training@intellibitz. int $day.intellibitz. ● Although this function can handle dates all the way back to 4713 B.not all accepted January as the first month. but the details did not stabilize until at least 8 A. The calendar was created in 46 B. such use may not be meaningful. www.. JulianToJD ● JulianToJD — Converts a Julian Calendar date to Julian Day Count ● int juliantojd ( int $month. the beginning of a year varied from one culture to another .D.com .C. Also.

unixtojd ● unixtojd — Convert Unix timestamp to Julian Day ● Description ● int unixtojd ( [int $timestamp] ) ● ● Return the Julian Day for a Unix timestamp (seconds since 1.1970). or for the current day if no timestamp is given.1.intellibitz.com . www.com                                                                                                                     training@intellibitz.

com .intellibitz. CHAPTER 15 CLASSES AND OBJECTS www.com                                                                                                                     training@intellibitz.

● Defining classes ● Creating new objects.com . Classes and Objects ● Object basics. ● Creating constructors.intellibitz. www. ● Accessing properties and methods.com                                                                                                                     training@intellibitz.

www.com . ● The PROPERTY is the variable defined in the class. Object Basics ● An OBJECT is a structure that combines data about a thing.com                                                                                                                     training@intellibitz. ● The CLASS describes and holds the variables and functions for a kind of object. ● The METHOD is the function defined in the class.intellibitz. with actions on that thing.

www.intellibitz.com                                                                                                                     training@intellibitz. ● PHP is inherently a procedural language that has added the syntax necessary to support solution using OOP technique. PHP and OOP ● OOP is a particular approach to solving problem that is not necessarily tied to any language or hardware architecture.com .

Defining Classes

The special form class,followed by the name of the class.

An optional extensional clause, extends and then the name
of the class that should be inherited from.

A set of braces containing the variable declaration and
function definitions.

www.intellibitz.com                                                                                                                     training@intellibitz.com

Defining Classes

The variable declaration starts with special form var which
is followed by conventional $variable name.

The variable declarations in a class can also have an initial
assignments to a constant value.

The functions defined in a class are local to the class.

www.intellibitz.com                                                                                                                     training@intellibitz.com

Creating new objects

An Object is an instance of a class and the act of creating
object from a class is called instantiation.

The objects can be created with new keyword.

$objectname = new classname();

$objectname is the instance of the class classname.

www.intellibitz.com                                                                                                                     training@intellibitz.com

Creating new object

We can invokeor acces the member variables and functions
in the class using -> operator

$objectname ->functionname();

www.intellibitz.com                                                                                                                     training@intellibitz.com

__autoload()

It is common OOP practice to place each of your class
definition into separate files.

It is good practice to group various class definition into
multiple files based on their usage.

By doing this you don't need to include one large library file
in every page.

You only need to include the files containing the specific
classes that page needs.

www.intellibitz.com                                                                                                                     training@intellibitz.com

__autoload()

You can define __ autoload
function that
automatically be called
any time a new object
attempts to be
instantiated.

www.intellibitz.com                                                                                                                     training@intellibitz.com

Constructors

Constructor function sets up the initial state of a new object
before it is used.

Constructors are used to initialize the member variables in
the class.

Classes which have a constructor method call this method
on each newly-created object

www.intellibitz.com                                                                                                                     training@intellibitz.com

Constructors

PHP5 allows you to declare a constructor method by
including the member function __construct() .

You can also define a constructor by method by including a
function with same name as the class.

www.intellibitz.com                                                                                                                     training@intellibitz.com

Magic functions
● PHP reserves for itself any function with double
underscores prefix(__)as magic functions.
● This provides various automatic features.
● Do not make any of your own functions have a double
underscore,unless you specially wnt to invoke one of this
magic functions.

www.intellibitz.com                                                                                                                     training@intellibitz.com

Destructors

– The destructor method will be called as soon
as all references to a particular object are
removed or when the object is explicitly
destroyed with a call to unset().
– Unlike __construct() function __destruct ()
function can't be defined to take any
parameter.

www.intellibitz.com                                                                                                                     training@intellibitz.com

Private members
– The variables and functions in the class can
be declared as private.
– The private variables and functions can be
accessed only by the code within the class.
– An attempt to access the private variables
and functions outside the class gives an
error.

www.intellibitz.com                                                                                                                     training@intellibitz.com

Protected members
– Protected is used for members which are
internal to the object's logic ,but where it
might make sense for inheriting classes to
override them.

www.intellibitz.com                                                                                                                     training@intellibitz.com

intellibitz. www.com . time and date parts and formatted date and time string.com                                                                                                                     training@intellibitz. ● Printing formatted time and date string with strftime( ) and date( ). ● Making an epoch timestamp with mktime ( ). Chapter Summary ● Defining some time and date handling vocabulary such as epoch timestamp.

Chapter summary ● Making an epoch timestamp with strtotime().com .com                                                                                                                     training@intellibitz. www. ● Displaying form elements to allow for date or time input.intellibitz.

intellibitz.com .com                                                                                                                     training@intellibitz. CHAPTER 16 CLASSES AND OBJECTS FUNCTIONS www.

com                                                                                                                     training@intellibitz. ● You can obtain the name of the class to which an object belongs.e.intellibitz. www. what class is the object class extending). you can find out not only the class membership of an object.as well as its member properties and methods. but also its parentage (i. ● Using these functions.com . classes/object functions ● These functions allow you to obtain information about classes and instance objects.

 $color="green")    {    {        return $this­>color.    var $edible. } // end of class Vegetable    }    www. Classes objects <?php function is_edible() // base class with member properties and methods    { class Vegetable {        return $this­>edible.com .intellibitz.        $this­>edible = $edible.    }        $this­>color = $color.    function what_color()    function Vegetable($edible.com                                                                                                                     training@intellibitz.    }    var $color.

   } www.    }    function cook_it()    {        $this­>cooked = true.intellibitz. "green").com                                                                                                                     training@intellibitz.    }    function Spinach() } // end of class Spinach    { ?>        $this­>Vegetable(true. Classes objects function is_cooked() // extends the base class    { class Spinach extends Vegetable {        return $this­>cooked.com .    var $cooked = false.

we first define a base class and an extension of the class. whether it is edible or not and what is its color.com . The base class describes a general vegetable. Classes object ● In this example.com                                                                                                                     training@intellibitz. www. The subclass Spinach adds a method to cook it and another to find out if it is cooked.intellibitz.

object &$obj [. mixed $parameter [. mixed $..]] ) www.. call_user_method ● call_user_method — Call a user method on an specific object [deprecated] ● Description ● mixed call_user_method ( string $method_name.intellibitz.com .com                                                                                                                     training@intellibitz.

call_user_method_array ● call_user_method_array — Call a user method given with an array of parameters [deprecated] ● Description ● mixed call_user_method_array ( string $method_name.com .com                                                                                                                     training@intellibitz. object &$obj.intellibitz. array $paramarr ) www.

com . www. ● Parameters – class_name ● The class name – autoload ● Whether to call __autoload or not by default ● Return Values – Returns TRUE if class_name is a defined class. FALSE otherwise.com                                                                                                                     training@intellibitz.intellibitz. class_exists ● class_exists — Checks if the class has been defined ● bool class_exists ( string $class_name [. bool $autoload] ) ● This function checks if the given class have been defined.

com                                                                                                                     training@intellibitz. } ?>        trigger_error("Unable to load class: $class". use it    // Check to see if the include declared the class if (class_exists('MyClass')) {    if (!class_exists($class. } ?> www. false)) {    $myclass = new MyClass().com .php'). '. class_exists <?php                   //autoload parameter example <?php function __autoload($class) // Check the class exists before trying to  {   include($class . E_USER_WARNING).intellibitz.    } } if (class_exists('MyClass')) {    $myclass = new MyClass().

get_class_methods ● get_class_methods — Gets the class methods' names ● array get_class_methods ( mixed $class_name ) ● Gets the class methods names. it returns NULL. ● Parameters – class_name ● The class name of an object instance ● Return Values – Returns an array of method names defined for the class specified by class_name.com                                                                                                                     training@intellibitz.com . www. In case of an error.intellibitz.

   // constructor    function myfunc2() // or    function myclass()    { $class_methods = get_class_methods(new     {        return(true). myclass myfunc1    }     } myfunc2 www.    } foreach ($class_methods as $method_name) {    }    echo "$method_name\n". myclass()). get_class_methods <?php class myclass { // method 2 $class_methods = get_class_methods('myclass').intellibitz.        return(true).com                                                                                                                     training@intellibitz.    // method 1 }    function myfunc1() ?>    { The above example will output:        return(true).com    .

com . www. get_class_vars ● get_class_vars — Get the default properties of the class ● array get_class_vars ( string $class_name ) ● Get the default properties of the given class. ● Parameters – class_name ● The class name ● Return Values – Returns an associative array of default public properties of the class.com                                                                                                                     training@intellibitz. The resulting array elements are in the form of varname => value.intellibitz.

 // this has no default value.      var $var1. var3 : 100 // As of PHP 4.com                                                                                                                     training@intellibitz.2.0 var2 : xyz        $this­>var1 = "foo". foreach ($class_vars as $name => $value) {    var $var2 = "xyz".0        $this­>var2 = "bar". class myclass { $class_vars = get_class_vars(get_class($my_class)).. var3 : 100    }                 } www. var1 : var2 : xyz        return true.com ..intellibitz. }    private $var4. // PHP 5       // constructor ?>    function myclass() { The above example will output:        // change some properties // Before PHP 4.    var $var3 = 100. <?php get_class_var $my_class = new myclass().    echo "$name : $value\n".2.

get_class ● get_class — Returns the name of the class of an object ● string get_class ( [object $object] ) ● Gets the name of the class of the given object.com                                                                                                                     training@intellibitz. www.intellibitz.com . Returns FALSE if object is not an object. ● Parameters – object ● The tested object ● Return Values – Returns the name of the class of which object is an instance.

intellibitz. Its name is foo My name is foo    } } www. get_class($bar) .    function name() ?>    { The above example will output:        echo "My name is " .com                                                                                                                     training@intellibitz.    function foo() // external call    { echo "Its name is " . get_class($this) . get_class <?php // create an object class foo { $bar = new foo().com . "\n".    // implements some logic // internal call    } $bar­>name(). "\n".

com                                                                                                                     training@intellibitz. get_declared_classes ● get_declared_classes — Returns an array with the name of the defined classes ● array get_declared_classes ( void ) ● Gets the declared classes. ● www.intellibitz.com . ● Return Values – Returns an array of the names of the declared classes in the current script.

There [2] => Directory ) is a list of predefined classes in the Predefined Classes section of the appendices.c).c).0. www.1. three extra classes are <?php returned at the beginning of the array: print_r(get_declared_classes()).intellibitz. something similar to: ● Also note that depending on what libraries Array you have compiled into PHP. get_declared_classes ● Note: In PHP 4.com .com                                                                                                                     training@intellibitz. additional ( classes could be present. stdClass (defined in Zend/zend. OverloadedTestClass (defined in ?> ext/standard/basic_functions. This means [0] => stdClass [1] => that you will not be able to define your __PHP_Incomplete_Class own classes using these names.c) and The above example will output  Directory (defined in ext/standard/dir.

com . ● Return Values – Returns an array of the names of the declared interfaces in the current script.intellibitz. www. get_declared_interfaces ● get_declared_interfaces — Returns an array of all declared interfaces ● array get_declared_interfaces ( void ) ● Gets the declared interfaces.com                                                                                                                     training@intellibitz.

intellibitz. get_declared_interfaces <?php print_r(get_declared_interfaces()). ?> The above example will output something similar to: Array ( [0] => Traversable [1] => IteratorAggregate [2] => Iterator [3] => ArrayAccess [4] => reflector [5] => RecursiveIterator [6] => SeekableIterator ) www.com .com                                                                                                                     training@intellibitz.

intellibitz. – Return Values ● Returns an associative array of defined object properties for the specified object.com                                                                                                                     training@intellibitz. get_object_vars ● get_object_vars — Gets the properties of the given object ● array get_object_vars ( object $object ) ● Gets the properties of the given object. www.com . ● Parameters – object ● An object instance. If a property have not been assigned a value. it will be returned with a NULL value.

com .com                                                                                                                     training@intellibitz.        return array("x" => $this­>x.    function Point2D($x.233.233 function setLabel($label) $p1 = new Point2D(1.    var $label.intellibitz.    {    var $x. print_r(get_object_vars($p1)).445 [label] => } // "$label" is declared but not  )        $this­>y = $y. $y.    } www.    function getPoint() class Point2D { $p1­>setLabel("point #1"). Array defined (    } [x] => 1. $y) The above example will output:                      "label" => $this­>label). get_object_vars <?php print_r(get_object_vars($p1)).445).445 [label] => point #1    3. [y] => 3.  [y] => 3. ?>                      "y" => $this­>y.233        $this­>x = $x. )    {        $this­>label = $label. Array    { (    } [x] => 1.

com                                                                                                                     training@intellibitz.com . ● Parameters – object ● The tested object or class name ● Return Values – Returns the name of the parent class of the class of which object is an instance or the name. this function returns FALSE. get_parent_class ● get_parent_class — Retrieves the parent class name for object or class ● string get_parent_class ( [mixed $object] ) ● Retrieves the parent class name for object or class. ● If called without parameter outside object. www.intellibitz.

  "'s son\n".     } get_parent_class('child2') . get_parent_class($this) .com }                                                                                                                                                              training@intellibitz. get_parent_class <?php class dad { class child2 extends dad {    function dad()    function child2()    {    {    // implements some logic        echo "I'm " .com                                                                                                                     training@intellibitz.               echo "I'm " . I'm dad's son    { I'm dad's son too $bar = new child2().intellibitz. }    } class child extends dad { } The above example will     function child() output: $foo = new child().    } ?> www.com . "'s son  too\n".

● Parameters – interface_name ● The interface name – autoload ● Wether to call __autoload or not by default – Return Values ● Returns TRUE if the interface given by interface_name has been defined.intellibitz. bool $autoload] ) ● Checks if the given interface has been defined. interface_exists ● interface_exists — Checks if the interface has been defined ● bool interface_exists ( string $interface_name [. www. FALSE otherwise.com                                                                                                                     training@intellibitz.com .

com                                                                                                                     training@intellibitz.intellibitz. interface_exists <?php // Check the interface exists before trying to  use it if (interface_exists('MyInterface')) {    class MyClass implements MyInterface    {        // Methods    } } ?> www.com .

com                                                                                                                     training@intellibitz. is_a ● is_a — Checks if the object is of this class or has this class as one of its parents ● bool is_a ( object $object. string $class_name ) ● Checks if the given object is of this class or has this class as one of its parents. ● Note: The is_a() function is deprecated as of PHP 5 in favor of the instanceof type operator. ● Parameters – object ● The tested object – class_name ● The class name www.intellibitz.com .

if (is_a($WF. class WidgetFactory FALSE otherwise.    echo 'Yes. } www. is_a <?php Return Values <?php ● Returns TRUE if the // define a class ● object is of this class or has this class as if ($WF instanceof WidgetFactory) { one of its parents.intellibitz. { }   var $oink = 'moo'. \$WF is still a  WidgetFactory\n".com ?> .com                                                                                                                     training@intellibitz. ?> } // create a new object $WF = new WidgetFactory(). $WF is a WidgetFactory'.  'WidgetFactory')) {   echo "yes.

is_subclass_of ● is_subclass_of — Checks if the object has this class as one of its parents ● bool is_subclass_of ( mixed $object.com                                                                                                                     training@intellibitz. belongs to a class which is a subclass of class_name. www. ● Parameters – Object ● A class name or an object instance – class_name ● The class name – Return Values ● This function returns TRUE if the object object. string $class_name ) ● Checks if the given object has the class class_name as one of its parents.intellibitz.com . FALSE otherwise.

 'WidgetFactory')) { {   echo "yes.com                                                                                                                     training@intellibitz. // define a class $WFC = new WidgetFactory_Child().   var $oink = 'moo'. } else { }   echo "no. \$WF is a subclass of WidgetFactory\n". is_subclass_of // create a new object <?php $WF = new WidgetFactory().   var $oink = 'oink'. \$WFC is a subclass of WidgetFactory\n". \$WFC is not a subclass of WidgetFactory\n". \$WF is not a subclass of WidgetFactory\n". class WidgetFactory if (is_subclass_of($WFC. www. 'WidgetFactory')) { {   echo "yes. } else { }   echo "no. // define a child class class WidgetFactory_Child  } extends WidgetFactory if (is_subclass_of($WF.intellibitz.com } .

$WFC is a subclass of WidgetFactory no. WidgetFactory_Child is not a subclass of WidgetFactory\n". } else {   echo "no. is_sub_class_of // usable only since PHP 5.3 if (is_subclass_of('WidgetFactory_Child'. } ?> The above example will output: yes. 'WidgetFactory')) {   echo "yes.intellibitz. $WF is not a subclass of WidgetFactory yes. WidgetFactory_Child is a subclass of WidgetFactory www.com                                                                                                                     training@intellibitz.0.com . WidgetFactory_Child is a subclass of WidgetFactory\n".

method_exists

method_exists — Checks if the class method exists

bool method_exists ( object $object, string
$method_name )

Checks if the class method exists in the given object.

www.intellibitz.com                                                                                                                     training@intellibitz.com

method_exists
<?php

$directory = new Directory('.');

Parameters
– object var_dump(method_exists($directory,'read'
));
An object instance

– method_name ?>

The method nameThe above example will output:
– Return Values bool(true)

Returns TRUE if the method given by
method_name has been defined for the
given object, FALSE otherwise.

www.intellibitz.com                                                                                                                     training@intellibitz.com

property_exists

property_exists — Checks if the object or class has a property

Description

bool property_exists ( mixed $class, string $property )

This function checks if the given property exists in the specified class
(and if it is accessible from the current scope).

Note: As opposed with isset(), property_exists() returns TRUE even if
the property has the value NULL.

Parameters
– Class - - The class name or an object of the class to test
for
– Property - - The name of the property

Return Values
– Returns TRUE if the property exists, FALSE if it doesn't exist or
NULL in case of an error.

www.intellibitz.com                                                                                                                     training@intellibitz.com

property_exists
<?php

class myClass {

   public $mine;

   private $xpto;

   static function test() {

       var_dump(property_exists('myClass', 'xpto')); // true, it can be accessed from here

   }

}

var_dump(property_exists('myClass', 'mine'));  //true

var_dump(property_exists(new myClass, 'mine')); //true

var_dump(property_exists('myClass', 'xpto'));  //false, isn't public

myClass::test();                                                

  ?>
www.intellibitz.com                                                                                                                     training@intellibitz.com

CHAPTER 17

WORKING WITH FILES

www.intellibitz.com                                                                                                                     training@intellibitz.com

Working with Files

Understanding File Permissions

Reading and Writing Entire Files

Reading and Writing Parts of Files

Working with CSV Files

Inspecting File Permissions

Sanitizing Externally Supplied Filenames

www.intellibitz.com                                                                                                                     training@intellibitz.com

Understanding File Permissions

PHP can open a remote file as easy as you can open a
local file

PHP interpreter running inside a webserver, has the
privileges of the webserver account

The web server (and the PHP interpreter) need to be able
to read all PHP program files that make your website, but
they shouldn't be able to change them

www.intellibitz.com                                                                                                                     training@intellibitz.com

Reading and Writing Entire Files

Use file_get_contents() to read the contents of a file into a
string

A local and remote file look the same to file_get_contents()

Use file_put_contents() to write a string to a file

The kinds of URL that are acceptable to file_put_contents()
are more limited

www.intellibitz.com                                                                                                                     training@intellibitz.com

Reading and Writing part of
Files

Use fopen(), fgets(), feof(), and fclose()

$fh = fopen ('/home/user/test.txt', 'rb');

Use fwrite() to write to a file.. fwrite() doesn't automatically
add a newline on to the end of the string you write

Use fgetcsv() to read a line of CSV file

Comma separated value file is a type of file that stores
tabular data.

www.intellibitz.com                                                                                                                     training@intellibitz.com

Inspecting File Permissions

Use file_exists() to check if file exists

Use is_readable() or is_writeable() before retrieving its
contents with file_get_contents()

Use $php_errormsg global variable to track error messages
(track_errors must be on)

Use identical operator === to compare for same value and
same type

www.intellibitz.com                                                                                                                     training@intellibitz.com

Sanitizing Filenames

Special characters must be escaped

In filenames the special characters are / (separates
filenames) and .. (go up one directory)

Use realpath() to translate obfuscated filename into the real
names

www.intellibitz.com                                                                                                                     training@intellibitz.com

Chapter Summary

Understanding where the PHP interpreter's file access
permissions come from

Reading and writing entire local and remote files with
file_get_contents()

Opening and closing files with fopen() and fclose()

Reading a line of a file with fgets()

www.intellibitz.com                                                                                                                     training@intellibitz.com

com .com                                                                                                                     training@intellibitz. Chapter Summary ● Using feof() and a for() loop to read each line in a file ● Using forward slashes in filenames with all operating systems ● Providing different file modes to fopen() ● Writing data to a file with fwrite () ● Reading a line of a CSV file with fgetcsv () www.intellibitz.

Chapter Summary ● Determining a file exists with file_exists() ● Inspecting file permissions with is_readable() and is_writeable() ● Checking for errors returned from file access functions ● Understanding when to check a return value with the identical operator (===) ● Sanitizing externally supplied filenames www.com .com                                                                                                                     training@intellibitz.intellibitz.

com . CHAPTER 18 GETTEXT FUNCTIONS www.intellibitz.com                                                                                                                     training@intellibitz.

com                                                                                                                          training@intellibitz. www. GETTEXT FUNCTIONS ● The gettext functions implement an NLS (Native Language Support) API which can be used to internationalize your PHP applications.intellibitz.com .

● Parameters – domain ● The domain – message ● The message – Category Return Values ● The category A string on  success. int $category ) ● This function allows you to override the current domain for a single message lookup. string $message. dcgettext ● dcgettext — Overrides the domain for a single lookup ● string dcgettext ( string $domain.intellibitz.com . www.com                                                                                                                          training@intellibitz.

com .com                                                                                                                          training@intellibitz. string $msgid2. ● Parameters – domain ● The domain – msgid1 Return Values – msgid2 – n A string on  – Category success. int $category ) ● This function allows you to override the current domain for a single plural message lookup. dcngettext ● dcngettext — Plural version of dcgettext ● string dcngettext ( string $domain. int $n. www.intellibitz. string $msgid1.

www.com . ● Parameters ● Domain – The domain ● message Return Values – The message A string on success.com                                                                                                                          training@intellibitz.intellibitz. string $message ) ● ● The dgettext() function allows you to override the current domain for a single message lookup. dgettext ● dgettext — Override the current domain ● Description ● string dgettext ( string $domain.

intellibitz.com                                                                                                                          training@intellibitz. int $n ) ● The dngettext() function allows you to override the current domain for a single plural message lookup.com . string $msgid2. ● Parameters – Domain ● The domain – msgid1 Return Values – msgid2 A string on success. – n www. string $msgid1. dngettext ● dngettext — Plural version of dgettext ● string dngettext ( string $domain.

gettext ● gettext — Lookup a message in the current domain ● string gettext ( string $message ) ● Looks up a message in the current domain. or the submitted message if not found. ● Parameters – message ● Return Values – Returns a translated string if one is found in the translation table.com                                                                                                                          training@intellibitz. www.com .intellibitz.

www. string $msgid2. ngettext ● ngettext — Plural version of gettext ● string ngettext ( string $msgid1. int $n ) ● The plural version of gettext(). ● Parameters – msgid1 – msgid2 – n ● Return Values – Returns correct plural form of message identified by msgid1 and msgid2 for count n.com                                                                                                                          training@intellibitz. Some languages have more than one form for plural messages dependent on the count.intellibitz.com .

textdomain ● textdomain — Sets the default domain ● string textdomain ( string $text_domain ) ● This function sets the domain to search within when calls are made to gettext().com .com                                                                                                                          training@intellibitz. usually the named after an application. www. ● Parameters – text_domain ● The new message domain. or NULL to get the current setting without changing it ● Return Values – If successful. this function returns the current message domain. after possibly changing it.intellibitz.

intellibitz.com                                                                                                                          training@intellibitz.com . CHAPTER 19 REGULAR EXPRESSION www.

intellibitz. ● Regular expressions are used to test the sequence of characters (may be in a credit card number.com                                                                                                                          training@intellibitz.is an expression that describes a set of string. Regular expression ● A regular expression.com . often called as pattern. www. mobile number.Email address)has an allowed pattern of characters.

xls – Online searching ● In production of code completion systems and syntax highlighting in integrated development environments(IDEs).intellibitz. www. Regex which you use already ● Search and replace in word processors. ● Directory listing – dir *.com                                                                                                                          training@intellibitz.com .* – dir sales04???.eexe – dir *.

www.intellibitz. Regex can be used for ● Finding doubled words ● Checking inputs from web forms ● Changing date formats ● Finding incorrect case.com                                                                                                                          training@intellibitz.com .

www.com                                                                                                                          training@intellibitz. Matching characters ● The simplest regular expression involves matching a single character.the regular expression test will match the string “test” exactly. ● For example. ● Most characters and letters mostly match themselves.intellibitz.com .

^*+?{[]}\|() is the complete list of metacharacters. www. Metacharacters ● Some characters do not match themselves and are called metacharacters.com .intellibitz. ● .com                                                                                                                          training@intellibitz.

”b” or”c” www.com                                                                                                                          training@intellibitz. ”]” are used for specifying a character class. ● Characters can be listed individually or a or a range of characters can be indicated by giving two characters and separating them by a “-” ● Example [abc] is equivalent to [a-c] will match any of the characters “a.which is a set of character that you wish to match. Metacharacters ● “[“ .intellibitz.com .

Metacharacters ● ^ matches a start of the line ● [^] matches a single character that is not contained within the bracket.com                                                                                                                          training@intellibitz.”m” or “$”.intellibitz.”k”.$ is a metacharacter but inside the character class it stripped of its special nature. ● $ matches the end of the line. – For example [akm$] will match any of the characters “a.com . ● Metacharacters are not active inside classes. www.

[0-9] ● \D Matches any non digit character[^0-9] ● \s matches any white space character[ \t\n\r\f\v] www. – For example [asd\[cdf] here “[“ needed to match inside character class so \ is used to escape [ ● \d matches any decimal digits.com .com                                                                                                                          training@intellibitz. Metacharacters ● \ is used to strip the special meaning of metacharacters.intellibitz.

] will match any white apace character or “.” www.com                                                                                                                          training@intellibitz..intellibitz.” or “. – For example [\s. [a-zA-Z0-9_] ● \W matches any non alphanumeric character. Metacharacters ● \S matches any non white space characters [^ \t\n\r\f\v] ● \w matches any alphanumeric character.com .

com . Metacharacters ● .intellibitz.com                                                                                                                          training@intellibitz. – For example “gray|grey” . ● | A vertical bar separates alternatives.which could be shortened to the equivalent gr(a|e)y. www. can match gray or grey ● () parentheses are used to define the scope and precedence of operator. matches any thing except new line character.

* and + www. ● The most common quantifiers are ?.com .intellibitz.com                                                                                                                          training@intellibitz. Quantifier ● A quantifier after a character or group specifies how often that preceding expression is allowed to occur.

gogle.google.com                                                                                                                          training@intellibitz. www. Quantifier ● ? The ? Indicates there is 0 or 1 of previous expression. ● * The * indicates there are 0. “colou?r “ matches both color and colour.com .gooogle etc. – For example . – For example “go*gle” matches ggle.1 or any of the previous expression .intellibitz.

google. Quantifier ● + The plus sign indicates that there is at least 1 of the previous expression – For example “go+gle “ matches gogle.com                                                                                                                          training@intellibitz.com .intellibitz.gooogle etc www.

– “ab{2.n} specifies occurrence of the character minimum of m times and maximum of n times. Metacharacter ● {m.com .com                                                                                                                          training@intellibitz.3}” matches abb or abbb www.intellibitz.

com                                                                                                                          training@intellibitz.com .intellibitz. CHAPTER 20 DEBUGGING www.

com . Debugging ● Controlling where errors appear ● Fixing parse errors ● Inspecting program data ● Fixing database errors www.intellibitz.com                                                                                                                     training@intellibitz.

Controlling Where Errors Appear ● Programs rarely work correctly the first time ● Use display_errors configuration directive to make error messages display in browser ● Use log_errors to On to send errors to the web server error log ● Parse error. Fatal error.intellibitz. Notice and Strict notices are the different kinds of errors www.com . Warning.com                                                                                                                     training@intellibitz.

com .com                                                                                                                     training@intellibitz.php.net/tokens Contains the list of all tokens that PHP interpreter uses www. Fixing Parse Errors ● The PHP interpreter is really picky but not very chatty ● Use PHP-aware editors with syntax highlighting turned on ● Error messages use tokens ● http://www.intellibitz.

. adding checkpoint to display values of variables ● Use diagnostic print statements ● Use var_dump() to include array in output ● Make sure to edit the right file. Inspecting Program Data ● A program can be syntactically correct but logically flawed..com                                                                                                                     training@intellibitz.com . use __FILE__ special constant to check filename ● ob_start().intellibitz. ob_end_clean www. ob_get_contents().

com . Fixing Database Errors ● Use setErrorHandling() with PEAR_ERROR_CALLBACK ● $db->setErrorHandling (PEAR_ERROR_CALLBACK. ● The callback function must accept one argument.com                                                                                                                     training@intellibitz. 'my_func').intellibitz. which is the error object ● Invoke getDebugInfo () to get more error info www.

com                                                                                                                     training@intellibitz.intellibitz.com . a web server error log. Chapter Summary ● Configuring error display for a web browser. or both ● Configuring the PHP interpreter's error-reporting level ● Getting the benefits of a PHP-aware text editor ● Deciphering parse error messages ● Finding and fixing parse errors www.

intellibitz.com                                                                                                                     training@intellibitz.com . var_dump() and error_log() ● Sending var_dump() output to the error log with output buffering functions ● Writing a custom database error-handling function www. Chapter Summary ● Printing debugging information with print.

com                                                                                                                     training@intellibitz.intellibitz.com . CHAPTER 21 WHAT ELSE WITH PHP www.

intellibitz.com . What Else with PHP? ● Graphics and PDF ● Shockwave/Flash ● Sending and Receiving Mail ● Uploading Files in Forms ● HTML_QuickForm Form-Handling framework ● Classes and Objects ● SQLite ● Advanced XML Processing www.com                                                                                                                     training@intellibitz.

and NNTP ● Command-Line PHP ● PHP-GTK www. What Else with PHP? ● Running Shell Commands ● Encryption ● Talking to Other Languages ● IMAP. POP3.com                                                                                                                     training@intellibitz.intellibitz.com .

library and built-in functions are available ● The PHP Manual http://www.intellibitz.php. Even More with PHP! ● More extensions.net/packages.php ● The PECL Package List http://pecl.php www.php.com                                                                                                                     training@intellibitz.php.com .net/manual ● The PEAR Package List http://pear.net/packages. add-ons.

Chapter Summary ● Printing debugging information with print.com .intellibitz. var_dump() and error_log() ● Sending var_dump() output to the error log with output buffering functions ● Writing a custom database error-handling function www.com                                                                                                                     training@intellibitz.

com training@intellibitz.com .intellibitz.intellibitz. Chennai 91. PH: +91 044 2247 5106 www. IntelliBitz Technologies Training Division 168. Medavakkam Main Road Madipakkam.com www.com                                                                                                                          training@intellibitz.