• Like
PHP Web Programming
Upcoming SlideShare
Loading in...5
×

PHP Web Programming

  • 98,813 views
Uploaded on

Learn PHP Web Programming with this comprehensive tutorial.

Learn PHP Web Programming with this comprehensive tutorial.

More in: Technology
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
No Downloads

Views

Total Views
98,813
On Slideshare
0
From Embeds
0
Number of Embeds
34

Actions

Shares
Downloads
8,412
Comments
26
Likes
157

Embeds 0

No embeds

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
    No notes for slide

Transcript

  • 1. IntelliBitz Technologies Training Division 168, Medavakkam Main Road Madipakkam, Chennai 91. PH: +91 044 2247 5106 www.intellibitz.com [email_address]
  • 2. PHP WEB PROGRAMMING.
  • 3. CHAPTER 1 STARTING WITH PHP.
  • 4. 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
  • 5. 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?”
  • 6. 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
  • 7. 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
  • 8. 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.
  • 9. 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
  • 10. 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
  • 11. Basic Rules of PHP Programs
    • Start and End Tags
    • Whitespace and Case-Sensitivity
    • Comments
  • 12. 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
  • 13. CHAPTER 2 TEXT AND NUMBERS
  • 14. Working with Text and Numbers
    • Defining Text Strings
    • Validating and formatting text
    • Manipulating Text
    • Numbers
    • Arithmetic Operators
    • Variables
    • Putting variables inside strings
  • 15. 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.. single quotes are delimiters
    • Backslash to be used for escaping
    • The escape character can itself be escaped
  • 16. Defining Text Strings
    • Variable names in a double-quoted string will be substituted with its value.This is called as variable interpolation.
    • Here documents obey the same escape-character and variable substitution rules
    • Use a . (period) to combine two strings.The . is the cancatenation.
  • 17. Manipulating Text
    • Validating string using trim () and strlen ()
    • To compare two strings, use the equality operator (==)
    • Use strcasecmp () to compare strings ignoring case
  • 18. Formatting Text
    • Use printf () with a format string and the items to print
    • Zero-padding, displaying signs with printf ()
    • Use of strtolower (), strtoupper (), ucwords (),ucfirst() substr (), str_replace ()
  • 19. String Functions.
    • $length = strlen($string);
    • $arrayStr = explode($separator,$string);
    • $str = implode($separator,$arrayStr);
    • $trimStr = trim($string);
    • $resultStr = str_replace($old,$new,$full);
    • Join() alias of implode().
  • 20. String Functions
    • $padded = str_pad ($string,$length)
        • The returned string is atleast $length characters long.
    • $repeat = str_repeat($string,$n)
        • $string is repeated $n times and returned as string.
    • $array= str_split($string);
        • This function returns an array comprising the characters that make up the string.
    • str_word_count
        • Return information about words used in a string
  • 21. String functions
    • $substring = substr($string,$n,$length)
        • The portion of the string starting from the $n th character for $length number of character is returned.
        • If $n is negative the substring wil start that many characters from end of the string.
        • If $length is negative ,that many characters will be omitted from end of the string.
  • 22. String functions
    • substr_compare
        • int substr_compare ( string $main_str, string $str, int $offset [, int $length [, bool $case_insensitivity]] )
          • substr_compare() compares main_str from position offset with str up to length characters.
          • Returns < 0 if main_str from position offset is less than str, > 0 if it is greater than str, and 0 if they are equal. If length is equal or greater than length of main_str and length is set, substr_compare() prints warning and returns FALSE.
        • If case_insensitivity is TRUE, comparison is case insensitive.
  • 23. String functions
    • substr_replace
        • mixed substr_replace ( mixed $string, string $replacement, int $start [, int $length] )
          • Replace text within a portion of a string
    • substr_count
        • int substr_count ( string $haystack, string $needle [, int $offset [, int $length]] )
          • substr_count() returns the number of times the needle substring occurs in the haystack string. Please note that needle is case sensitive.
  • 24. String functions.
    • strtolower(),strtoupper()
        • Converts the case to lower and upper respectively.
    • strcmp($string1,$string2)
        • Returns 0 if both are equal
        • Returns positive int if first string has higher ASCII value.
        • Returns negative int if second string has higher ASCII value.
    • similar_text (string $first,string $second
        • Calculate the similarity between two strings
          • It returns the number matching characters in both string
  • 25. String functions
    • printf($format,$var1.$var2...);
        • The $format argument returns how the subsequent arguments are printed.
    • $array = sscanf($string,$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.if match is found it returns a string starting from the character it just matched to end of the string.
  • 26. String functions.
    • $res= strpos($bigstring,$search)
        • The function returns the position of the $search string in $bigstring
    • rtrim(),ltrim(),str_ireplace(),strcasecmp(), strnatcmp(),strnatcasecmp(),stripos(), strrpos().Chop is alias of rtrim
    • string chr ( int $ascii )
        • Returns a one-character string containing the character specified by ascii
  • 27. String functions
    • strrev
        • Reverse a string
    • chunk_split — Split a string into smaller chunks
        • string chunk_split ( string $body [, int $chunklen [, string $end]] )
    • string convert_cyr_string ( string $str, string $from, string $to )
  • 28. String functions
    • strstr
        • Find first occurrence of a string
          • string strstr ( string $haystack, string $needle )
        • Returns part of haystack string from the first occurrence of needle to the end of haystack.
        • If needle is not found, returns FALSE.
        • If needle is not a string, it is converted to an integer and applied as the ordinal value of a character.
        • Stristr() - case insensitive
    • Strchr
        • Alias of strstr()
  • 29. String functions
    • Strtok()
        • string strtok ( string $str, string $token )
          • strtok() splits a string (str) into smaller strings (tokens), with each token being delimited by any character from token.
    • Strtr()
        • string strtr ( string $str, string $from, string $to )
          • This function returns a copy of str, translating all occurrences of each character in from to the corresponding character in to.
  • 30. String functions
    • strcspn
        • int strcspn ( string $str1, string $str2 [, int $start [, 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.
    • Strcoll
        • Locale based string comparison
        • If the current locale is C or POSIX, this function is equivalent to strcmp().
        • Note that this comparison is case sensitive, and unlike strcmp() this function is not binary safe.
  • 31. String functions
    • convert_uuencode(),convert_uudecode().
    • Levenshtein ()
      • Calculate Levenshtein distance between two strings or -1, if one of the argument strings is longer than the limit of 255 characters.
    • 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.
  • 32. String functions
    • string addslashes ( string $str )
        • Returns a string with backslashes before characters that need to be quoted in database queries etc. These characters are single quote ('), double quote (&quot;), backslash () and NUL (the NULL byte).
    • addcslashes(),stripcslashes(), stripslashes().
    • str_shuffle
        • Randomly shuffles a string
    • str_split
        • Convert a string to an array
  • 33. String functions
    • string htmlentities ( string $string [, int $quote_style [, string $charset]] )
        • Convert all applicable characters to HTML entities
        • ENT_COMPAT Will convert double-quotes and leave single-quotes alone.
        • ENT_QUOTES Will convert both double and single quotes.
        • ENT_NOQUOTES Will leave both double and single quotes unconverted.
        • charset-ISO-8859-1,ISO-8859-15,UTF-8.
  • 34. String functions
    • Htmlspecialchars()
        • Convert special characters to HTML entities.
        • This function returns a string with some of these conversions made
        • '&' (ampersand) becomes '&amp;'
        • '&quot;' (double quote) becomes '&quot;' when ENT_NOQUOTES is not set.
        • ''' (single quote) becomes '&#039;' only when ENT_QUOTES is set.
        • '<' (less than) becomes '&lt;'
        • '>' (greater than) becomes '&gt;'
  • 35. String functions
    • htmlspecialchars_decode
          • Convert special HTML entities back to characters
          • string htmlspecialchars_decode ( string $string [, int $quote_style] )
          • This function is the opposite of htmlspecialchars(). It converts special HTML entities back to characters.Returns the decoded string.
    • nl2br
          • Inserts HTML line breaks before all newlines in a string
          • Returns string with '<br />' inserted before all newlines.
    • strip_tags
          • Strip HTML and PHP tags from a string
  • 36. String functions
    • md5($string)
        • Calculates the md5 hash of a given string using RSA Data Security, Inc. MD5 Message-Digest Algorithm, and returns that hash. The hash is a 32-character hexadecimal number.
    • md5_file($filename)
        • md5_file — Calculates the md5 hash of a given file.
    • sha1
        • Calculate the sha1 hash of a string
  • 37. String functions
    • soundex
        • Calculate the soundex key of a string
          • Soundex keys have the property that words pronounced similarly produce the same soundex key, and can thus be used to simplify searches in databases where you know the pronunciation but not the spelling.
          • This soundex function returns a string 4 characters long, starting with a letter.
  • 38. String functions
    • Metaphone
        • Calculate the metaphone key of a string.
          • Similar to soundex() metaphone creates the same key for similar sounding words.
          • It's more accurate than soundex() as it knows the basic rules of English pronunciation. The metaphone generated keys are of variable length.
    • money_format
        • Formats a number as a currency string
    • number_format
        • Format a number with grouped thousands
  • 39. 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
  • 40. 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:
          • . + * ? [ ^ ] ( $ )
        • Note: This function is binary-safe.
  • 41. String functions
    • print
        • Output a string
        • int print ( string $arg )
        • Outputs arg. Returns 1, always.
          • print() is not actually a real function (it is a language construct) so you are not required to use parentheses with its argument list.
    • sprintf
        • Return a formatted string
    • str_getcsv
        • Parse a CSV string into an array.
  • 42. String functions
    • wordwrap
          • Wraps a string to a given number of characters using a string break character
        • string wordwrap ( string $str [, int $width [, string $break [, bool $cut]]] )
          • Returns a string with str wrapped at the column number specified by the optional width parameter. The line is broken using the (optional) break parameter.
          • wordwrap() will automatically wrap at column 75 and break using ' ' (newline) if width or break are not given.
          • If the cut is set to 1, the string is always wrapped at the specified width. So if you have a word that is larger than the given width, it is broken apart
  • 43. 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 )
  • 44. Type specifiers
    • type specifier that says what type the argument data should be treated as. Possible types:
    • % - a literal percent character. No argument is required.
    • b - the argument is treated as an integer, and presented as a binary number.
    • c - the argument is treated as an integer, and presented as the character with that ASCII value.
    • d - the argument is treated as an integer, and presented as a (signed) decimal number.
    • e - the argument is treated as scientific notation (e.g. 1.2e+2).
    • u - the argument is treated as an integer, and presented as an unsigned decimal number.
    • f - the argument is treated as a float, and presented as a floating-point number (locale aware).
    • F - the argument is treated as a float, and presented as a floating-point number (non-locale aware). Available since PHP 4.3.10 and PHP 5.0.3.
    • o - the argument is treated as an integer, and presented as an octal number.
    • s - the argument is treated as and presented as a string.
    • x - the argument is treated as an integer and presented as a hexadecimal number (with lowercase letters).
    • X - the argument is treated as an integer and presented as a hexadecimal number (with uppercase letters).
  • 45. Numbers
    • Numbers – floating point and decimals
    • Arithmetic operators
    • +, -, *, /, %
    • Operator precedence
    • Grouping operations inside parentheses, will execute whats inside the parentheses first
  • 46. Variables
    • In PHP, 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.
  • 47. 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”
    • +=, .=, ++, --
    • Variable interpolation and curly braces
  • 48. Number functions
    • $absvalue = abs($number)
        • If $number is negative the value returned is positive.
    • $remainder = $dividend % $divisor;
        • % called modulus operator,returns the remainder.
    • $result = pow($number,$pow);
        • PHP does not have power operator. This function must be used instead.
    • $root = sqrt($number)
  • 49. Number functions
    • $ceilinged = ceil($number);
        • Rounds a fractional number up to next integer.
    • $floored = floor($number);
        • Same as ceil but returned value is still a float type
    • $rounded = round($number);
        • The function rounds the number to the nearest whole number.
  • 50. Number functions
    • $maximum = max ($array);
    • $minimum = min($array);
    • $newNumber = base_convert($number,$oldbase,$newbase);
        • This function converts a number in any base , up to base 36,to a number in any other base,again upto base 36.
    • $result = rand($min,$max)
        • Generates random numbers between $min and $max
  • 51. Number functions
    • $result = exp($power);
        • The function returns the natural base 'e' raised to the specified power.
    • $result = log($number,$base);
        • This function returns the logarithm of the specified number to the base provided.
  • 52. Number functions
    • sin,cos,tan,sinh,cosh,tanh,asin,asinh,acos, acosh,atan,atanh.
    • Float atan2(float $y,float $x)
        • This function calculates the arc tangent of the two variables x and y. It is similar to calculating the arc tangent of y / x, except that the signs of both arguments are used to determine the quadrant of the result.
        • The function returns the result in radians, which is between -PI and PI (inclusive).
  • 53. Number functions
    • dechex,decoct,decbin.
    • fmod,hypot.
    • is_finite, is_infinite,is_nan.
    • deg2rad,rad2deg,pi.
    • float lcg_value ( void )
        • lcg_value() returns a pseudo random number in the range of (0, 1). Combined linear congruential generator.
  • 54. Number functions
    • mt_rand()
        • By default, PHP uses the libc random number generator with the rand() function.The mt_rand() uses a random number generator with known characteristics using the » Mersenne Twister, which will produce random numbers four times faster than what the average libc rand() provides.
  • 55. Chapter Summary
    • Defining strings in 3 different ways: single quotes, double quotes, 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, removing leading and trailing whitespace
    • Formatting string with printf ()
  • 56. Chapter Summary
    • Manipulating the case of string with strtolower (), 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
  • 57. Chapter Summary
    • Naming variables appropriately
    • Using combined operators with variables
    • Using increment and decrement operators with variables
    • Interpolating variables in strings
  • 58. CHAPTER 3 Making Decisions and Looping
  • 59. Making Decisions and Looping
    • Understanding true and false
    • Making Decisions
    • Building Complicated Decisions
    • Repeating Yourself
  • 60. Understanding true and false
    • All expression in PHP program has a truth value: true or false
    • Most scalar values are true. All integers and floating point (except 0 and 0.0) are true
    • All strings are true except for two: an empty string and the string containing only 0
    • An empty array is false
  • 61. Control statements
    • Any PHP script is built out of a series of statements.
    • A statement can be an assignment, a function call, a loop, a conditional statement or even a statement that does nothing (an empty statement).
    • Statements usually end with a semicolon.
    • In addition, statements can be grouped into a statement-group by encapsulating a group of statements with curly braces {...}.
    • A statement-group is a statement by itself as well.
  • 62. Making Decisions
    • If () construct runs a block of code if its test expression is true
    • Add an else to if() statement, 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, at most one of the code blocks is run
  • 63. If statement
    • it allows for conditional execution of code fragments.
    • PHP features an if structure that is similar to that of C:
    • The expression is evaluated to its Boolean value. If expression evaluates to TRUE, PHP will execute statement, and if it evaluates to FALSE - it'll ignore it.
    if (expr) statement
  • 64. If statements
    • Often you'd want to have more than one statement to be executed conditionally.
    • In such case there's no need to wrap each statement with an if clause. Instead, you can group several statements into a statement group.
    • If statements can be nested indefinitely within other if statements, which provides you with complete flexibility for conditional execution of the various parts of your program.
    <?php if ($a > $b)    echo &quot;a is bigger than b&quot;; ?> <?php if ($a > $b) {    echo &quot;a is bigger than b&quot;;    $b = $a; } ?>
  • 65. If else statement
    • Often you'd want to execute a statement if a certain condition is met, and a different statement if the condition is not met. This is what else is for.
    • else extends an if statement to execute a statement in case the expression in the if statement evaluates to FALSE.
    • The else statement is only executed if the if expression evaluated to FALSE, and if there were any elseif expressions - only if they evaluated to FALSE this else is executed
    <?php if ($a > $b) {    echo &quot;a is bigger than b&quot;; } else {    echo &quot;a is NOT bigger than b&quot;; } ?>
  • 66. else if
    • elseif, as its name suggests, is a combination of if and else.
    • It extends an if statement to execute a different statement in case the original if expression evaluates to FALSE.
    • However, unlike else, it will execute that alternative expression only if the elseif conditional expression evaluates to TRUE.
    <?php if ($a > $b) {    echo &quot;a is bigger than b&quot;; } elseif ($a == $b) {    echo &quot;a is equal to b&quot;; } else {    echo &quot;a is smaller than b&quot;; } ?>
  • 67. elseif statement
    • There may be several elseifs within the same if statement. The first elseif expression (if any) that evaluates to TRUE would be executed.
    • In PHP, you can also write 'else if' (in two words) and the behavior would be identical to the one of 'elseif' (in a single word). 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.
    • The elseif statement is only executed if the preceding if expression and any preceding elseif expressions evaluated to FALSE, and the current elseif expression evaluated to TRUE.
  • 68. while()
    • While statements tells PHP to execute the nested statement(s) repeatedly, as long as the while expression evaluates to TRUE.
    • The value of the expression is checked each time at the beginning of the loop, so even if this value changes during the execution of the nested statement(s), execution will not stop until the end of the iteration (each time PHP runs the statements in the loop is one iteration).
    • Sometimes, if the while expression evaluates to FALSE from the very beginning, the nested statement(s) won't even be run once.
    while (expr) statement <?php $i = 1; while ($i <= 10) {    echo $i++;  } /* the printed value would be $i before the increment (post-increment) */ ?>
  • 69. do while
    • do-while loops are very similar to while loops, except the truth expression is checked at the end of each iteration instead of in the beginning.
    • The main difference from regular while loops is that the first iteration of a do-while loop is guaranteed to run as the truth expression is only checked at the end of the iteration).
    • whereas it's may not necessarily run with a regular while loop the truth expression is checked at the beginning of each iteration, if it evaluates to FALSE right from the beginning, the loop execution would end immediately.
    <?php $i = 0; do {    echo $i; } while ($i > 0); ?>
  • 70. for statement
    • A variable can be initialised once unconditionally at the beginning of the loop.
    • In the beginning of each iteration, test condition is checked. If it evaluates to TRUE, the loop continues and the nested statement(s) are executed. If it evaluates to FALSE, the execution of the loop ends.
    • At the end of each iteration, increment value is evaluated (executed).
    for (initialise; test condition; increment value) statement for ($i = 1; $i <= 10; $i++) {   echo $i; } for ($i = 1; ; $i++) { if ($i > 10) { break; } echo $i; }
  • 71. for loop
    • Each of the expressions can be empty or contain multiple expressions separated by commas.
    • Comma separated expressions in test condition are treated similarly to being separated by the || operator but has a lower precedence than ||. expr2 being empty means the loop should be run indefinitely (PHP implicitly considers it as TRUE, like C).
    • This may not be as useless as you might think, since often you'd want to end the loop using a conditional break statement instead of using the for truth expression.
    $i = 1; for (; ; ) {    if ($i > 10) {        break;    }    echo $i;    $i++; } for ($i = 1, $j = 0; $i <= 10; $j += $i, print $i, $i++);
  • 72. foreach loop
    • PHP 4 introduced a foreach construct, much like Perl
    • This simply gives an easy way to iterate over arrays.
    • 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; the second is a minor but useful extension of the first:
    foreach (array_expression as $value) statement foreach (array_expression as $key => $value) statement
  • 73. foreach
    • The first form loops over the array given by array_expression. On each loop, the value of the current element is assigned to $value and the internal array pointer is advanced by one (so on the next loop, you'll be looking at the next element).
    • The second form does the same thing, except that the current element's key will be assigned to the variable $key on each loop.
    • you can easily modify array's elements by preceding $value with &. This will assign reference instead of copying the value.
    <?php $arr = array(1, 2, 3, 4); foreach ($arr as &$value) {    $value = $value * 2; } // $arr is now array(2, 4, 6, 8) foreach($arr as $key =>$val){ print”$key=$val”; } ?>
  • 74. foreach
    • When foreach first starts executing, the internal array pointer is automatically reset to the first element of the array. This means that you do not need to call reset() before a foreach loop.
    • Unless the array is referenced, foreach operates on a copy of the specified array and not the array itself.
  • 75. break
    • break ends execution of the current for, foreach, while, do-while or switch structure.
    • break accepts an optional numeric argument which tells it how many nested enclosing structures are to be broken out of.
    $i = 0; while (++$i) {    switch ($i) {    case 5:        echo &quot;At 5<br /> &quot;;        break 1;  /* Exit only the switch. */    case 10:        echo &quot;At 10; quitting<br /> &quot;;        break 2;  /* Exit the switch and the while. */    default:        break;    } }
  • 76. continue
    • continue is used within looping structures to skip the rest of the current loop iteration and continue execution at the condition evaluation and then the beginning of the next iteration.
    • Note that in PHP the switch statement is considered a looping structure for the purposes of continue.
    • continue accepts an optional numeric argument which tells it how many levels of enclosing loops it should skip to the end of.
    $i = 0; while ($i++ < 5) {    echo &quot;Outer<br /> &quot;;    while (1) {        echo &quot;Middle<br /> &quot;;        while (1) {            echo &quot;Inner<br /> &quot;;            continue 3;        }    echo &quot;This never gets output.<br /> &quot;;    }    echo &quot;Neither does this.<br /> &quot;; }
  • 77. switch
    • The switch statement is similar to a series of IF statements on the same expression. In many occasions, you may want to compare the same variable (or expression) with many different values, and execute a different piece of code depending on which value it equals to. This is exactly what the switch statement is for.
    • Note that unlike some other languages, the continue statement applies to switch and acts similar to break. If you have a switch inside a loop and wish to continue to the next iteration of the outer loop, use continue 2.
    <?php switch ($i) { case 0:    echo &quot;i equals 0&quot;;    break; case 1:    echo &quot;i equals 1&quot;;    break; case 2:    echo &quot;i equals 2&quot;;    break; } ?>
  • 78. switch
    • The switch statement executes line by line (actually, statement by statement).
    • In the beginning, no code is executed. Only when a case statement is found with a value that matches the value of the switch expression does PHP begin to execute the statements.
    • PHP continues to execute the statements until the end of the switch block, or the first time it sees a break statement.
    • Thus, it is important not to forget break statements to avoid mistakes.
    ?php switch ($i) { case 0:    echo &quot;i equals 0&quot;; case 1:    echo &quot;i equals 1&quot;; case 2:    echo &quot;i equals 2&quot;; } ?>
  • 79. Alternative syntax
    • PHP offers an alternative syntax for some of its control structures; namely, if, while, for, foreach, and switch. In each case, the basic form of the alternate syntax is to change the opening brace to a colon (:) and the closing brace to endif;, endwhile;, endfor;, endforeach;, or endswitch;, respectively.
    <?php if ($a == 5): ?> A is equal to 5 <?php endif; ?> <?php if ($a == 5):    echo &quot;a equals 5&quot;;    echo &quot;...&quot;; elseif ($a == 6):    echo &quot;a equals 6&quot;;    echo &quot;!!!&quot;; else:    echo &quot;a is neither 5 nor 6&quot;; endif; ?>
  • 80. 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.
    • return() will also end the execution of an eval() statement or script file.
    • Eval() evaluates the string as PHP code.
  • 81. return
    • Note that since return() is a language construct and not a function, the parentheses surrounding its arguments are not required. It is common to leave them out, and you actually should do so as PHP has less work to do in this case.
    • You should never use parentheses around your return variable when returning by reference, as this will not work. You can only return variables by reference, not the result of a statement. If you use return ($a); then you're not returning a variable, but the result of the expression ($a) (which is, of course, the value of $a).
  • 82. require()
    • The require() statement includes and evaluates the specific file.
      • Require() includes and evaluates a specific file.
    <?php require 'prepend.php'; require $somefile; require ('somefile.txt'); ?>
  • 83. include()
    • The include() statement includes and evaluates the specified file.
    • The difference between include() and require() The two constructs are identical in every way except how they handle failure.
    • They both produce a Warning, but require() results in a Fatal Errorand stops execution.
    • include() does not behave this way, the script will continue regardless.
    • use require() if you want a missing file to halt processing of the page.
  • 84. require_once()
    • This is a behavior similar to the require() statement, with the only difference being that if the code from a file has already been included, it will not be included again.
    • 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, variable value reassignments, etc.
  • 85. require_once()
    • Be aware, 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).
    <?php require_once(&quot;a.php&quot;); // this will include a.php require_once(&quot;A.php&quot;); // this will include a.php //again on Windows! (PHP 4 only) ?>
  • 86. include_once()
    • This is a behavior similar to the include() statement, with the only difference being that if the code from a file has already been included, it will not be included again.
  • 87. declare
    • The declare construct is used to set execution directives for a block of code. The syntax of declare is similar to the syntax of other flow control constructs
    • A tick is an event that occurs for every N low-level statements executed by the parser within the declare block.
    • The value for N is specified using ticks=N within the declare blocks's directive section.
    • The event(s) that occur on each tick are specified using the register_tick_function()
    declare (directive) statement <?php // these are the same: // you can use this: declare(ticks=1) {    // entire script here } // or you can use this: declare(ticks=1); // entire script here ?>
  • 88. ticks
    • The example profiles the PHP code within the 'declare' block, recording the time at which every second low-level statement in the block was executed.
    • This information can then be used to find the slow areas within particular segments of code.
    • This process can be performed using other methods: using ticks is more convenient and easier to implement.
  • 89. ticks <?php // A function that records the time when it is called function profile($dump = FALSE) {    static $profile;    // Return the times stored in profile, then erase it    if ($dump) {        $temp = $profile;        unset($profile);        return $temp;    } $profile[] = microtime(); } // Set up a tick handler register_tick_function(&quot;profile&quot;); // Initialize the function before the declare block profile(); // Run a block of code, throw a tick every 2nd statement declare(ticks=2) {   for ($x = 1; $x < 50; ++$x) { echo similar_text(md5($x), md5($x*$x)), &quot;<br />;&quot;;    } } // Display the data stored in the profiler print_r(profile(TRUE)); ?>
  • 90. 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
  • 91. Repeating Yourself
    • When a program does something repeatedly, its called looping
    • Use while(), for(), foreach() for looping
    • Multiple expression in for() is allowed but only one test expression is possible
  • 92. Chapter Summary
    • Evaluating an expression's truth value: true or false
    • Making a decision with if().
    • Extending if() with else
    • Extending if() with elseif()
    • Putting multiple statements inside an if(), elseif(), or else code block
  • 93. Chapter Summary
    • Using the equality (==) and not-equals (!=) operators in test expressions.
    • Distinguishing between assignment (=) and equality comparison (==)
    • Using the less-than (<), greater-than (>), less-than-or-equal-to (<=), and greater-than-or-equal-to (>=) operators in test expressions
  • 94. 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
  • 95. 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 ()
  • 96. CHAPTER 4 WORKING WITH ARRAYS
  • 97. Working with Arrays
    • Creating an Array
    • Creating a Numeric Array
    • Looping through Arrays
    • Modifying Arrays
    • Sorting Arrays
    • Using Multidimensional Arrays
  • 98. Array Basics and Creation
    • An array is made up of elements. Each element has a key and a value. Only one element with a given key can exist.
    • Any string or number can be the key
    • An element value can be string, number, true or false; it can also be another array
  • 99. Creating an Array
    • Assign a value to a particular array key to create an array
    • Use array() language construct
    • With array(), specify a comma-delimited list of key/value pairs
    • Beware of array and scalar name collision
  • 100. Creating a Numeric Array
    • Use array() with only a list of values, 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
  • 101. 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(), the elements are accessed in the order they were added to the array
    • Use for() to access elements in numerical key order
  • 102. 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
  • 103. array()
    • Create an array
    • array array ( [mixed $...] )
    • Returns an array of the parameters. The parameters can be given an index with the => operator.
    <?php $fruits = array (    &quot;fruits&quot;  => array(&quot;a&quot; => &quot;orange&quot;, &quot;b&quot; => &quot;banana&quot;, &quot;c&quot; => &quot;apple&quot;),    &quot;numbers&quot; => array(1, 2, 3, 4, 5, 6),    &quot;holes&quot;  => array(&quot;first&quot;, 5 => &quot;second&quot;, &quot;third&quot;) ); ?>
  • 104. array <?php $array = array(1, 1, 1, 1,  1, 8 => 1,  4 => 1, 19, 3 => 13); print_r($array); ?> Array (    [0] => 1    [1] => 1    [2] => 1    [3] => 13    [4] => 1    [8] => 1    [9] => 19 )
  • 105. array() <?php $firstquarter = array(1 => 'January', 'February', 'March'); print_r($firstquarter); ?> The above example will output: Array ( [1] => January [2] => February [3] => March ) 1-based index with array() <?php $foo = array('bar' => 'baz'); echo &quot;Hello {$foo['bar']}!&quot;; // Hello baz! ?>
  • 106. sort
    • Sort an array
    • Description
    • bool sort ( array &$array [, int $sort_flags] )
    • This function sorts an array. Elements will be arranged from lowest to highest when this function has completed.
    • Note: This function assigns new keys for the elements in array. It will remove any existing keys you may have assigned, rather than just reordering the keys.
    • Returns TRUE on success or FALSE on failure.
    <?php $fruits = array(&quot;lemon&quot;, &quot;orange&quot;, &quot;banana&quot;, &quot;apple&quot;); sort($fruits); foreach ($fruits as $key => $val) {    echo &quot;fruits[&quot; . $key . &quot;] = &quot; . $val . &quot; &quot;; } ?> The above example will output: fruits[0] = apple fruits[1] = banana fruits[2] = lemon fruits[3] = orange
  • 107. rsort
    • Sort an array in reverse order
    • bool rsort ( array &$array [, int $sort_flags] )
    • This function sorts an array in reverse order (highest to lowest).
    • This function assigns new keys for the elements in array. It will remove any existing keys you may have assigned, rather than just reordering the keys.
    • Returns TRUE on success or FALSE on failure.
  • 108. rsort <?php $fruits = array(&quot;lemon&quot;, &quot;orange&quot;, &quot;banana&quot;, &quot;apple&quot;); rsort($fruits); foreach ($fruits as $key => $val) {    echo &quot;$key = $val &quot;; } ?> The above example will output: 0 = orange 1 = lemon 2 = banana 3 = apple
  • 109. asort
    • Sort an array and maintain index association
    • bool asort ( 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. This is used mainly when sorting associative arrays where the actual element order is significant.
    • Returns TRUE on success or FALSE on failure.
  • 110. asort <?php $fruits = array(&quot;d&quot; => &quot;lemon&quot;, &quot;a&quot; => &quot;orange&quot;, &quot;b&quot; => &quot;banana&quot;, &quot;c&quot; => &quot;apple&quot;); asort($fruits); foreach ($fruits as $key => $val) {    echo &quot;$key = $val &quot;; } ?> The above example will output: c = apple b = banana d = lemon a = orange The fruits have been sorted in alphabetical order, and the index associated with each element has been maintained.
  • 111. 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. This is used mainly when sorting associative arrays where the actual element order is significant.
    • Returns TRUE on success or FALSE on failure.
  • 112. arsort <?php $fruits = array(&quot;d&quot; => &quot;lemon&quot;, &quot;a&quot; => &quot;orange&quot;, &quot;b&quot; => &quot;banana&quot;, &quot;c&quot; => &quot;apple&quot;); arsort($fruits); foreach ($fruits as $key => $val) {    echo &quot;$key = $val &quot;; } ?> The above example will output: a = orange d = lemon b = banana c = apple The fruits have been sorted in reverse alphabetical order, and the index associated with each element has been maintained.
  • 113. ksort
    • Sort an array by key
    • bool ksort ( array &$array [, int $sort_flags] )
    • Sorts an array by key, maintaining key to data correlations. This is useful mainly for associative arrays.
    • Returns TRUE on success or FALSE on failure.
    <?php $fruits = array(&quot;d&quot;=>&quot;lemon&quot;, &quot;a&quot;=>&quot;orange&quot;, &quot;b&quot;=>&quot;banana&quot;, &quot;c&quot;=>&quot;apple&quot;); ksort($fruits); foreach ($fruits as $key => $val) {    echo &quot;$key = $val &quot;; } ?> The above example will output: a = orange b = banana c = apple d = lemon
  • 114. krsort
    • Sort an array by key in reverse order
    • bool krsort ( array &$array [, int $sort_flags] )
    • Sorts an array by key in reverse order, maintaining key to data correlations. This is useful mainly for associative arrays.
    • Returns TRUE on success or FALSE on failure.
    <?php $fruits = array(&quot;d&quot;=>&quot;lemon&quot;, &quot;a&quot;=>&quot;orange&quot;, &quot;b&quot;=>&quot;banana&quot;, &quot;c&quot;=>&quot;apple&quot;); krsort($fruits); foreach ($fruits as $key => $val) {    echo &quot;$key = $val &quot;; } ?> The above example will output: d = lemon c = apple b = banana a = orange
  • 115. natsort
    • Sort an array using a &quot;natural order&quot; 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. This is described as a &quot;natural ordering&quot;. 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.
    • natcasesort -- case insensitive.
  • 116. natsort <?php $array1 = $array2 = array(&quot;img12.png&quot;, &quot;img10.png&quot;, &quot;img2.png&quot;, &quot;img1.png&quot;); sort($array1); echo &quot;Standard sorting &quot;; print_r($array1); natsort($array2); echo &quot; Natural order sorting &quot;; print_r($array2); ?> The above example will output: Standard sorting Array ( [0] => img1.png [1] => img10.png [2] => img12.png [3] => img2.png ) Natural order sorting Array ( [3] => img1.png [2] => img2.png [1] => img10.png [0] => img12.png )
  • 117. usort
    • Sort an array by values using a user-defined comparison function
    • Description
    • bool usort ( array &$array, callback $cmp_function )
    • This function will sort an array by its values using a user-supplied comparison function. If the array you wish to sort needs to be sorted by some non-trivial criteria, you should use this function.
    • The comparison function must return an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second.
  • 118. usort <?php function cmp($a, $b) {    if ($a == $b) {        return 0;    }    return ($a < $b) ? -1 : 1; } $a = array(3, 2, 5, 6, 1); usort($a, &quot;cmp&quot;); foreach ($a as $key => $value) {    echo &quot;$key: $value &quot;; } ?> The above example will output: 0: 1 1: 2 2: 3 3: 5 4: 6
  • 119. usort
    • Note: If two members compare as equal, their order in the sorted array is undefined. Up to PHP 4.0.6 the user defined functions would keep the original order for those elements, but with the new sort algorithm introduced with 4.1.0 this is no longer the case as there is no solution to do so in an efficient way.
    • Note: This function assigns new keys for the elements in array. It will remove any existing keys you may have assigned, rather than just reordering the keys.
    • Returns TRUE on success or FALSE on failure.
  • 120. uasort
    • Sort an array with a user-defined comparison function and maintain index association
    • bool uasort ( array &$array, callback $cmp_function )
    • This function sorts an array such that array indices maintain their correlation with the array elements they are associated with. This is used mainly when sorting associative arrays where the actual element order is significant. The comparison function is user-defined.
    • Returns TRUE on success or FALSE on failure.
  • 121. uksort
    • Sort an array by keys using a user-defined comparison function
    • bool uksort ( array &$array, callback $cmp_function )
    • uksort() will sort the keys of an array using a user-supplied comparison function. If the array you wish to sort needs to be sorted by some non-trivial criteria, you should use this function.
    • Function cmp_function should accept two parameters which will be filled by pairs of array keys. The comparison function must return an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second.
    • Returns TRUE on success or FALSE on failure.
  • 122. uksort <?php function cmp($a, $b) {    $a = ereg_replace('^(a|an|the) ', '', $a);    $b = ereg_replace('^(a|an|the) ', '', $b);    return strcasecmp($a, $b); } The above example will output: an apple: 3 a banana: 4 the Earth: 2 John: 1 $a = array(&quot;John&quot; => 1, &quot;the Earth&quot; => 2, &quot;an apple&quot; => 3, &quot;a banana&quot; => 4); uksort($a, &quot;cmp&quot;); foreach ($a as $key => $value) {    echo &quot;$key: $value &quot;; } ?>
  • 123. list
    • Assign variables as if they were an array
    • void list ( mixed $varname, mixed $... )
    • Like array(), this is not really a function, but a language construct. list() is used to assign a list of variables in one operation.
    • Note: list() only works on numerical arrays and assumes the numerical indices start at 0.
    <?php $info = array('coffee', 'brown', 'caffeine'); // Listing all the variables list($drink, $color, $power) = $info; echo &quot;$drink is $color and $power makes it special. &quot;; // Listing some of them list($drink, , $power) = $info; echo &quot;$drink has $power. &quot;; // Or let's skip to only the third one list( , , $power) = $info; echo &quot;I need $power! &quot;; ?>
  • 124. shuffle
    • Shuffle an array
    • bool shuffle ( array &$array )
    • This function shuffles (randomizes the order of the elements in) an array. Note: This function assigns new keys for the elements in array. It will remove any existing keys you may have assigned, rather than just reordering the keys.
    <?php $numbers = range(1, 20); shuffle($numbers); foreach ($numbers as $number) {    echo &quot;$number &quot;; } ?>
  • 125. array_change_key_case
    • Returns an array with all string keys lowercased or uppercased
      • array array_change_key_case ( array $input [, int $case] )
      • array_change_key_case() changes the keys in the input array to be all lowercase or uppercase.
      • The change depends on the last optional case parameter.
      • You can pass two constants there, CASE_UPPER and CASE_LOWER. The default is CASE_LOWER.
      • The function will leave number indices as is.
    <?php $input_array = array(&quot;FirSt&quot; => 1, &quot;SecOnd&quot; => 4); print_r(array_change_key_case($input_array, CASE_UPPER)); ?> The above example will output: Array ( [FIRST] => 1 [SECOND] => 4 )
  • 126. array_chunk()
    • Split an array into chunks
      • array array_chunk ( array $input, int $size [, bool $preserve_keys] )
      • array_chunk() splits the array into several arrays with size values in them. You may also have an array with less values at the end. You get the arrays as members of a multidimensional array indexed with numbers starting from zero.
    <?php $input_array = array('a', 'b', 'c', 'd', 'e'); print_r(array_chunk($input_array, 2)); ?> The below example will output: Array ( [0] => Array ( [0] => a [1] => b ) [1] => Array ( [0] => c [1] => d ) [2] => Array ( [0] => e ) )
  • 127. array_chunk()
    • By setting the optional preserve_keys parameter to TRUE, you can force PHP to preserve the original keys from the input array.
    • If you specify FALSE new number indices will be used in each resulting array with indices starting from zero. The default is FALSE.
    <?php $input_array = array('a', 'b', 'c', 'd', 'e'); print_r(array_chunk($input_array, 2, true)); ?> The below example will output: Array ( [0] => Array ( [0] => a [1] => b ) [1] => Array ( [2] => c [3] => d ) [2] => Array ( [4] => e ) )
  • 128. key
    • Fetch a key from an associative array
    • mixed key ( array &$array )
    • key() returns the index element of the current array position.
    <?php $array = array(    'fruit1' => 'apple',    'fruit2' => 'orange',    'fruit3' => 'grape',    'fruit4' => 'apple',    'fruit5' => 'apple'); / / this cycle echoes all associative array // key where value equals &quot;apple&quot; while ($fruit_name = current($array)) {    if ($fruit_name == 'apple') {        echo key($array).'<br />';    }    next($array); } ?>
  • 129. count
    • Count elements in an array, or properties in an object
    • int count ( mixed $var [, int $mode] )
    • Returns the number of elements in var, which is typically an array, since anything else will have one element.
    • For objects, if you have SPL installed, you can hook into count() by implementing interface Countable. The interface has exactly one method, count(), which returns the return value for the count() function.
    • If var is not an array or an object with implemented Countable interface, 1 will be returned. There is one exception, if var is NULL, 0 will be returned.
    • The optional mode parameter is available as of PHP 4.2.0.
    • If the optional mode parameter is set to COUNT_RECURSIVE (or 1), count() will recursively count the array. This is particularly useful for counting all the elements of a multidimensional array. The default value for mode is 0. count() does not detect infinite recursion.
  • 130. count <?php $a[0] = 1; $a[1] = 3; $a[2] = 5; $result = count($a); // $result == 3 $b[0]  = 7; $b[5]  = 9; $b[10] = 11; $result = count($b); // $result == 3 $result = count(null); // $result == 0 $result = count(false); // $result == 1 ?> sizeof — Alias of count()
  • 131. current
    • Return the current element in an array
    • Description
    • mixed current ( array &$array )
    • Every array has an internal pointer to its &quot;current&quot; element, which is initialized to the first element inserted into the array.
    • The current() function simply returns the value of the array element that's currently being pointed to by the internal pointer. It does not move the pointer in any way. If the internal pointer points beyond the end of the elements list, current() returns FALSE.
    • Pos is alias of current
  • 132. next
    • Advance the internal array pointer of an array
    • mixed next ( array &$array )
    • Returns the array value in the next place that's pointed to by the internal array pointer, or FALSE if there are no more elements.
    • next() behaves like current(), with one difference. It advances the internal array pointer one place forward before returning the element value. That means it returns the next array value and advances the internal array pointer by one. If advancing the internal array pointer results in going beyond the end of the element list, next() returns FALSE.
    <?php $transport = array('foot', 'bike', 'car', 'plane'); $mode = current($transport); // $mode = 'foot'; $mode = next($transport);    // $mode = 'bike'; $mode = next($transport);    // $mode = 'car'; $mode = prev($transport);    // $mode = 'bike'; $mode = end($transport);    // $mode = 'plane'; ?>
  • 133. prev
    • Rewind the internal array pointer
    • mixed prev ( array &$array )
    • Returns the array value in the previous place that's pointed to by the internal array pointer, or FALSE if there are no more elements.
    <?php $transport = array('foot', 'bike', 'car', 'plane'); $mode = current($transport); // $mode = 'foot'; $mode = next($transport);    // $mode = 'bike'; $mode = next($transport);    // $mode = 'car'; $mode = prev($transport);    // $mode = 'bike'; $mode = end($transport);    // $mode = 'plane'; ?>
  • 134. 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. This pair is returned in a four-element array, with the keys 0, 1, key, and value. Elements 0 and key contain the key name of the array element, and 1 and value contain the data.
    • If the internal pointer for the array points past the end of the array contents, each() returns FALSE.
  • 135. each <?php $foo = array(&quot;bob&quot;, &quot;fred&quot;, &quot;jussi&quot;, &quot;jouni&quot;, &quot;egon&quot;, &quot;marliese&quot;); $bar = each($foo); print_r($bar); ?> $bar now contains the following key/value pairs: Array ( [1] => bob [value] => bob [0] => 0 [key] => 0 ) <?php $foo = array(&quot;Robert&quot; => &quot;Bob&quot;, &quot;Seppo&quot; => &quot;Sepi&quot;); $bar = each($foo); print_r($bar); ?> $bar now contains the following key/value pairs: Array ( [1] => Bob [value] => Bob [0] => Robert [key] => Robert )
  • 136. 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, and returns its value.
    <?php $fruits = array('apple', 'banana', 'cranberry'); echo end($fruits); // cranberry ?>
  • 137. 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, or FALSE if the array is empty.
  • 138. reset <?php $array = array('step one', 'step two', 'step three', 'step four'); // by default, the pointer is on the first element echo current($array) . &quot;<br /> &quot;; // &quot;step one&quot; // skip two steps next($array); next($array); echo current($array) . &quot;<br /> &quot;; // &quot;step three&quot; // reset pointer, start again on step one reset($array); echo current($array) . &quot;<br /> &quot;; // &quot;step one&quot; ?>
  • 139. range
    • Create an array containing a range of elements
    • array range ( mixed $low, mixed $high [, number $step] )
    • range() returns an array of elements from low to high, inclusive. If low > high, the sequence will be from high to low.
    • New parameter: The optional step parameter was added in 5.0.0.
    • If a step value is given, it will be used as the increment between elements in the sequence. step should be given as a positive number. If not specified, step will default to 1.
  • 140. range // array('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i'); foreach (range('a', 'i') as $letter) {    echo $letter; } // array('c', 'b', 'a'); foreach (range('c', 'a') as $letter) {    echo $letter; } ?> ?php // array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12) foreach (range(0, 12) as $number) {    echo $number; } // The step parameter was introduced in 5.0.0 // array(0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100) foreach (range(0, 100, 10) as $number) {    echo $number; }
  • 141. in_array()
    • Checks if a value exists in an array
    • bool in_array ( mixed $needle, array $haystack [, bool $strict] )
    • Searches haystack for needle and returns TRUE if it is found in the array, FALSE otherwise.
    • 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.
    • Note: If needle is a string, the comparison is done in a case-sensitive manner.
    • Note: In PHP versions before 4.2.0 needle was not allowed to be an array.
  • 142. in_array <?php $os = array(&quot;Mac&quot;, &quot;NT&quot;, &quot;Irix&quot;, &quot;Linux&quot;); if (in_array(&quot;Irix&quot;, $os)) {    echo &quot;Got Irix&quot;; } if (in_array(&quot;mac&quot;, $os)) {    echo &quot;Got mac&quot;; } ?> The second condition fails because in_array() is case-sensitive, so the program above will display: Got Irix
  • 143. extract
    • Import variables into the current symbol table from an array
    • nt extract ( array $var_array [, int $extract_type [, string $prefix]] )
    • This function is used to import variables from an array into the current symbol table. It takes an associative array var_array and treats keys as variable names and values as variable values. For each key/value pair it will create a variable in the current symbol table, subject to extract_type and prefix parameters.
  • 144. array_count_values
    • Counts all the values of an array
      • array array_count_values ( array $input )
        • array_count_values() returns an array using the values of the input array as keys and their frequency in input as values.
    <?php $array = array(1, &quot;hello&quot;, 1, &quot;world&quot;, &quot;hello&quot;); print_r(array_count_values($array)); ?> The above example will output: Array ( [1] => 2 [hello] => 2 [world] => 1 )
  • 145. 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.
    <?php $a = array(2, 4, 6, 8); echo &quot;sum(a) = &quot; . array_sum($a) . &quot; &quot;; $b = array(&quot;a&quot; => 1.2, &quot;b&quot; => 2.3, &quot;c&quot; => 3.4); echo &quot;sum(b) = &quot; . array_sum($b) . &quot; &quot;; ?> The above example will output: sum(a) = 20 sum(b) = 6.9
  • 146. array_values
    • Return all the values of an array
    • array array_values ( array $input )
    • array_values() returns all the values from the input array and indexes numerically the array.
    <?php $array = array(&quot;size&quot; => &quot;XL&quot;, &quot;color&quot; => &quot;gold&quot;); print_r(array_values($array)); ?> The above example will output: Array (    [0] => XL    [1] => gold )
  • 147. array_pad
    • Pad array to the specified length with a value.
    • array array_pad ( array $input, int $pad_size, mixed $pad_value )
    • array_pad() returns a copy of the input padded to size specified by pad_size with value pad_value. If pad_size is positive then the array is padded on the right, if it's negative then on the left. If the absolute value of pad_size is less than or equal to the length of the input then no padding takes place. It is possible to add most 1048576 elements at a time.
    <?php $input = array(12, 10, 9); $result = array_pad($input, 5, 0); // result is array(12, 10, 9, 0, 0) $result = array_pad($input, -7, -1); // result is array(-1, -1, -1, -1, 12, 10, 9) $result = array_pad($input, 2, &quot;noop&quot;); // not padded ?> www.intellibitz.com [email_address]
  • 148. array_pop
    • Pop the element off the end of array
    • mixed array_pop ( array &$array )
    • array_pop() pops and returns the last value of the array, shortening the array by one element. If array is empty (or is not an array), NULL will be returned.
    <?php $stack = array(&quot;orange&quot;, &quot;banana&quot;, &quot;apple&quot;, &quot;raspberry&quot;); $fruit = array_pop($stack); print_r($stack); ?> After this, $stack will have only 3 elements: Array (    [0] => orange    [1] => banana    [2] => apple ) and raspberry will be assigned to $fruit.
  • 149. array_push
    • Push one or more elements onto the end of array
    • int array_push ( array &$array, mixed $var [, mixed $...] )
    • array_push() treats array as a stack, and pushes the passed variables onto the end of array. The length of array increases by the number of variables pushed.
    <?php $stack = array(&quot;orange&quot;, &quot;banana&quot;); array_push($stack, &quot;apple&quot;, &quot;raspberry&quot;); print_r($stack); ?> The above example will output: Array (    [0] => orange    [1] => banana    [2] => apple    [3] => raspberry )
  • 150. array_push
    • array_push has the same effect as:
    • <?php
    • $array[] = $var;
    • ?>
    • repeated for each var.
    • Returns the new number of elements in the array. array_push() will raise a warning if the first argument is not an array. This differs from the $var[] behaviour where a new array is created.
  • 151. compact
    • Create array containing variables and their values
    • array compact ( mixed $varname [, mixed $...] )
    • compact() takes a variable number of parameters. Each parameter can be either a string containing the name of the variable, or an array of variable names. The array can contain other arrays of variable names inside it; compact() handles it recursively.
    • For each of these, 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, it does the opposite of extract(). It returns the output array with all the variables added to it.
    • Any strings that are not set will simply be skipped.
  • 152. 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.
    <?php $a = array(2, 4, 6, 8); echo &quot;product(a) = &quot; . array_product($a) . &quot; &quot;; ?> The above example will output: product(a) = 384
  • 153. array_rand
    • Pick one or more random entries out of an array
    • mixed array_rand ( array $input [, int $num_req] )
    • array_rand() is rather useful when you want to pick one or more random entries out of an array. It takes an input array and an optional argument num_req which specifies how many entries you want to pick - if not specified, it defaults to 1.
    • If you are picking only one entry, array_rand() returns the key for a random entry. Otherwise, it returns an array of keys for the random entries. This is done so that you can pick random keys as well as values out of the array.
    <?php $input = array(&quot;Neo&quot;, &quot;Morpheus&quot;, &quot;Trinity&quot;, &quot;Cypher&quot;, &quot;Tank&quot;); $rand_keys = array_rand($input, 2); echo $input[$rand_keys[0]] . &quot; &quot;; echo $input[$rand_keys[1]] . &quot; &quot;; ?>
  • 154. array_walk
    • Apply a user function to every member of an array
    • bool array_walk ( array &$array, callback $funcname [, mixed $userdata] )
    • Returns TRUE on success or FALSE on failure.
    • Applies the user-defined function funcname to each element of the array array. Typically, funcname takes on two parameters. The array parameter's value being the first, and the key/index second. If the optional userdata parameter is supplied, it will be passed as the third parameter to the callback funcname.
  • 155. array_walk <?php $fruits = array(&quot;d&quot; => &quot;lemon&quot;, &quot;a&quot; => &quot;orange&quot;, &quot;b&quot; => &quot;banana&quot;, &quot;c&quot; => &quot;apple&quot;); function test_alter(&$item1, $key, $prefix) {    $item1 = &quot;$prefix: $item1&quot;; } function test_print($item2, $key) {    echo &quot;$key. $item2<br /> &quot;; } This example will output: Before ...: d. lemon a. orange b. banana c. apple ... and after: d. fruit: lemon a. fruit: orange b. fruit: banana c. fruit: apple echo &quot;Before ...: &quot;; array_walk($fruits, 'test_print'); array_walk($fruits, 'test_alter', 'fruit'); echo &quot;... and after: &quot;; array_walk($fruits, 'test_print'); ?>
  • 156. 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.
    • Note that keys are preserved. array_unique() sorts the values treated as string at first, then will keep the first key encountered for every value, and ignore all following keys. It does not mean that the key of the first related value from the unsorted array will be kept.
    • Note: Two elements are considered equal if and only if (string) $elem1 === (string) $elem2. In words: when the string representation is the same.
    • The first element will be used.
  • 157. array_unique <?php $input = array(&quot;a&quot; => &quot;green&quot;, &quot;red&quot;, &quot;b&quot; => &quot;green&quot;, &quot;blue&quot;, &quot;red&quot;); $result = array_unique($input); print_r($result); ?> The above example will output: Array (    [a] => green    [0] => red    [1] => blue ) <?php $input = array(4, &quot;4&quot;, &quot;3&quot;, 4, 3, &quot;3&quot;); $result = array_unique($input); var_dump($result); ?> The above example will output: array(2) {   [0] => int(4)   [2] => string(1) &quot;3&quot; }
  • 158. array_map
    • Applies the callback to the elements of the given arrays
    • array array_map ( callback $callback, array $arr1 [, array $...] )
    • array_map() returns an array containing all the elements of arr1 after applying the callback function to each one. The number of parameters that the callback function accepts should match the number of arrays passed to the array_map()
    ?php function cube($n) {    return($n * $n * $n); } $a = array(1, 2, 3, 4, 5); $b = array_map(&quot;cube&quot;, $a); print_r($b); ?> This makes $b have: Array ( [0] => 1 [1] => 8 [2] => 27 [3] => 64 [4] => 125 )
  • 159. array_reduce
    • Iteratively reduce the array to a single value using a callback function
    • mixed array_reduce ( array $input, callback $function [, int $initial] )
    <?php function rsum($v, $w) {    $v += $w;    return $v; } $a = array(1, 2, 3, 4, 5); $x = array(); $b = array_reduce($a, &quot;rsum&quot;); $c = array_reduce($a, &quot;rmul&quot;, 10); $d = array_reduce($x, &quot;rsum&quot;, 1); ?> This will result in $b containing 15, $c containing 1200 (= 10*1*2*3*4*5), and $d containing 1. function rmul($v, $w) {    $v *= $w;    return $v; }
  • 160. array_reduce
    • array_reduce() applies iteratively the function function to the elements of the array input, so as to reduce the array to a single value.
    • If the optional initial is available, it will be used at the beginning of the process, or as a final result in case the array is empty.
    • If the array is empty and initial is not passed, array_reduce() returns NULL.
  • 161. array_reverse
    • Return an array with elements in reverse order
    • array array_reverse ( array $array [, bool $preserve_keys] )
    • array_reverse() takes input array and returns a new array with the order of the elements reversed, preserving the keys if preserve_keys is TRUE.
  • 162. array_reverse <?php $input  = array(&quot;php&quot;, 4.0, array(&quot;green&quot;, &quot;red&quot;)); $result = array_reverse($input); $result_keyed = array_reverse($input, true); ?> Array (    [2] => Array        (            [0] => green            [1] => red        )    [1] => 4    [0] => php ) Array (    [0] => Array        (            [0] => green            [1] => red        )    [1] => 4    [2] => php ) $result will be $result_keyed will be: This makes both $result and $result_keyed have the same elements, but note the difference between the keys.
  • 163. array_search
    • Searches the array for a given value and returns the corresponding key if successful mixed array_search ( mixed $needle, array $haystack [, bool $strict] )
    • Searches haystack for needle and returns the key if it is found in the array, FALSE otherwise.
    • If needle is a string, the comparison is done in a case-sensitive manner.
    • Prior to PHP 4.2.0, array_search() returns NULL on failure instead of FALSE.
    • 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.
    <?php $array = array(0 => 'blue', 1 => 'red', 2 => 'green', 3 => 'red'); $key = array_search('green', $array); // $key = 2; $key = array_search('red', $array);  // $key = 1; ?>
  • 164. 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, shortening the array by one element and moving everything down.
    • All numerical array keys will be modified to start counting from zero while literal keys won't be touched. If array is empty (or is not an array), NULL will be returned.
    • This function will reset() the array pointer after use.
  • 165. array_shift <?php $stack = array(&quot;orange&quot;, &quot;banana&quot;, &quot;apple&quot;, &quot;raspberry&quot;); $fruit = array_shift($stack); print_r($stack); ?> This would result in $stack having 3 elements left: Array (    [0] => banana    [1] => apple    [2] => raspberry ) and orange will be assigned to $fruit.
  • 166. array_unshift
    • Prepend one or more elements to the beginning of an array
    • int array_unshift ( array &$array, mixed $var [, mixed $...] )
    • array_unshift() prepends passed elements to the front of the array. Note that the list of elements is prepended as a whole, so that the prepended elements stay in the same order. All numerical array keys will be modified to start counting from zero while literal keys won't be touched.
    • Returns the new number of elements in the array
    <?php $queue = array(&quot;orange&quot;, &quot;banana&quot;); array_unshift($queue, &quot;apple&quot;, &quot;raspberry&quot;); print_r($queue); ?> The above example will output: Array (    [0] => apple    [1] => raspberry    [2] => orange    [3] => banana )
  • 167. array_slice
    • Extract a slice of the array
    • rray array_slice ( array $array, int $offset [, int $length [, bool $preserve_keys]] )
    • array_slice() returns the sequence of elements from the array array as specified by the offset and length parameters.
  • 168. array_slice
    • if offset is non-negative, the sequence will start at that offset in the array. If offset is negative, the sequence will start that far from the end of the array.
    • If length is given and is positive, then the sequence will have that many elements in it. If length is given and is negative then the sequence will stop that many elements from the end of the array. If it is omitted, then the sequence will have everything from offset up until the end of the array.
  • 169. array_slice <?php $input = array(&quot;a&quot;, &quot;b&quot;, &quot;c&quot;, &quot;d&quot;, &quot;e&quot;); $output = array_slice($input, 2);      // returns &quot;c&quot;, &quot;d&quot;, and &quot;e&quot; $output = array_slice($input, -2, 1);  // returns &quot;d&quot; $output = array_slice($input, 0, 3);  // returns &quot;a&quot;, &quot;b&quot;, and &quot;c&quot; // note the differences in the array keys print_r(array_slice($input, 2, -1)); print_r(array_slice($input, 2, -1, true)); Array ( [0] => c [1] => d ) Array ( [2] => c [3] => d )
  • 170. array_splice
    • Remove a portion of the array and replace it with something else
    • array array_splice ( array &$input, int $offset [, int $length [, array $replacement]] )
    <?php $input = array(&quot;red&quot;, &quot;green&quot;, &quot;blue&quot;, &quot;yellow&quot;); array_splice($input, 2); // $input is now array(&quot;red&quot;, &quot;green&quot;) $input = array(&quot;red&quot;, &quot;green&quot;, &quot;blue&quot;, &quot;yellow&quot;); array_splice($input, 1, -1); // $input is now array(&quot;red&quot;, &quot;yellow&quot;)
  • 171. 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.
    • If length is omitted, removes everything from offset to the end of the array. If length is specified and is positive, then that many elements will be removed. 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. Tip: to remove everything from offset to the end of the array when replacement is also specified, use count($input) for length.
    • If replacement array is specified, then the removed elements are replaced with elements from this array. If offset and length are such that nothing is removed, then the elements from the replacement array are inserted in the place specified by the offset. Note that keys in replacement array are not preserved. If replacement is just one element it is not necessary to put array() around it, unless the element is an array itself.
  • 172. array_merge
    • array array_merge ( array $array1 [, array $array2 [, array $...]] )
    • array_merge() merges the elements of one or more arrays together so that the values of one are appended to the end of the previous one. It returns the resulting array.
    • If the input arrays have the same string keys, then the later value for that key will overwrite the previous one. If, however, the arrays contain numeric keys, the later value will not overwrite the original value, but will be appended.
    <?php $array1 = array( &quot;color&quot; => &quot;red&quot;, 2, 4); $array2 = array( &quot;a&quot;, &quot;b&quot;, &quot;color&quot; => &quot;green&quot;, &quot;shape&quot; => &quot;trapezoid&quot;,4); $result = array_merge($array1, $array2); print_r($result); ?> This example will output: Array (    [color] => green    [0] => 2    [1] => 4    [2] => a    [3] => b    [shape] => trapezoid    [4] => 4 )
  • 173. array_merge_recursive
    • If the input arrays have the same string keys, then the values for these keys are merged together into an array, and this is done recursively, so that if one of the values is an array itself, the function will merge it with a corresponding entry in another array too.
    <?php $ar1 = array(&quot;color&quot; => array(&quot;favorite&quot; => &quot;red&quot;), 5); $ar2 = array(10, &quot;color&quot; => array(&quot;favorite&quot; => &quot;green&quot;, &quot;blue&quot;)); $result = array_merge_recursive($ar1, $ar2); print_r($result); ?> Array (    [color] => Array        (            [favorite] => Array                (                    [0] => red                    [1] => green                )            [0] => blue )   [0] => 5    [1] => 10 )
  • 174. array_key
    • Return all the keys of an array
    • array array_keys ( array $input [, mixed $search_value [, bool $strict]] )
    • array_keys() returns the keys, numeric and string, from the input array.
    • If the optional search_value is specified, then only the keys for that value are returned. Otherwise, all the keys from the input are returned. As of PHP 5, you can use strict parameter for comparison including type (===).
  • 175. array_key <?php $array = array(0 => 100, &quot;color&quot; => &quot;red&quot;); print_r(array_keys($array)); $array = array(&quot;blue&quot;, &quot;red&quot;, &quot;green&quot;, &quot;blue&quot;, &quot;blue&quot;); print_r(array_keys($array, &quot;blue&quot;)); $array = array(&quot;color&quot; => array(&quot;blue&quot;, &quot;red&quot;, &quot;green&quot;),                &quot;size&quot;  => array(&quot;small&quot;, &quot;medium&quot;, &quot;large&quot;)); print_r(array_keys($array)); ?> The above example will output: Array ( [0] => 0 [1] => color ) Array ( [0] => 0 [1] => 3 [2] => 4 ) Array ( [0] => color [1] => size )
  • 176. array_key_exists
    • Checks if the given key or index exists in the array
    • bool array_key_exists ( mixed $key, array $search )
    • array_key_exists() returns TRUE if the given key is set in the array. key can be any value possible for an array index. array_key_exists() also works on objects. The name of this function is key_exists() in PHP 4.0.6.
    <?php $search_array = array('first' => 1, 'second' => 4); if (array_key_exists('first', $search_array)) {    echo &quot;The 'first' element is in the array&quot;; } ?> <?php $search_array = array('first' => null, 'second' => 4); // returns false isset($search_array['first']); // returns true array_key_exists('first', $search_array); ?>
  • 177. array_fill
    • Fill an array with values
      • array array_fill ( int $start_index, int $num, mixed $value )
      • array_fill() fills an array with num entries of the value of the value parameter, keys starting at the start_index parameter. Note that num must be a number greater than zero, or PHP will throw a warning.
    ?php $a = array_fill(5, 6, 'banana'); print_r($a); ?> $a now is: Array ( [5] => banana [6] => banana [7] => banana [8] => banana [9] => banana [10] => banana )
  • 178. array_fill_keys
    • Fill an array with values, specifying keys
    • array array_fill_keys ( array $keys, mixed $value )
    • array_fill_keys() fills an array with the value of the value parameter, using the values of the keys array as keys.
    <?php $keys = array('foo', 5, 10, 'bar'); $a = array_fill_keys($keys, 'banana'); print_r($a); ?> $a now is: Array ( [foo] => banana [5] => banana [10] => banana [bar] => banana )
  • 179. array_flip
    • Exchanges all keys with their associated values in an array
    • array array_flip ( array $trans )
    • array_flip() returns an array in flip order, i.e. keys from trans become values and values from trans become keys.
    • Note that the values of trans need to be valid keys, i.e. they need to be either integer or string. A warning will be emitted if a value has the wrong type, and the key/value pair in question will not be flipped.
    • If a value has several occurrences, the latest key will be used as its values, and all others will be lost.
    • array_flip() returns FALSE if it fails.
    <?php $trans = array(&quot;a&quot; => 1, &quot;b&quot; => 1, &quot;c&quot; => 2); $trans = array_flip($trans); print_r($trans); ?> now $trans is: Array ( [1] => b [2] => c )
  • 180. array_intersect
    • Computes the intersection of arrays
    • array array_intersect ( array $array1, array $array2 [, array $ ...] )
    • array_intersect() returns an array containing all the values of array1 that are present in all the arguments. Note that keys are preserved.
      • Two elements are considered equal if and only if (string) $elem1 === (string) $elem2. In words: when the string representation is the same.
    <?php $array1 = array(&quot;a&quot; => &quot;green&quot;, &quot;red&quot;, &quot;blue&quot;); $array2 = array(&quot;b&quot; => &quot;green&quot;, &quot;yellow&quot;, &quot;red&quot;); $result = array_intersect($array1, $array2); print_r($result); ?> The above example will output: Array (    [a] => green    [0] => red )
  • 181. array_intersect_key
    • Computes the intersection of arrays using keys for comparison
      • array array_intersect_key ( array $array1, array $array2 [, array $ ...] )
      • array_intersect_key() returns an array containing all the values of array1 which have matching keys that are present in all the arguments.
  • 182. array_intersect_key
    • In our example you see that only the keys 'blue' and 'green' are present in both arrays and thus returned. Also notice that the values for the keys 'blue' and 'green' differ between the two arrays. A match still occurs because only the keys are checked. The values returned are those of array1.
    • The two keys from the key => value pairs are considered equal only if (string) $key1 === (string) $key2 . In other words a strict type check is executed so the string representation must be the same.
    <?php $array1 = array('blue'  => 1, 'red'  => 2, 'green'  => 3, 'purple' => 4); $array2 = array('green' => 5, 'blue' => 6, 'yellow' => 7, 'cyan'  => 8); var_dump(array_intersect_key($array1, $array2)); ?> The above example will output: array(2) { [&quot;blue&quot;]=> int(1) [&quot;green&quot;]=> int(3) }
  • 183. array_intersect_uassoc
    • Computes the intersection of arrays with additional index check, compares indexes by a callback function
      • array array_intersect_uassoc ( array $array1, array $array2 [, array $ ..., callback $key_compare_func] )
      • array_intersect_uassoc() returns an array containing all the values of array1 that are present in all the arguments. Note that the keys are used in the comparison unlike in array_intersect().
      • The index comparison is done by a user supplied callback function. It must return an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second.
    <?php $array1 = array(&quot;a&quot; => &quot;green&quot;, &quot;b&quot; => &quot;brown&quot;, &quot;c&quot; => &quot;blue&quot;, &quot;red&quot;); $array2 = array(&quot;a&quot; => &quot;GREEN&quot;, &quot;B&quot; => &quot;brown&quot;, &quot;yellow&quot;, &quot;red&quot;); print_r(array_intersect_uassoc($array1, $array2, &quot;strcasecmp&quot;)); ?> The above example will output: Array ( [b] => brown )
  • 184. array_intersect_assoc
    • Computes the intersection of arrays with additional index check
    • array array_intersect_assoc ( array $array1, array $array2 [, array $ ...] )
    • array_intersect_assoc() returns an array containing all the values of array1 that are present in all the arguments. Note that the keys are used in the comparison unlike in array_intersect().
    <?php $array1 = array(&quot;a&quot; => &quot;green&quot;, &quot;b&quot; => &quot;brown&quot;, &quot;c&quot; => &quot;blue&quot;, &quot;red&quot;); $array2 = array(&quot;a&quot; => &quot;green&quot;, &quot;yellow&quot;, &quot;red&quot;); $result_array = array_intersect_assoc($array1, $array2); print_r($result_array); ?> The above example will output: Array ( [a] => green )
  • 185. array_intersect_assoc
    • In our example you see that only the pair &quot;a&quot; => &quot;green&quot; is present in both arrays and thus is returned. The value &quot;red&quot; is not returned because in $array1 its key is 0 while the key of &quot;red&quot; in $array2 is 1.
    • The two values from the key => value pairs are considered equal only if (string) $elem1 === (string) $elem2 . In other words a strict type check is executed so the string representation must be the same.
  • 186. array_intersect_ukey
    • Computes the intersection of arrays using a callback function on the keys for comparison
    • array array_intersect_ukey ( array $array1, array $array2 [, array $..., 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.
    • This comparison is done by a user supplied callback function. It must return an integer less than, equal to, or greater than zero if the first key is considered to be respectively less than, equal to, or greater than the second.
  • 187. array_intersect_ukey <?php function key_compare_func($key1, $key2) {    if ($key1 == $key2)        return 0;    else if ($key1 > $key2)        return 1;    else        return -1; } The above example will output: array(2) { [&quot;blue&quot;]=> int(1) [&quot;green&quot;]=> int(3) } $array1 = array('blue'  => 1, 'red'  => 2, 'green'  => 3, 'purple' => 4); $array2 = array('green' => 5, 'blue' => 6, 'yellow' => 7, 'cyan'  => 8); var_dump(array_intersect_ukey($array1, $array2, 'key_compare_func')); ?>
  • 188. array_uintersect
    • Computes the intersection of arrays, compares data by a callback function
    • array array_uintersect ( array $array1, array $array2 [, array $ ..., callback $data_compare_func] )
    • array_uintersect() returns an array containing all the values of array1 that are present in all the arguments. The data is compared by using a callback function.
    <?php $array1 = array(&quot;a&quot; => &quot;green&quot;, &quot;b&quot; => &quot;brown&quot;, &quot;c&quot; => &quot;blue&quot;, &quot;red&quot;); $array2 = array(&quot;a&quot; => &quot;GREEN&quot;, &quot;B&quot; => &quot;brown&quot;, &quot;yellow&quot;, &quot;red&quot;); print_r(array_uintersect($array1, $array2, &quot;strcasecmp&quot;)); ?> The above example will output: Array ( [a] => green [b] => brown [0] => red )
  • 189. array_uintersect_assoc
    • Computes the intersection of arrays with additional index check, compares data by a callback function
    • rray array_uintersect_assoc ( array $array1, array $array2 [, array $ ..., callback $data_compare_func] )
    • array_uintersect_assoc() returns an array containing all the values of array1 that are present in all the arguments.
    <?php $array1 = array(&quot;a&quot; => &quot;green&quot;, &quot;b&quot; => &quot;brown&quot;, &quot;c&quot; => &quot;blue&quot;, &quot;red&quot;); $array2 = array(&quot;a&quot; => &quot;GREEN&quot;, &quot;B&quot; => &quot;brown&quot;, &quot;yellow&quot;, &quot;red&quot;); print_r(array_uintersect_assoc($array1, $array2, &quot;strcasecmp&quot;)); ?> The above example will output: Array ( [a] => green )
  • 190. array_uintersect_uassoc
    • Computes the intersection of arrays with additional index check, compares data and indexes by a callback functions
    • array array_uintersect_uassoc ( array $array1, array $array2 [, array $ ..., callback $data_compare_func, callback $key_compare_func] )
    • array_uintersect_uassoc() returns an array containing all the values of array1 that are present in all the arguments. Note that the keys are used in the comparison unlike in array_uintersect().
    <?php $array1 = array(&quot;a&quot; => &quot;green&quot;, &quot;b&quot; => &quot;brown&quot;, &quot;c&quot; => &quot;blue&quot;, &quot;red&quot;); $array2 = array(&quot;a&quot; => &quot;GREEN&quot;, &quot;B&quot; => &quot;brown&quot;, &quot;yellow&quot;, &quot;red&quot;); print_r(array_uintersect_uassoc($array1, $array2, &quot;strcasecmp&quot;, &quot;strcasecmp&quot;)); ?> The above example will output: Array ( [a] => green [b] => brown )
  • 191. array_diff
    • Computes the difference of arrays
      • array array_diff ( array $array1, array $array2 [, array $ ...] )
      • array_diff() returns an array containing all the values of array1 that are not present in any of the other arguments. Note that keys are preserved.
    <?php $array1 = array(&quot;a&quot; => &quot;green&quot;, &quot;red&quot;, &quot;blue&quot;, &quot;red&quot;); $array2 = array(&quot;b&quot; => &quot;green&quot;, &quot;yellow&quot;, &quot;red&quot;); $result = array_diff($array1, $array2); print_r($result); ?> This will output : Array ( [1] => blue )
  • 192. array_diff_key
    • Computes the difference of arrays using keys for comparison
      • array array_diff_key ( array $array1, array $array2 [, array $ ...] )
        • 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. Note that the associativity is preserved. This function is like array_diff() except the comparison is done on the keys instead of the values.
          • The two keys from the key => value pairs are considered equal only if (string) $key1 === (string) $key2 . In other words a strict type check is executed so the string representation must be the same.
    <?php $array1 = array('blue'  => 1, 'red'  => 2, 'green'  => 3, 'purple' => 4); $array2 = array('green' => 5, 'blue' => 6, 'yellow' => 7, 'cyan'  => 8); var_dump(array_diff_key($array1, $array2)); ?> This example will output array(2) { [&quot;red&quot;]=> int(2) [&quot;purple&quot;]=> int(4) }
  • 193. array_diff_assoc
    • Computes the difference of arrays with additional index check
      • array array_diff_assoc ( array $array1, array $array2 [, array $ ...] )
      • array_diff_assoc() returns an array containing all the values from array1 that are not present in any of the other arguments.
      • Note that the keys are used in the comparison unlike array_diff().
    <?php $array1 = array(&quot;a&quot; => &quot;green&quot;, &quot;b&quot; => &quot;brown&quot;, &quot;c&quot; => &quot;blue&quot;, &quot;red&quot;); $array2 = array(&quot;a&quot; => &quot;green&quot;, &quot;yellow&quot;, &quot;red&quot;); $result = array_diff_assoc($array1, $array2); print_r($result); ?> This example will output: Array ( [b] => brown [c] => blue [0] => red )
  • 194. array_udiff
    • Computes the difference of arrays by using a callback function for data comparison
    • array array_udiff ( array $array1, array $array2 [, array $ ..., 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. Note that keys are preserved.
  • 195. 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 array1 that are not present in any of the other arguments.
    <?php function key_compare_func($a, $b) {    if ($a === $b) {        return 0;    }    return ($a > $b)? 1:-1; } $array1 = array(&quot;a&quot; => &quot;green&quot;, &quot;b&quot; => &quot;brown&quot;, &quot;c&quot; => &quot;blue&quot;, &quot;red&quot;); $array2 = array(&quot;a&quot; => &quot;green&quot;, &quot;yellow&quot;, &quot;red&quot;); $result = array_diff_uassoc($array1, $array2, &quot;key_compare_func&quot;); print_r($result); ?> The above example will output: Array ( [b] => brown [c] => blue [0] => red )
  • 196. array_diff_uassoc
    • Note that the keys are used in the comparison unlike array_diff().
      • This comparison is done by a user supplied callback function. It must return an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second.
      • This is unlike array_diff_assoc() where an internal function for comparing the indices is used.
  • 197. array_diff_ukey
    • Computes the difference of arrays using a callback function on the keys for comparison
      • array array_diff_ukey ( array $array1, array $array2 [, array $ ..., 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. Note that the associativity is preserved. This function is like array_diff() except the comparison is done on the keys instead of the values.
        • This comparison is done by a user supplied callback function. It must return an integer less than, equal to, or greater than zero if the first key is considered to be respectively less than, equal to, or greater than the second.
  • 198. array_diff_ukey <?php function key_compare_func($key1, $key2) {    if ($key1 == $key2)        return 0;    else if ($key1 > $key2)        return 1;    else        return -1; } $array1 = array('blue'  => 1, 'red'  => 2, 'green'  => 3, 'purple' => 4); $array2 = array('green' => 5, 'blue' => 6, 'yellow' => 7, 'cyan'  => 8); var_dump(array_diff_ukey($array1, $array2, 'key_compare_func')); ?> The above example will output: array(2) { [&quot;red&quot;]=> int(2) [&quot;purple&quot;]=> int(4) }
  • 199. array_udiff_assoc
    • Computes the difference of arrays with additional index check, compares data by a callback function
    • array array_udiff_assoc ( array $array1, array $array2 [, array $ ..., 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.
    • Note that the keys are used in the comparison unlike array_diff() and array_udiff(). The comparison of arrays' data is performed by using an user-supplied callback.
    • In this aspect the behaviour is opposite to the behaviour of array_diff_assoc() which uses internal function for comparison.
  • 200. array_udiff_uassoc
    • Computes the difference of arrays with additional index check, compares data and indexes by a callback function
    • array array_udiff_uassoc ( array $array1, array $array2 [, array $ ..., callback $data_compare_func, 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. Note that the keys are used in the comparison unlike array_diff() and array_udiff().
  • 201. 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
  • 202. 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
  • 203. 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()
  • 204. 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
  • 205. 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
  • 206. 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
  • 207. 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()
  • 208. 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
  • 209. CHAPTER 5 FUNCTIONS
  • 210. Functions
    • Declaring and Calling Functions
    • Passing Arguments to Functions
    • Returning Values from Functions
    • Understanding Variable Scope
  • 211. 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
  • 212. 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
  • 213. 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, and not variables
  • 214. 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
  • 215. Returning values from Functions
    • Functions can also compute a value, 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, use an array as return value
    • A test expression can consist just a function call with no comparison or other operator
  • 216. 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, but local variables of a function are not accessible outside that function
  • 217. 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, called an auto-global
    • The auto-globals are always arrays that are automatically populated with data
  • 218. 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
  • 219. CHAPTER 6 HTML AN INTRODUCTION TO WEB FORMS
  • 220. 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
  • 221. 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.
    • Fire fox, Internet Explorer,Netscafe, opera are few well known web browsers.
  • 222. Viewing outputs in browsers
    • To view the output, correct path of the html file has to be typed into the address box of the web browser .
    • The web browser has to be refreshed to view the changes made in the html file
  • 223. HTML Tags
    • The tags in HTML are enclosed by angle brackets(<,>).
    • Html tags normally come in pair s like <b></b>.
    • Html tags are not case sensitive ,<b>means the same as <B>.
    • <html> </html> are the starting and ending tags.
  • 224. Head
    • Html files has two major parts,head and body.
    • <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.
  • 225. 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. Use <del> instead
    • <u> Deprecated. Use styles instead
  • 226. BODY
    • <BODY> encloses the content that has to be displayed in the browser.
    • <p> tag encloses the paragraph.
  • 227. Attribute
    • Attributes provide additional information to an HTML element.
    • Attributes always come in name/value pairs like this: name=&quot;value&quot;.
    • Attributes are always specified in the start tag of an HTML element.
  • 228. Attribute
    • The following tag defines an HTML table: <table>. With an added border attribute, you can tell the browser that the table should have no borders: <table border=&quot;0&quot;>
    • Attribute values should always be enclosed in quotes. Double style quotes are the most common, but single style quotes are also allowed.
  • 229. Attribute
    • In some rare situations, like when the attribute value itself contains quotes, it is necessary to use single quotes:
      • name='John &quot;ShotGun&quot; Nelson'
  • 230. Headings
    • Headings are defined with the <h1> to <h6> tags. <h1> defines the largest heading. <h6> defines the smallest heading.
    • Paragraphs are defined with the <p> tag.
    • HTML automatically adds an extra blank line before and after a headings and paragraph.
  • 231. Line break
    • The <br> tag is used when you want to end a line, but don't want to start a new paragraph. The <br> tag forces a line break wherever you place it.
    • The <br> tag is an empty tag. It has no closing tag.
  • 232. Comments
    • The comment tag is used to insert a comment in the HTML source code. A comment will be ignored by the browser. 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, but not before the closing bracket.
  • 233. Formatting
    • HTML defines a lot of elements for formatting output, like bold or italic text.
    • <b> Defines bold text
    • <big> Defines big text
    • <em> Defines emphasized text
    • <i> Defines italic text
    • <small> Defines small text
  • 234. 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. Use <pre> instead
    • <plaintext> Deprecated. Use <pre> instead
    • <xmp> Deprecated. Use <pre> instead
  • 235. 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
  • 236. Html entities
    • Some characters like the < character, have a special meaning in HTML, and therefore cannot be used in the text.
    • To display a less than sign (<) in HTML, we have to use a character entity.
  • 237. Html entities
    • A character entity has three parts: an ampersand (&), an entity name or a # and an entity number, and finally a semicolon (;).
      • To display a less than sign in an HTML document we must write: &lt; or &#60;
  • 238. Html entities
    • Normally HTML will truncate spaces in your text. If you write 10 spaces in your text HTML will remove 9 of them.
    • To add spaces(non breaking space) to your text, use the &nbsp; character entity.
  • 239. Html entities
    • non-breaking space &nbsp; &#160;
    • < less than &lt; &#60;
    • > greater than &gt; &#62;
    • & ampersand &amp; &#38;
    • &quot; quotation mark &quot; &#34;
    • ' apostrophe &apos; &#39;
  • 240. Html entities
    • ¢ cent &cent; &#162;
    • £ pound &pound; &#163;
    • ¥ yen &yen; &#165;
    • § section &sect; &#167;
    • © copyright &copy; &#169;
    • ® registered trademark &reg; &#174;
    • × multiplication &times; &#215;
    • ÷ division &divide; &#247;
  • 241. Links
    • HTML uses a hyperlink to link to another document on the Web.
    • The <a> tag is used to create an anchor to link from, the href attribute is used to address the document to link to, and the words between the open and close of the anchor tag will be displayed as a hyperlink.
  • 242. Link
    • With the target attribute, you can define where the linked document will be opened.
    • <a href=&quot;http://www.IntelliBitz.com/&quot;
    • target=&quot;_blank&quot;>Visit IntelliBitz!</a>
  • 243. Link
    • The name attribute is used to create a named anchor.
    • When using named anchors we can create links that can jump directly into a specific section on a page, instead of letting the user scroll around to find what he/she is looking for.
  • 244. Frames
    • With frames, you can display more than one Web page in the same browser window.
    • The disadvantages of using frames are:
      • The web developer must keep track of more HTML documents
      • It is difficult to print the entire page
  • 245. 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
  • 246. Frames
    • The <frame> tag defines what HTML document to put into each frame
    <frameset cols=&quot;25%,75%&quot;>    <frame src=&quot;frame_a.htm&quot;>    <frame src=&quot;frame_b.htm&quot;> </frameset>
  • 247. Frames
    • if you add a <noframes> tag containing some text for browsers that do not support frames, you will have to enclose the text in <body></body> tags!
  • 248. Tables
    • Tables are defined with the <table> tag.
    • A table is divided into rows (with the <tr> tag)
    • Each row is divided into data cells (with the <td> tag).
    • A data cell can contain text, images, lists, paragraphs, forms, horizontal rules, tables, etc.
  • 249. Tables <table border=&quot;1&quot;> <tr> <td>row 1, cell 1</td> <td>row 1, cell 2</td> </tr> <tr> <td>row 2, cell 1</td> <td>row 2, cell 2</td> </tr> </table> <table border=&quot;1&quot;> <tr> <th>Heading</th> <th>Another Heading</th> </tr> <tr> <td>row 1, cell 1</td> <td>row 1, cell 2</td> </tr> <tr> <td>row 2, cell 1</td> <td>row 2, cell 2</td> </tr> </table>
  • 250. List
    • An unordered list is a list of items. The list items are marked with bullets (typically small black circles).
    • An ordered list is also a list of items. The list items are marked with numbers.
    • A definition list is not a list of items. This is a list of terms and explanation of the terms.
  • 251. List <ul> <li>Coffee</li> <li>Milk</li> </ul> <ol> <li>Coffee</li> <li>Milk</li> </ol> <dl> <dt>Coffee</dt> <dd>Black hot drink</dd> <dt>Milk</dt> <dd>White cold drink</dd> </dl>
  • 252. Image
    • With HTML you can display images in a document.
    • The src attribute of img tag should be assigned with the path of the file.
    • Img tag has no closing tag.
    <img src=&quot;boat.gif&quot; alt=&quot;Big Boat&quot;>
  • 253. Image
    • The &quot;alt&quot; attribute tells the reader what he or she is missing on a page if the browser can't load images.
    • The browser will then display the alternate text instead of the image.
    • It is a good practice to include the &quot;alt&quot; attribute for each image on a page, to improve the display
  • 254. Background
    • The <body> tag has two attributes where you can specify backgrounds.
      • The bgcolor attribute specifies a background-color for an HTML page.
      • The background attribute specifies a background-image for an HTML page.
    • The background can be a color or an image.
  • 255. <div> <span>
    • A <div> is a block value element ,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.
  • 256. Web form
    • Web form are used to get data from the user.
    • Form elements are elements that allow the user to enter information (like text fields, textarea fields, drop-down menus, radio buttons, checkboxes, etc.) in a form.
    www.intellibitz.com [email_address]
  • 257. <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).
    www.intellibitz.com [email_address]
  • 258. Text box
    • Text box is a single line text field.
    • <input type = “text”> tag can be used to define a textbox
    • Attributes
      • Name
        • The name assigned to the textbox.this will be the key to $_POST[ ] .
      • Size
        • The size of the text fields in browser in character.
  • 259. Textbox
      • Maxlength
        • The maximum number of character to accept in the textfields.
      • Value
        • The default value of the textbox.
        • This value will be displayed inside the textbox on the browser.
    www.intellibitz.com [email_address]
  • 260. Password fields
    • Password field masks the input so that it cannot be read on the screen.
    • The attributes of password field are same as text field.
    www.intellibitz.com [email_address]
  • 261. 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,the name attribute of option button must have the same value.
    www.intellibitz.com [email_address]
  • 262. 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 .
    www.intellibitz.com [email_address]
  • 263. Check box
    • The check box allows the user to select the any number of the provided option.
    • 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.intellibitz.com [email_address]
  • 264. Lists and drop-down lists
    • Lists
      • A list can be in a standard scrollable box where one or more items can be selected.
    • Drop-down lists
      • A list can be displayed as single line and user clicks the arrow button to see all the choices
    www.intellibitz.com [email_address]
  • 265. Lists and drop-down lists
    • A <select> tag defines a list.
    • Attributes
      • Name
        • The name given to the list.
      • Size
        • The number of items to display at once in the lists (a value of one indicates a dropdown lists).
      • Multiple
        • A flag indicating whether multiple items can be selected
  • 266. Lists and drop-down lists
    • <option> tag is used to represent items in the lists
    • Attributes
      • Value
        • The value to submit if selected.
      • Selected
        • A flag indicating if this item is selected by default.
  • 267. Lists and drop-down lists
  • 268. 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.
  • 269. Image
    • <input type = “image”> is identical to <input type = “submit”>except thet instead of displaying a button it displays a specific image.
  • 270. Hidden
    • Along with user editable data,HTML also allows to send uneditable hidden data to the server.
  • 271. 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
  • 272. 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.
        • It will run past the edge of the text field.
        • Text will be sent exactly as typed.
  • 273. 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.
  • 274. 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.
    • Attributes
      • Name
        • Name of the file field
      • Size
        • Size of the file field (in characters)
      • Maxlength
        • Maximum length of the text field
  • 275. Summary
    • HTML is the universal markup language for the Web.
    • HTML lets you format text, add graphics, create links, input forms, frames and tables, etc., and save it all in a text file that any browser can read and display.
    • The key to HTML is the tags, which indicates what content is coming up.
  • 276. CHAPTER 7 PHP AND WEB FORMS
  • 277. 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
  • 278. Making Web Forms
    • Forms are how users communicate with your web server.
    • $_GET and $_POST auto global array
    • $_SERVER holds request and server information.
    • Beware of submitted form parameter, can contain embedded HTML or JavaScript.
  • 279. 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
  • 280. Validating Data
    • Use regular expressions to match text patterns.
    • Take advantage of the fact that an empty array evaluates to false.
    • Use strlen() when checking a required. element instead of testing the value itself in an if() statement.
    • Use intval() and floatval() to ensure number.
  • 281. Validating Form Data
    • Use trim() when validating string elements.
    • Beware of making changes to $_POST auto-global inside your validation functions.
    • Use arrays for display and validation of <select> menus.
  • 282. HTML and JavaScript
    • Beware of cross-site scripting attack
    • To prevent cross-site scripting attacks, never display unmodified external input.
    • Use strip_tags() and htmlentities().
    • Always use htmlentities() to sanitize external input use strip_tags() only when you are absolutely sure.
  • 283. Displaying Default Values
    • Use default values to display prepopulated form.
    • 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.
  • 284. Putting It All Together
    • Displaying a form, including default values
    • Validating the submitted data.
    • Redisplaying, the form with error messages and preserved user input if the submitted data isn't valid.
    • Processing the submitted data if it is valid.
  • 285. Chapter Summary
    • Understanding the conversation between the web browser and web server that displays a form, 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
  • 286. 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(), validate_form(), and process_form() functions for form handling
  • 287. 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, integers, floating-point numbers, strings, date ranges, email addresses, and <select> menus
  • 288. Chapter Summary
    • Removing submitted HTML and JavaScript before displaying it.
    • Displaying default values for form elements.
    • Using helper functions to display form elements.
  • 289. CHAPTER 8 PHP AND DATABASE
  • 290. 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
  • 291. 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
  • 292. Organizing Data in a Database
    • Information in your database is organized in tables, which have rows and columns
    • Tables are like Spreadsheet, 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, UPDATE, DELETE, SELECT
  • 293. Connecting to a Database
    • Use require 'DB.php';
    • 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 ');
    • DB::isError () checks if object contains error information
  • 294. Creating a Table
    • CREATE TABLE dishes (
    • dish_id INT,
    • dish_name VARCHAR(255),
    • price DECIMAL(4,2),
    • is_spicy INT
    • )
    • DROP TABLE dishes
  • 295. Putting Data into Database
    • Pass an INSERT statement to the object's query() function
    • $q = $db->query(“INSERT here...”);
    • Use setErrorHandling() to have your program automatically print an error message and exit if a query fails
  • 296. 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
  • 297. Generating Unique IDs
    • To identify individual database records, 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
  • 298. Retrieving Data from Database
    • Use fetchRow() to get the next row returned from the query, when no rows left, 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
  • 299. 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, mysqli extension can be used
    • $db = mysqli_connect ('db.intellibitz.com', 'user', 'pass', 'schema');
  • 300. 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
  • 301. 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
  • 302. 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()
  • 303. Chapter Summary
    • Counting the number of rows retrieved by query()
    • Retrieving data with getAll(), getRow(), and getOne()
    • Using the SQL ORDER BY and LIMIT keywords with SELECT
    • Retrieving rows as string-keyed arrays or objects
  • 304. 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
  • 305. CHAPTER 9 PHP AND MySQL FUNCTIONS
  • 306. mysql_query
    • Send a MySQL query
    • resource mysql_query ( string $query [, 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.
  • 307. mysql_query
    • Parameters
      • query
        • A SQL query
        • The query string should not end with a semicolon.
      • link_identifier
        • The MySQL connection. If the link identifier is not specified, the last link opened by mysql_connect() is assumed. If no such link is found, it will try to create one as if mysql_connect() was called with no arguments. If by chance no connection is found or established, an E_WARNING level warning is generated.
  • 308. mysql_query
    • Return Values
    • For SELECT, SHOW, DESCRIBE or EXPLAIN statements, mysql_query() returns a resource on success, or FALSE on error.
    • For other type of SQL statements, UPDATE, DELETE, DROP, etc, mysql_query() returns TRUE on success or FALSE on error.
    • The returned result resource should be passed to mysql_fetch_array(), and other functions for dealing with result tables, to access the returned data.
    • 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, INSERT, REPLACE, or UPDATE statement.
    • mysql_query() will also fail and return FALSE if the user does not have permission to access the table(s) referenced by the query.
  • 309. mysql_result
    • Get result data
    • string mysql_result ( resource $result, int $row [, mixed $field] )
    • Retrieves the contents of one cell from a MySQL result set.
    • When working on large result sets, you should consider using one of the functions that fetch an entire row (specified below). As these functions return the contents of multiple cells in one function call, they're MUCH quicker than mysql_result(). Also, note that specifying a numeric offset for the field argument is much quicker than specifying a fieldname or tablename.fieldname argument.
  • 310. mysql_result
    • Parameters
      • result
        • The result resource that is being evaluated. This result comes from a call to mysql_query().
      • row
        • The row number from the result that's being retrieved. Row numbers start at 0.
      • field
        • The name or offset of the field being retrieved.
        • It can be the field's offset, the field's name, or the field's table dot field name (tablename.fieldname). If the column name has been aliased ('select foo as bar from...'), use the alias instead of the column name. If undefined, the first field is retrieved.
  • 311. mysql_result
    • Return Values
    • The contents of one cell from a MySQL result set on success, or FALSE on failure.
    <?php $link = mysql_connect('localhost', 'mysql_user', 'mysql_password'); if (!$link) {    die('Could not connect: ' . mysql_error()); } $result = mysql_query('SELECT name FROM work.employee'); if (!$result) {    die('Could not query:' . mysql_error()); } echo mysql_result($result, 2); // outputs third employee's name mysql_close($link); ?>
  • 312. mysql_selest_db
    • Select a MySQL database
    • bool mysql_select_db ( string $database_name [, resource $link_identifier] )
    • Sets the current active database on the server that's associated with the specified link identifier. Every subsequent call to mysql_query() will be made on the active database.
  • 313. mysql_select_db
    • Parameters
      • database_name
        • The name of the database that is to be selected.
      • link_identifier
        • The MySQL connection. If the link identifier is not specified, the last link opened by mysql_connect() is assumed. If no such link is found, it will try to create one as if mysql_connect() was called with no arguments. If by chance no connection is found or established, an E_WARNING level warning is generated.
  • 314. mysql_select_db
    • Return Values
    • Returns TRUE on success or FALSE on failure.
    <?php $link = mysql_connect('localhost', 'mysql_user', 'mysql_password'); if (!$link) {    die('Not connected : ' . mysql_error()); } // make foo the current db $db_selected = mysql_select_db('foo', $link); if (!$db_selected) {    die ('Can't use foo : ' . mysql_error()); } ?>
  • 315. 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, UPDATE, REPLACE or DELETE query associated with link_identifier.
  • 316. mysql_affected_rows
    • Parameters
    • link_identifier
      • The MySQL connection. If the link identifier is not specified, the last link opened by mysql_connect() is assumed. If no such link is found, it will try to create one as if mysql_connect() was called with no arguments. If by chance no connection is found or established, an E_WARNING level warning is generated.
  • 317. mysql_affected_rows
    • Return Values
    • Returns the number of affected rows on success, and -1 if the last query failed.
    • If the last query was a DELETE query with no WHERE clause, all of the records will have been deleted from the table but this function will return zero with MySQL versions prior to 4.1.2.
    • When using UPDATE, MySQL will not update columns where the new value is the same as the old value. This creates the possibility that mysql_affected_rows() may not actually equal the number of rows matched, only the number of rows that were literally affected by the query.
    • The REPLACE statement first deletes the record with the same primary key and then inserts the new record. This function returns the number of deleted records plus the number of inserted records.
  • 318. mysql_affected_row <?php $link = mysql_connect('localhost', 'mysql_user', 'mysql_password'); if (!$link) {    die('Could not connect: ' . mysql_error()); } mysql_select_db('mydb'); /* this should return the correct numbers of deleted records */ mysql_query('DELETE FROM mytable WHERE id < 10'); printf(&quot;Records deleted: %d &quot;, mysql_affected_rows()); /* with a where clause that is never true, it should return 0 */ mysql_query('DELETE FROM mytable WHERE 0'); printf(&quot;Records deleted: %d &quot;, mysql_affected_rows()); ?> The above example will output something similar to: Records deleted: 10 Records deleted: 0
  • 319. mysql_affected_rows <?php $link = mysql_connect('localhost', 'mysql_user', 'mysql_password'); if (!$link) {    die('Could not connect: ' . mysql_error()); } mysql_select_db('mydb'); /* Update records */ mysql_query(&quot;UPDATE mytable SET used=1 WHERE id < 10&quot;); printf (&quot;Updated records: %d &quot;, mysql_affected_rows()); mysql_query(&quot;COMMIT&quot;); ?> The above example will output something similar to: Updated Records: 10
  • 320. mysql_change_user
    • mysql_change_user — Change logged in user of the active connection
    • int mysql_change_user ( string $user, string $password [, string $database [, resource $link_identifier]] )
    • mysql_change_user() changes the logged in user of the current active connection, or the connection given by the optional link_identifier parameter. If a database is specified, this will be the current database after the user has been changed. If the new user and password authorization fails, the current connected user stays active.
    • This function is deprecated and no longer exists in PHP.
  • 321. mysql_change_user
    • Parameters
    • user
    • The new MySQL username.
      • password
    • The new MySQL password.
      • database
    • The MySQL database. If not specified, the current selected database is used.
      • link_identifier
    • The MySQL connection. If the link identifier is not specified, the last link opened by mysql_connect() is assumed. If no such link is found, it will try to create one as if mysql_connect() was called with no arguments. If by chance no connection is found or established, an E_WARNING level warning is generated.
    • Return Values
      • Returns TRUE on success or FALSE on failure.
  • 322. 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.
    • Parameters
      • link_identifier
        • The MySQL connection. If the link identifier is not specified, the last link opened by mysql_connect() is assumed. If no such link is found, it will try to create one as if mysql_connect() was called with no arguments. If by chance no connection is found or established, an E_WARNING level warning is generated.
  • 323. mysql_client_encoding <?php $link = mysql_connect('localhost', 'mysql_user', 'mysql_password'); $charset = mysql_client_encoding($link); echo &quot;The current character set is: $charset &quot;; ?> The above example will output something similar to: The current character set is: latin1
  • 324. 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. If link_identifier isn't specified, the last opened link is used.
    • Using mysql_close() isn't usually necessary, as non-persistent open links are automatically closed at the end of the script's execution. See also freeing resources.
    • Parameters
      • link_identifier
        • The MySQL connection. If the link identifier is not specified, the last link opened by mysql_connect() is assumed. If no such link is found, it will try to create one as if mysql_connect() was called with no arguments. If by chance no connection is found or established, an E_WARNING level warning is generated.
    • Return Values
        • Returns TRUE on success or FALSE on failure.
  • 325. mysql_close <?php $link = mysql_connect('localhost', 'mysql_user', 'mysql_password'); if (!$link) { die('Could not connect: ' . mysql_error()); } echo 'Connected successfully'; mysql_close($link); ?> The above example will output: Connected successfully
  • 326. mysql_connect
    • mysql_connect — Open a connection to a MySQL Server
    • resource mysql_connect ( [string $server [, string $username [, string $password [, bool $new_link [, int $client_flags]]]]] )
    • Opens or reuses a connection to a MySQL server.
  • 327. mysql_connect
    • Parameters
      • server
        • The MySQL server. It can also include a port number. e.g. &quot;hostname:port&quot; or a path to a local socket e.g. &quot;:/path/to/socket&quot; for the localhost.
        • If the PHP directive mysql.default_host is undefined (default), then the default value is 'localhost:3306'. In SQL safe mode, this parameter is ignored and value 'localhost:3306' is always used.
      • username
        • The username. Default value is defined by mysql.default_user. In SQL safe mode, this parameter is ignored and the name of the user that owns the server process is used.
  • 328. mysql_connect
    • password
        • The password. Default value is defined by mysql.default_password. In SQL safe mode, this parameter is ignored and empty password is used.
      • new_link
        • If a second call is made to mysql_connect() with the same arguments, no new link will be established, but instead, the link identifier of the already opened link will be returned. The new_link parameter modifies this behavior and makes mysql_connect() always open a new link, even if mysql_connect() was called before with the same parameters. In SQL safe mode, this parameter is ignored.
  • 329. mysql_connect
    • client_flags
        • The client_flags parameter can be a combination of the following constants: MYSQL_CLIENT_SSL, MYSQL_CLIENT_COMPRESS, MYSQL_CLIENT_IGNORE_SPACE or MYSQL_CLIENT_INTERACTIVE. Read the section about Table 173, “MySQL client constants” for further information. In SQL safe mode, this parameter is ignored.
      • Return Values
        • Returns a MySQL link identifier on success, or FALSE on failure.
  • 330. mysql_connect <?php // we connect to example.com and port 3307 $link = mysql_connect('example.com:3307', 'mysql_user', 'mysql_password'); if (!$link) { die('Could not connect: ' . mysql_error()); } echo 'Connected successfully'; mysql_close($link); // we connect to localhost at port 3307 $link = mysql_connect('127.0.0.1:3307', 'mysql_user', 'mysql_password'); if (!$link) { die('Could not connect: ' . mysql_error()); }echo 'Connected successfully'; mysql_close($link); ?>
  • 331. mysql_connect
    • Parameters
      • database_name
        • The name of the database being created.
      • link_identifier
        • The MySQL connection. If the link identifier is not specified, the last link opened by mysql_connect() is assumed. If no such link is found, it will try to create one as if mysql_connect() was called with no arguments. If by chance no connection is found or established, an E_WARNING level warning is generated.
    • Return Values
      • Returns TRUE on success or FALSE on failure.
  • 332. mysql_create_db
    • Create a MySQL database
    • bool mysql_create_db ( string $database_name [, resource $link_identifier] )
    • mysql_create_db() attempts to create a new database on the server associated with the specified link identifier.
  • 333. mysql_create_db <?php $link = mysql_connect('localhost', 'mysql_user', 'mysql_password'); if (!$link) {    die('Could not connect: ' . mysql_error()); } $sql = 'CREATE DATABASE my_db'; if (mysql_query($sql, $link)) {    echo &quot;Database my_db created successfully &quot;; } else {    echo 'Error creating database: ' . mysql_error() . &quot; &quot;; } ?> The above example will output something similar to: Database my_db created successfully
  • 334. mysql_data_seek
    • Move internal result pointer
    • bool mysql_data_seek ( resource $result, 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. The next call to a MySQL fetch function, such as mysql_fetch_assoc(), would return that row.
    • row_number starts at 0. The row_number should be a value in the range from 0 to mysql_num_rows() - 1. However if the result set is empty (mysql_num_rows() == 0), a seek to 0 will fail with a E_WARNING and mysql_data_seek() will return FALSE.
  • 335. mysql_data_seek
    • Parameters
      • result
        • The result resource that is being evaluated. This result comes from a call to mysql_query().
      • row_number
        • The desired row number of the new result pointer.
    • Return Values
      • Returns TRUE on success or FALSE on failure.
  • 336. mysql_db_name
    • Get result data
    • Description
    • string mysql_db_name ( resource $result, int $row [, mixed $field] )
    • Retrieve the database name from a call to mysql_list_dbs().
  • 337. mysql_db_name
    • Parameters
      • result
        • The result pointer from a call to mysql_list_dbs().
      • row
        • The index into the result set.
      • field
        • The field name.
      • Return Values
        • Returns the database name on success, and FALSE on failure. If FALSE is returned, use mysql_error() to determine the nature of the error.
  • 338. mysql_db_name <?php error_reporting(E_ALL); $link = mysql_connect('dbhost', 'username', 'password'); $db_list = mysql_list_dbs($link); $i = 0; $cnt = mysql_num_rows($db_list); while ($i < $cnt) {    echo mysql_db_name($db_list, $i) . &quot; &quot;;    $i++; } ?>
  • 339. mysql_db_query
    • Send a MySQL query
    • resource mysql_db_query ( string $database, string $query [, resource $link_identifier] )
    • mysql_db_query() selects a database, and executes a query on it.
    • Parameters
      • database
        • The name of the database that will be selected.
      • query
    • The MySQL query.
      • link_identifier
        • The MySQL connection. If the link identifier is not specified, the last link opened by mysql_connect() is assumed. If no such link is found, it will try to create one as if mysql_connect() was called with no arguments. If by chance no connection is found or established, an E_WARNING level warning is generated.
    • Return Values
        • Returns a positive MySQL result resource to the query result, or FALSE on error. The function also returns TRUE/FALSE for INSERT/UPDATE/DELETE queries to indicate success/failure.
  • 340. mysql_db_query <?php if (!$link = mysql_connect('mysql_host', 'mysql_user', 'mysql_password')) {    echo 'Could not connect to mysql';    exit; } if (!mysql_select_db('mysql_dbname', $link)) {    echo 'Could not select database';    exit; } $sql    = 'SELECT foo FROM bar WHERE id = 42'; $result = mysql_query($sql, $link); if (!$result) {    echo &quot;DB Error, could not query the database &quot;;    echo 'MySQL Error: ' . mysql_error();    exit; } while ($row = mysql_fetch_assoc($result)) {    echo $row['foo']; } mysql_free_result($result); ?>
  • 341. mysql_drop_db
    • Drop (delete) a MySQL database
    • bool mysql_drop_db ( string $database_name [, resource $link_identifier] )
    • mysql_drop_db() attempts to drop (remove) an entire database from the server associated with the specified link identifier. This function is deprecated, it is preferable to use mysql_query() to issue a sql DROP DATABASE statement instead.
  • 342. mysql_drop_db
    • Parameters
      • database_name
        • The name of the database that will be deleted.
      • link_identifier
        • The MySQL connection. If the link identifier is not specified, the last link opened by mysql_connect() is assumed. If no such link is found, it will try to create one as if mysql_connect() was called with no arguments. If by chance no connection is found or established, an E_WARNING level warning is generated.
      • Return Values
        • Returns TRUE on success or FALSE on failure.
  • 343. mysql_drop_db mysql_drop_db() alternative example <?php $link = mysql_connect('localhost', 'mysql_user', 'mysql_password'); if (!$link) {    die('Could not connect: ' . mysql_error()); } $sql = 'DROP DATABASE my_db'; if (mysql_query($sql, $link)) {    echo &quot;Database my_db was successfully dropped &quot;; } else {    echo 'Error dropping database: ' . mysql_error() . &quot; &quot;; } ?>
  • 344. 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.
    • Errors coming back from the MySQL database backend no longer issue warnings. Instead, use mysql_errno() to retrieve the error code. Note that this function only returns the error code from the most recently executed MySQL function (not including mysql_error() and mysql_errno()), so if you want to use it, make sure you check the value before calling another MySQL function.
  • 345. mysql_errno <?php $link = mysql_connect(&quot;localhost&quot;, &quot;mysql_user&quot;, &quot;mysql_password&quot;); if (!mysql_select_db(&quot;nonexistentdb&quot;, $link)) {    echo mysql_errno($link) . &quot;: &quot; . mysql_error($link). &quot; &quot;; } mysql_select_db(&quot;kossu&quot;, $link); if (!mysql_query(&quot;SELECT * FROM nonexistenttable&quot;, $link)) {    echo mysql_errno($link) . &quot;: &quot; . mysql_error($link) . &quot; &quot;; } ?> The above example will output something similar to: 1049: Unknown database 'nonexistentdb' 1146: Table 'kossu.nonexistenttable' doesn't exist
  • 346. 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. Errors coming back from the MySQL database backend no longer issue warnings. Instead, use mysql_error() to retrieve the error text. 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, make sure you check the value before calling another MySQL function.
  • 347. mysql_error
    • Parameters
    • link_identifier
      • The MySQL connection. If the link identifier is not specified, the last link opened by mysql_connect() is assumed. If no such link is found, it will try to create one as if mysql_connect() was called with no arguments. If by chance no connection is found or established, an E_WARNING level warning is generated.
    • Return Values
      • Returns the error text from the last MySQL function, or '' (empty string) if no error occurred.
  • 348. mysql_error <?php $link = mysql_connect(&quot;localhost&quot;, &quot;mysql_user&quot;, &quot;mysql_password&quot;); mysql_select_db(&quot;nonexistentdb&quot;, $link); echo mysql_errno($link) . &quot;: &quot; . mysql_error($link). &quot; &quot;; mysql_select_db(&quot;kossu&quot;, $link); mysql_query(&quot;SELECT * FROM nonexistenttable&quot;, $link); echo mysql_errno($link) . &quot;: &quot; . mysql_error($link) . &quot; &quot;; ?> The above example will output something similar to: 1049: Unknown database 'nonexistentdb' 1146: Table 'kossu.nonexistenttable' doesn't exist
  • 349. 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, so that it is safe to place it in a mysql_query(). This function is deprecated.
    • 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. mysql_escape_string() does not take a connection argument and does not respect the current charset setting.
  • 350. mysql_escape_string
    • Parameters
      • unescaped_string
        • The string that is to be escaped.
    • Return Values
      • Returns the escaped string.
    <?php $item = &quot;Zak's Laptop&quot;; $escaped_item = mysql_escape_string($item); printf(&quot;Escaped string: %s &quot;, $escaped_item); ?> The above example will output: Escaped string: Zak's Laptop
  • 351. mysql_fetch_array
    • Fetch a result row as an associative array, a numeric array, or both
    • array mysql_fetch_array ( resource $result [, int $result_type] )
    • Returns an array that corresponds to the fetched row and moves the internal data pointer ahead.
    • Parameters
    • result
    • The result resource that is being evaluated. This result comes from a call to mysql_query().
    • result_type
    • The type of array that is to be fetched. It's a constant and can take the following values: MYSQL_ASSOC, MYSQL_NUM, and the default value of MYSQL_BOTH.
  • 352. mysql_fetch_array
    • Return Values
    • Returns an array that corresponds to the fetched row, or FALSE if there are no more rows. The type of returned array depends on how result_type is defined. By using MYSQL_BOTH (default), you'll get an array with both associative and number indices. Using MYSQL_ASSOC, you only get associative indices (as mysql_fetch_assoc() works), using MYSQL_NUM, you only get number indices (as mysql_fetch_row() works).
    • If two or more columns of the result have the same field names, the last column will take precedence. To access the other column(s) of the same name, you must use the numeric index of the column or make an alias for the column. For aliased columns, you cannot access the contents with the original column name.
  • 353. mysql_fetch_array <?php mysql_connect(&quot;localhost&quot;, &quot;mysql_user&quot;, &quot;mysql_password&quot;) or    die(&quot;Could not connect: &quot; . mysql_error()); mysql_select_db(&quot;mydb&quot;); $result = mysql_query(&quot;SELECT id, name FROM mytable&quot;); while ($row = mysql_fetch_array($result, MYSQL_NUM)) {    printf(&quot;ID: %s  Name: %s&quot;, $row[0], $row[1]);  } mysql_free_result($result); ?>
  • 354. 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.
  • 355. mysql_fetch_assoc
    • Parameters
      • result
        • The result resource that is being evaluated. This result comes from a call to mysql_query().
      • Return Values
        • Returns an associative array that corresponds to the fetched row, or FALSE if there are no more rows.
        • If two or more columns of the result have the same field names, the last column will take precedence. To access the other column(s) of the same name, you either need to access the result with numeric indices by using mysql_fetch_row() or add alias names. See the example at the mysql_fetch_array() description about aliases.
  • 356. array_fetch_assoc <?php $conn = mysql_connect(&quot;localhost&quot;, &quot;mysql_user&quot;, &quot;mysql_password&quot;); if (!$conn) {    echo &quot;Unable to connect to DB: &quot; . mysql_error();    exit; }   if (!mysql_select_db(&quot;mydbname&quot;)) {    echo &quot;Unable to select mydbname: &quot; . mysql_error();    exit; } $sql = &quot;SELECT id as userid, fullname, userstatus        FROM  sometable        WHERE  userstatus = 1&quot;; $result = mysql_query($sql); if (!$result) {    echo &quot;Could not successfully run query ($sql) from DB: &quot; . mysql_error();    exit; } if (mysql_num_rows($result) == 0) {    echo &quot;No rows found, nothing to print so am exiting&quot;;    exit; }
  • 357. mysql_fetch_field
    • Get column information from a result and return as an object
    • object mysql_fetch_field ( resource $result [, int $field_offset] )
    • Returns an object containing field information. This function can be used to obtain information about fields in the provided query result.
    • Parameters
      • result
        • The result resource that is being evaluated. This result comes from a call to mysql_query().
      • field_offset
        • The numerical field offset. If the field offset is not specified, the next field that was not yet retrieved by this function is retrieved. The field_offset starts at 0.
  • 358. mysql_fetch_fields
    • Return Values
    • Returns an object containing field information. 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
      • * unsigned - 1 if the column is unsigned
      • * zerofill - 1 if the column is zero-filled
  • 359. mysql_fetch_fields $i = 0; while ($i < mysql_num_fields($result)) {    echo &quot;Information for column $i:<br /> &quot;;    $meta = mysql_fetch_field($result, $i);    if (!$meta) {        echo &quot;No information available<br /> &quot;;    }    echo &quot;<pre> blob:        $meta->blob max_length:  $meta->max_length multiple_key: $meta->multiple_key name:        $meta->name table:        $meta->table type:        $meta->type default:      $meta->def unique_key:  $meta->unique_key unsigned:    $meta->unsigned zerofill:    $meta->zerofill </pre>&quot;;    $i++; } not_null:    $meta->not_null numeric:      $meta->numeric primary_key:  $meta->primary_key
  • 360. 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.
    • mysql_fetch_lengths() stores the lengths of each result column in the last row returned by mysql_fetch_row(), mysql_fetch_assoc(), mysql_fetch_array(), and mysql_fetch_object() in an array, starting at offset 0.
  • 361. mysql_fetch_length
    • Parameters
      • result
        • The result resource that is being evaluated. This result comes from a call to mysql_query().
    • Return Values
      • An array of lengths on success, or FALSE on failure.
    <?php $result = mysql_query(&quot;SELECT id,email FROM people WHERE id = '42'&quot;); if (!$result) {    echo 'Could not run query: ' . mysql_error();    exit; } $row    = mysql_fetch_assoc($result); $lengths = mysql_fetch_lengths($result); print_r($row); print_r($lengths); ?> Array ( [id] => 42 [email] => user@example.com ) Array ( [0] => 2 [1] => 16 )
  • 362. mysql_fetch_object
    • Fetch a result row as an object
    • object mysql_fetch_object ( resource $result [, string $class_name [, array $params]] )
    • Returns an object with properties that correspond to the fetched row and moves the internal data pointer ahead.
  • 363. mysql_fetch_object
    • Parameters
      • Result
        • The result resource that is being evaluated. This result comes from a call to mysql_query().
      • class_name
        • The name of the class to instantiate, set the properties of and return. If not specified, a stdClass object is returned.
      • Params
        • An optional array of parameters to pass to the constructor for class_name objects.
  • 364. mysql_fetch_object
    • Return Values
      • Returns an object with properties that correspond to the fetched row, 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. The row is returned as an array. Each result column is stored in an array offset, starting at offset 0.
  • 365. mysql_fetch_object <?php mysql_connect(&quot;hostname&quot;, &quot;user&quot;, &quot;password&quot;); mysql_select_db(&quot;mydb&quot;); $result = mysql_query(&quot;select * from mytable&quot;); while ($row = mysql_fetch_object($result)) {    echo $row->user_id;    echo $row->fullname; } mysql_free_result($result); ?> <?php $row = mysql_fetch_object($result); /* this is valid */ echo $row->field; /* this is invalid */ // echo $row->0; ?>
  • 366. 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.
    • Parameters
    • result
    • The result resource that is being evaluated. This result comes from a call to mysql_query().
  • 367. mysql_fetch_row
    • Return Values
    • Returns an numerical array that corresponds to the fetched row, 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. The row is returned as an array. Each result column is stored in an array offset, starting at offset 0.
  • 368. mysql_fetch_row <?php $result = mysql_query(&quot;SELECT id,email FROM people WHERE id = '42'&quot;); if (!$result) {    echo 'Could not run query: ' . mysql_error();    exit; } $row = mysql_fetch_row($result); echo $row[0]; // 42 echo $row[1]; // the email value ?>
  • 369. mysql_field_flags
    • Get the flags associated with the specified field in a result
    • string mysql_field_flags ( resource $result, int $field_offset )
    • mysql_field_flags() returns the field flags of the specified field. 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().
  • 370. mysql_field_flags
    • Parameters
      • Result
        • The result resource that is being evaluated. This result comes from a call to mysql_query().
      • field_offset
        • The numerical field offset. The field_offset starts at 0. If field_offset does not exist, an error of level E_WARNING is also issued.
  • 371. mysql_field_flags
    • Return Values
      • Returns a string of flags associated with the result, or FALSE on failure.
      • The following flags are reported, if your version of MySQL is current enough to support them: &quot;not_null&quot;, &quot;primary_key&quot;, &quot;unique_key&quot;, &quot;multiple_key&quot;, &quot;blob&quot;, &quot;unsigned&quot;, &quot;zerofill&quot;, &quot;binary&quot;, &quot;enum&quot;, &quot;auto_increment&quot; and &quot;timestamp&quot;.
  • 372. mysql_field_flags <?php $result = mysql_query(&quot;SELECT id,email FROM people WHERE id = '42'&quot;); if (!$result) {    echo 'Could not run query: ' . mysql_error();    exit; } $flags = mysql_field_flags($result, 0); echo $flags; print_r(explode(' ', $flags)); ?> not_null primary_key auto_increment Array ( [0] => not_null [1] => primary_key [2] => auto_increment )
  • 373. mysql_field_len
    • Returns the length of the specified field
    • int mysql_field_len ( resource $result, int $field_offset )
    • mysql_field_len() returns the length of the specified field.
    • Parameters
      • result
        • The result resource that is being evaluated. This result comes from a call to mysql_query().
      • field_offset
        • The numerical field offset. The field_offset starts at 0. If field_offset does not exist, an error of level E_WARNING is also issued.
    • Return Values
      • The length of the specified field index on success, or FALSE on failure.
  • 374. mysql_field_len <?php $result = mysql_query(&quot;SELECT id,email FROM people WHERE id = '42'&quot;); if (!$result) {    echo 'Could not run query: ' . mysql_error();    exit; } // Will get the length of the id field as specified in the database // schema. $length = mysql_field_len($result, 0); echo $length; ?>
  • 375. mysql_field_len <?php $result = mysql_query(&quot;SELECT id,email FROM people WHERE id = '42'&quot;); if (!$result) {    echo 'Could not run query: ' . mysql_error();    exit; } // Will get the length of the id field as specified in the database // schema. $length = mysql_field_len($result, 0); echo $length; ?>
  • 376. mysql_field_name
    • Get the name of the specified field in a result
    • string mysql_field_name ( resource $result, int $field_offset )
    • mysql_field_name() returns the name of the specified field index.
    • Parameters
      • result
        • The result resource that is being evaluated. This result comes from a call to mysql_query().
      • field_offset
        • The numerical field offset. The field_offset starts at 0. If field_offset does not exist, an error of level E_WARNING is also issued.
    • Return Values
      • The name of the specified field index on success, or FALSE on failure.
  • 377. mysql_field_name <?php /* The users table consists of three fields: *  user_id *  username *  password. */ $link = @mysql_connect('localhost', 'mysql_user', 'mysql_password'); if (!$link) {    die('Could not connect to MySQL server: ' . mysql_error()); } $dbname = 'mydb'; $db_selected = mysql_select_db($dbname, $link); if (!$db_selected) {    die(&quot;Could not set $dbname: &quot; . mysql_error()); } $res = mysql_query('select * from users', $link); echo mysql_field_name($res, 0) . &quot; &quot;; echo mysql_field_name($res, 2); ?> The above example will output: user_id password
  • 378. mysql_field_seek
    • Set result pointer to a specified field offset
    • bool mysql_field_seek ( resource $result, int $field_offset )
    • Seeks to the specified field offset. If the next call to mysql_fetch_field() doesn't include a field offset, the field offset specified in mysql_field_seek() will be returned.
  • 379. mysql_field_seek
    • Parameters
      • result
        • The result resource that is being evaluated. This result comes from a call to mysql_query().
      • field_offset
        • The numerical field offset. The field_offset starts at 0. If field_offset does not exist, an error of level E_WARNING is also issued.
    • Return Values
      • Returns TRUE on success or FALSE on failure.
  • 380. 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.
  • 381. mysql_field_table
    • Parameters
      • result
        • The result resource that is being evaluated. This result comes from a call to mysql_query().
      • field_offset
        • The numerical field offset. The field_offset starts at 0. If field_offset does not exist, an error of level E_WARNING is also issued.
    • Return Values
      • The name of the table on success.
  • 382. mysql_field_table <?php $result = mysql_query(&quot;SELECT name,comment FROM people,comments&quot;); if (!$result) {    echo 'Could not run query: ' . mysql_error();    exit; } // Assuming name is in the people table $table = mysql_field_table($result, 'name'); echo $table; // people ?>
  • 383. mysql_field_type
    • Get the type of the specified field in a result
    • string mysql_field_type ( resource $result, int $field_offset )
    • mysql_field_type() is similar to the mysql_field_name() function. The arguments are identical, but the field type is returned instead.
  • 384. mysql_field_type
    • Parameters
      • result
        • The result resource that is being evaluated. This result comes from a call to mysql_query().
      • field_offset
        • The numerical field offset. The field_offset starts at 0. If field_offset does not exist, an error of level E_WARNING is also issued.
    • Return Values
      • The returned field type will be one of &quot;int&quot;, &quot;real&quot;, &quot;string&quot;, &quot;blob&quot;, and others as detailed in the » MySQL documentation.
  • 385. mysql_field_type <?php mysql_connect(&quot;localhost&quot;, &quot;mysql_username&quot;, &quot;mysql_password&quot;); mysql_select_db(&quot;mysql&quot;); $result = mysql_query(&quot;SELECT * FROM func&quot;); $fields = mysql_num_fields($result); $rows  = mysql_num_rows($result); $table  = mysql_field_table($result, 0); echo &quot;Your '&quot; . $table . &quot;' table has &quot; . $fields . &quot; fields and &quot; . $rows . &quot; record(s) &quot;; echo &quot;The table has the following fields: &quot;; for ($i=0; $i < $fields; $i++) {    $type  = mysql_field_type($result, $i);    $name  = mysql_field_name($result, $i);    $len  = mysql_field_len($result, $i);    $flags = mysql_field_flags($result, $i);    echo $type . &quot; &quot; . $name . &quot; &quot; . $len . &quot; &quot; . $flags . &quot; &quot;; } mysql_free_result($result); mysql_close(); ?>
  • 386. 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
  • 387. 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.
    • 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. All associated result memory is automatically freed at the end of the script's execution.
    • 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.
  • 388. mysql_free_result <?php $result = mysql_query(&quot;SELECT id,email FROM people WHERE id = '42'&quot;); if (!$result) {    echo 'Could not run query: ' . mysql_error();    exit; } /* Use the result, assuming we're done with it afterwords */ $row = mysql_fetch_assoc($result); /* Now we free up the result and continue on with our script */ mysql_free_result($result); echo $row['id']; echo $row['email']; ?>
  • 389. 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.
    • Return Values
    • The MySQL client version.
    <?php printf(&quot;MySQL client info: %s &quot;, mysql_get_client_info()); ?> The above example will output something similar to: MySQL client info: 3.23.39
  • 390. 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.
  • 391. mysql_host_info
    • Parameters
      • link_identifier
        • The MySQL connection. If the link identifier is not specified, the last link opened by mysql_connect() is assumed. If no such link is found, it will try to create one as if mysql_connect() was called with no arguments. If by chance no connection is found or established, an E_WARNING level warning is generated.
    • Return Values
      • Returns a string describing the type of MySQL connection in use for the connection or FALSE on failure.
  • 392. mysql_host_info <?php $link = mysql_connect('localhost', 'mysql_user', 'mysql_password'); if (!$link) {    die('Could not connect: ' . mysql_error()); } printf(&quot;MySQL host info: %s &quot;, mysql_get_host_info()); ?> The above example will output something similar to: MySQL host info: Localhost via UNIX socket
  • 393. mysql_get_proto_info
    • Get MySQL protocol info
    • int mysql_get_proto_info ( [resource $link_identifier] )
    • Retrieves the MySQL protocol.
    • Parameters
      • link_identifier
        • The MySQL connection. If the link identifier is not specified, the last link opened by mysql_connect() is assumed. If no such link is found, it will try to create one as if mysql_connect() was called with no arguments. If by chance no connection is found or established, an E_WARNING level warning is generated.
  • 394. mysql_get_proto_info
    • Return Values
      • Returns the MySQL protocol on success, or FALSE on failure.
    <?php $link = mysql_connect('localhost', 'mysql_user', 'mysql_password'); if (!$link) {    die('Could not connect: ' . mysql_error()); } printf(&quot;MySQL protocol version: %s &quot;, mysql_get_proto_info()); ?> The above example will output something similar to: MySQL protocol version: 10
  • 395. mysql_get_server_info
    • Get MySQL server info
    • string mysql_get_server_info ( [resource $link_identifier] )
    • Retrieves the MySQL server version.
    • Parameters
      • link_identifier
        • The MySQL connection. If the link identifier is not specified, the last link opened by mysql_connect() is assumed. If no such link is found, it will try to create one as if mysql_connect() was called with no arguments. If by chance no connection is found or established, an E_WARNING level warning is generated.
  • 396. mysql_get_server_info
    • Return Values
      • Returns the MySQL server version on success, or FALSE on failure.
    <?php $link = mysql_connect('localhost', 'mysql_user', 'mysql_password'); if (!$link) {    die('Could not connect: ' . mysql_error()); } printf(&quot;MySQL server version: %s &quot;, mysql_get_server_info()); ?> The above example will output something similar to: MySQL server version: 4.0.1-alpha
  • 397. mysql_info
    • Get information about the most recent query
    • string mysql_info ( [resource $link_identifier] )
    • Returns detailed information about the last query.
    • Parameters
      • link_identifier
        • The MySQL connection. If the link identifier is not specified, the last link opened by mysql_connect() is assumed. If no such link is found, it will try to create one as if mysql_connect() was called with no arguments. If by chance no connection is found or established, an E_WARNING level warning is generated.
  • 398. mysql_info
    • Return Values
      • Returns information about the statement on success, or FALSE on failure. See the example below for which statements provide information, and what the returned value may look like. Statements that are not listed will return FALSE.
  • 399. 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.
    • Parameters
      • link_identifier
        • The MySQL connection. If the link identifier is not specified, the last link opened by mysql_connect() is assumed. If no such link is found, it will try to create one as if mysql_connect() was called with no arguments. If by chance no connection is found or established, an E_WARNING level warning is generated.
  • 400. mysql_insert_id
    • Return Values
    • The ID generated for an AUTO_INCREMENT column by the previous INSERT query on success, 0 if the previous query does not generate an AUTO_INCREMENT value, or FALSE if no MySQL connection was established.
  • 401. mysql_insert_id <?php $link = mysql_connect('localhost', 'mysql_user', 'mysql_password'); if (!$link) {    die('Could not connect: ' . mysql_error()); } mysql_select_db('mydb'); mysql_query(&quot;INSERT INTO mytable (product) values ('intelli')&quot;); printf(&quot;Last inserted record has id %d &quot;, mysql_insert_id()); ?>
  • 402. 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.
    • function to traverse this result pointer, or any function for result tables, such as mysql_fetch_array().
  • 403. mysql_list_dbs
    • Parameters
      • link_identifier
        • The MySQL connection. If the link identifier is not specified, the last link opened by mysql_connect() is assumed. If no such link is found, it will try to create one as if mysql_connect() was called with no arguments. If by chance no connection is found or established, an E_WARNING level warning is generated.
    • Return Values
      • Returns a result pointer resource on success, or FALSE on failure.
  • 404. mysql_list_dbs <?php $link = mysql_connect('localhost', 'mysql_user', 'mysql_password'); $db_list = mysql_list_dbs($link); while ($row = mysql_fetch_object($db_list)) {      echo $row->Database . &quot; &quot;; } ?> The above example will output something similar to: database1 database2 database3
  • 405. mysql_list_fields
    • List MySQL table fields
    • resource mysql_list_fields ( string $database_name, string $table_name [, resource $link_identifier] )
    • Retrieves information about the given table name.
    • This function is deprecated. It is preferable to use mysql_query() to issue a SQL SHOW COLUMNS FROM table [LIKE 'name'] statement instead.
  • 406. mysql_list_fields
    • Parameters
      • database_name
        • The name of the database that's being queried.
      • table_name
        • The name of the table that's being queried.
      • link_identifier
      • The MySQL connection. If the link identifier is not specified, the last link opened by mysql_connect() is assumed. If no such link is found, it will try to create one as if mysql_connect() was called with no arguments. If by chance no connection is found or established, an E_WARNING level warning is generated.
    • Return Values
    • A result pointer resource on success, or FALSE on failure.
  • 407. mysql_list_fields Alternate to deprecated mysql_list_fields() <?php $result = mysql_query(&quot;SHOW COLUMNS FROM sometable&quot;); if (!$result) {    echo 'Could not run query: ' . mysql_error();    exit; } if (mysql_num_rows($result) > 0) {    while ($row = mysql_fetch_assoc($result)) {        print_r($row);    } } ?> This example will output something similar to: Array ( [Field] => id [Type] => int(7) [Null] => [Key] => PRI [Default] => [Extra] => auto_increment ) Array ( [Field] => email [Type] => varchar(100) [Null] => [Key] => [Default] => [Extra] => )
  • 408. 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. If the link identifier is not specified, the last link opened by mysql_connect() is assumed. If no such link is found, it will try to create one as if mysql_connect() was called with no arguments. If by chance no connection is found or established, an E_WARNING level warning is generated.
  • 409. mysql_list_processes
    • Return Values
      • A result pointer resource on success, or FALSE on failure.
    <?php $link = mysql_connect('localhost', 'mysql_user', 'mysql_password'); $result = mysql_list_processes($link); while ($row = mysql_fetch_assoc($result)){    printf(&quot;%s %s %s %s %s &quot;, $row[&quot;Id&quot;], $row[&quot;Host&quot;], $row[&quot;db&quot;],        $row[&quot;Command&quot;], $row[&quot;Time&quot;]); } mysql_free_result($result); ?> The above example will output something similar to: 1 localhost test Processlist 0 4 localhost mysql sleep 5
  • 410. mysql_list_tables
    • List tables in a MySQL database
    • resource mysql_list_tables ( string $database [, resource $link_identifier] )
    • Retrieves a list of table names from a MySQL database.
    • This function is deprecated. It is preferable to use mysql_query() to issue a SQL SHOW TABLES [FROM db_name] [LIKE 'pattern'] statement instead.
  • 411. msql_list_tables
    • Parameters
      • database
        • The name of the database
      • link_identifier
        • The MySQL connection. If the link identifier is not specified, the last link opened by mysql_connect() is assumed. If no such link is found, it will try to create one as if mysql_connect() was called with no arguments. If by chance no connection is found or established, an E_WARNING level warning is generated.
    • Return Values
      • A result pointer resource on success, or FALSE on failure.
  • 412. mysql_list_tables mysql_list_tables() alternative example <?php $dbname = 'mysql_dbname'; if (!mysql_connect('mysql_host', 'mysql_user', 'mysql_password')) {    echo 'Could not connect to mysql';    exit; } $sql = &quot;SHOW TABLES FROM $dbname&quot;; $result = mysql_query($sql); if (!$result) {    echo &quot;DB Error, could not list tables &quot;;    echo 'MySQL Error: ' . mysql_error();    exit; } while ($row = mysql_fetch_row($result)) {    echo &quot;Table: {$row[0]} &quot;; } mysql_free_result($result); ?>
  • 413. mysql_num_fields
    • Get number of fields in result
    • int mysql_num_fields ( resource $result )
    • Retrieves the number of fields from a query.
    • Parameters
    • result
    • The result resource that is being evaluated. This result comes from a call to mysql_query().
    • Return Values
    • Returns the number of fields in the result set resource on success, or FALSE on failure.
  • 414. mysql_num_fields <?php $result = mysql_query(&quot;SELECT id,email FROM people WHERE id = '42'&quot;); if (!$result) {    echo 'Could not run query: ' . mysql_error();    exit; } /* returns 2 because id,email === two fields */ echo mysql_num_fields($result); ?>
  • 415. mysql_num_rows
    • Get number of rows in result
    • int mysql_num_rows ( resource $result )
    • Retrieves the number of rows from a result set. 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, REPLACE or DELETE query, use mysql_affected_rows().
  • 416. mysql_num_rows
    • Parameters
      • result
        • The result resource that is being evaluated. This result comes from a call to mysql_query().
    • Return Values
      • The number of rows in a result set on success, or FALSE on failure.
  • 417. mysql_num_rows <?php $link = mysql_connect(&quot;localhost&quot;, &quot;mysql_user&quot;, &quot;mysql_password&quot;); mysql_select_db(&quot;database&quot;, $link); $result = mysql_query(&quot;SELECT * FROM table1&quot;, $link); $num_rows = mysql_num_rows($result); echo &quot;$num_rows Rows &quot;; ?>
  • 418. mysql_pconnect
    • Open a persistent connection to a MySQL server
    • resource mysql_pconnect ( [string $server [, string $username [, string $password [, int $client_flags]]]] )
    • Establishes a persistent connection to a MySQL server.
    • mysql_pconnect() acts very much like mysql_connect() with two major differences.
    • First, when connecting, the function would first try to find a (persistent) link that's already open with the same host, username and password. If one is found, an identifier for it will be returned instead of opening a new connection.
    • Second, the connection to the SQL server will not be closed when the execution of the script ends. Instead, the link will remain open for future use (mysql_close() will not close links established by mysql_pconnect()).
    • This type of link is therefore called 'persistent'.
  • 419. mysql_pconnect
    • Parameters
      • server
        • The MySQL server. It can also include a port number. e.g. &quot;hostname:port&quot; or a path to a local socket e.g. &quot;:/path/to/socket&quot; for the localhost.
        • If the PHP directive mysql.default_host is undefined (default), then the default value is 'localhost:3306'
      • username
        • The username. Default value is the name of the user that owns the server process.
      • password
        • The password. Default value is an empty password.
  • 420. mysql_pconnect
    • client_flags
        • The client_flags parameter can be a combination of the following constants: MYSQL_CLIENT_SSL, MYSQL_CLIENT_COMPRESS, MYSQL_CLIENT_IGNORE_SPACE or MYSQL_CLIENT_INTERACTIVE.
    • Return Values
      • Returns a MySQL persistent link identifier on success, or FALSE on failure.
  • 421. 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. If it has gone down, an automatic reconnection is attempted. This function can be used by scripts that remain idle for a long while, to check whether or not the server has closed the connection and reconnect if necessary.
  • 422. mysql_ping
    • Parameters
      • link_identifier
        • The MySQL connection. If the link identifier is not specified, the last link opened by mysql_connect() is assumed. If no such link is found, it will try to create one as if mysql_connect() was called with no arguments. If by chance no connection is found or established, an E_WARNING level warning is generated.
    • Return Values
    • Returns TRUE if the connection to the server MySQL server is working, otherwise FALSE.
  • 423. mysql_ping <?php set_time_limit(0); $conn = mysql_connect('localhost', 'mysqluser', 'mypass'); $db  = mysql_select_db('mydb'); /* Assuming this query will take a long time */ $result = mysql_query($sql); if (!$result) {    echo 'Query #1 failed, exiting.';    exit; } /* Make sure the connection is still alive, if not, try to reconnect */ if (!mysql_ping($conn)) {    echo 'Lost connection, exiting after query #1';    exit; } mysql_free_result($result); /* So the connection is still alive, let's run another query */ $result2 = mysql_query($sql2); ?>
  • 424. mysql_real_escape_string
    • Escapes special characters in a string for use in a SQL statement
    • string mysql_real_escape_string ( string $unescaped_string [, resource $link_identifier] )
    • Escapes special characters in the unescaped_string, 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, this function must be used.
    • mysql_real_escape_string() calls MySQL's library function mysql_real_escape_string, which prepends backslashes to the following characters: x00, , , , ', &quot; and x1a.
    • This function must always (with few exceptions) be used to make data safe before sending a query to MySQL .
  • 425. mysql_real_escape_string
    • Parameters
      • unescaped_string
        • The string that is to be escaped.
      • link_identifier
      • The MySQL connection. If the link identifier is not specified, the last link opened by mysql_connect() is assumed. If no such link is found, it will try to create one as if mysql_connect() was called with no arguments. If by chance no connection is found or established, an E_WARNING level warning is generated.
    • Return Values
      • Returns the escaped string, or FALSE on error.
  • 426. mysql_real_escape_string <?php // Connect $link = mysql_connect('mysql_host', 'mysql_user', 'mysql_password')    OR die(mysql_error()); // Query $query = sprintf(&quot;SELECT * FROM users WHERE user='%s' AND password='%s'&quot;,            mysql_real_escape_string($user),            mysql_real_escape_string($password)); ?>
  • 427. mysql_stat
    • Get current system status
    • string mysql_stat ( [resource $link_identifier] )
    • mysql_stat() returns the current server status.
  • 428. mysql_stat
    • Parameters
      • link_identifier
        • The MySQL connection. If the link identifier is not specified, the last link opened by mysql_connect() is assumed. If no such link is found, it will try to create one as if mysql_connect() was called with no arguments. If by chance no connection is found or established, an E_WARNING level warning is generated.
  • 429. mysql_stat
    • Return Values
      • Returns a string with the status for uptime, threads, queries, open tables, flush tables and queries per second. For a complete list of other status variables, you have to use the SHOW STATUS SQL command. If link_identifier is invalid, NULL is returned.
    <?php $link  = mysql_connect('localhost', 'mysql_user', 'mysql_password'); $status = explode('  ', mysql_stat($link)); print_r($status); ?> The above example will output something similar to: Array ( [0] => Uptime: 5380 [1] => Threads: 2 [2] => Questions: 1321299 [3] => Slow queries: 0 [4] => Opens: 26 [5] => Flush tables: 1 [6] => Open tables: 17 [7] => Queries per second avg: 245.595 )
  • 430. mysql_tablename
    • Get table name of field
    • string mysql_tablename ( resource $result, int $i )
    • Retrieves the table name from a result.
    • This function deprecated. It is preferable to use mysql_query() to issue a SQL SHOW TABLES [FROM db_name] [LIKE 'pattern'] statement instead.
    • Parameters
      • result
        • A result pointer resource that's returned from mysql_list_tables().
      • i
        • The integer index (row/table number)
  • 431. mysql_tablename
    • Return Values
      • The name of the table on success, or FALSE on failure.
    <?php mysql_connect(&quot;localhost&quot;, &quot;mysql_user&quot;, &quot;mysql_password&quot;); $result = mysql_list_tables(&quot;mydb&quot;); $num_rows = mysql_num_rows($result); for ($i = 0; $i < $num_rows; $i++) {    echo &quot;Table: &quot;, mysql_tablename($result, $i), &quot; &quot;; } mysql_free_result($result); ?>
  • 432. mysql_thread_id
    • Return the current thread ID
    • int mysql_thread_id ( [resource $link_identifier] )
    • Retrieves the current thread ID. If the connection is lost, and a reconnect with mysql_ping() is executed, the thread ID will change. This means only retrieve the thread ID when needed.
  • 433. mysql_thread_id
    • Parameters
      • link_identifier
        • The MySQL connection. If the link identifier is not specified, the last link opened by mysql_connect() is assumed. If no such link is found, it will try to create one as if mysql_connect() was called with no arguments. If by chance no connection is found or established, an E_WARNING level warning is generated.
    • Return Values
      • The thread ID on success, or FALSE on failure.
  • 434. mysql_thread_id <?php $link = mysql_connect('localhost', 'mysql_user', 'mysql_password'); $thread_id = mysql_thread_id($link); if ($thread_id){    printf(&quot;current thread id is %d &quot;, $thread_id); } ?> The above example will output something similar to: current thread id is 73
  • 435. mysql_unbuffered_query
    • Send an SQL query to MySQL, 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, without fetching and buffering the result rows automatically, as mysql_query() does. On the one hand, this saves a considerable amount of memory with SQL queries that produce large result sets. On the other hand, 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. When using multiple DB-connects, you have to specify the optional parameter link_identifier.
  • 436. mysql_unbuffered_query
    • Parameters
      • query
        • A SQL query
      • link_identifier
        • The MySQL connection. If the link identifier is not specified, the last link opened by mysql_connect() is assumed. If no such link is found, it will try to create one as if mysql_connect() was called with no arguments. If by chance no connection is found or established, an E_WARNING level warning is generated.
    • Return Values
      • For SELECT, SHOW, DESCRIBE or EXPLAIN statements, mysql_unbuffered_query() returns a resource on success, or FALSE on error.
    • For other type of SQL statements, UPDATE, DELETE, DROP, etc, mysql_unbuffered_query() returns TRUE on success or FALSE on error.
  • 437. CHAPTER 10 PHP AND PEAR DB
  • 438. PEAR
    • PEAR(PHP Extention and Application Repository)is a collection of useful modules and libraries for PHP.
    • PEAR DB databse program abstraction layer is an add on to php that simplifies communication between your PHP program and database program.
  • 439. PHP databse abstraction layer
    • Web browser
    • Apache/IIS
    • PHP engine
    • Pear DB
    • DB extension
    • Mysql ,sqlite
    • DB server
  • 440. PEAR
    • The DB module is one of the most popular pear modules and is bundled with recent versions of PHP.
    • To use PEAR DB in a PHP program,first you have to load the DB module.
    • To load DB module use require construct.
    • require DB.php //case-sensitive
  • 441. DB.php
    • DB.php is the main file of the PEAR DB package.
    • It defines the functions that u use to talk to your database.
    • DB::connect(),DB::isError(),query(), disconnect(),getMessage(),fetchRow() are some of the functions defined by DB.php
  • 442. require and include
    • The require construct tells the PHP interpreter to execute all the code in the file DB.php.
    • The require and include are simillar but differ in how they handle errors.
  • 443. require and include
    • If you try to require a file that dosen't exists,require consider that as fatal error and your php program ends.
    • If you try to include a file that doesn,t exists, include reports a warning allowing your program to continue running.
  • 444. DB:: connect()
    • You pass DB::connect() a string as argument.
    • The string pssed to DB::connect () is called a Data Source Network.(DSN)
    • Its genral form is dbProgram://user:pass@hostname/database
    • disconnect() is used to terminate connection with database.
  • 445. Error handling in PEAR
    • DB::is Error () returns true if error occurred in database operations.
    • Instead of calling DB::isError () after every query to check its succeeded or failed ,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.
  • 446. fetchRow()
    • The fetchRow() function all field data in a record.
    • This data can be assigned to an array variable.
    • This fetchRow () function returns false if all row resulted by the query is fetched.
    • So the fetchRow () can be iterated using while loop.
  • 447. Chapter Summary
    • Understanding PEAR helps the programmer in database operations.
    • Requiring DB.php.
    • Establishing ans terminating connections with databases.
    • Error handling
    • Retriving data from database using PEAR.
  • 448. CHAPTER 11 COOKIES AND SESSIONS
  • 449. Cookies and Sessions
    • Working with Cookies.
    • Activating Sessions.
    • Storing and retrieving information.
    • Login and User identification.
    • Why setcookie() and session_start() want to be at the top of the page.
  • 450. Cookies and Sessions
    • Cookie identifies a web client to web server
    • Cookie has a name and a value.
    • Session uses cookie to persist data across requests.
    • PHP session capabilities keeps track of multiple piece of information under one cookie.
  • 451. Working with Cookies
    • Use setcookie() function to set a cookie.
    • Call setcookie() before the page generates any output.
    • Cookies show up in $_COOKIE only when the web client sends them with the request.
    • Cookies are only sent back with requests for pages in the same directory.
    • Path to setcookie() must match the server .
  • 452. Cookies
    • Setcookie() can take five arguments. First argument is the name of the cookie. Second is the value of the cookie. Third argument specifies the life time of the cookie. Fourth and fifth are path and domain.
    • The default lifetime of the cookie is the lifetime of the web client. when you quit internet explorer or Mozilla Firefox the cookie is automatically deleted.
  • 453. 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.
  • 454. 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, to access a user's session data
    • Session data is not restricted to string and numbers, its like any other array
  • 455. Configuring Sessions
    • Sessions work great with no additional tweak
    • Session default timeout is 24 minutes
    • Use session.gc_maxlifetime configuration directive, or call ini_set() function from your program to configure idle time to keep a session active
    • Use ini_set() before session_start()
  • 456. 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, cookie and session functions
  • 457. 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, path, and domain
    • Deleting a cookie in a PHP program
  • 458. 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, validating, and processing a validation form
  • 459. 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.
  • 460. CHAPTER 12 WORKING WITH DATES AND TIMES
  • 461. Handling Dates And Times
    • Displaying the Date or Time.
    • Parsing a Date or Time.
    • Dates and Times in Forms.
  • 462. Displaying Date or Time
    • Use the date( ) or strftime( ) functions to display the date and time.
    • Both strftime( ) and date( )take two arguments.
    • The first argument controls how the date or time string is formatted.
    • The second argument controls what date or time is used.
  • 463. Displaying Date or Time
    • In date ( ) function / can't be used for escaping.
    • 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.
  • 464. Displaying Date and Time
    • The date( ) and strftime( )functions have their strong points.
    • Strftime( ) is better because we don't want to worry about letters with out percentage sign turning into time or date values.
    • Date ( ) is better because it supports leap year indicator and trims leading zeros from some values.
  • 465. Displaying Date and Time
    • Date( ) is php specific function. It operates on any OS.
    • The strftime( ) is a php function that relies on underlying operating system functions.
  • 466. Parsing Date or Time
    • Epoch timestamp: The number of seconds that have elapsed since midnight on January 1,1970.
    • If you have discrete date or time parts then use mktime ( )
    • The mktime ( ) accepts an hour, minute, second,month,days and year and returns the corresponding epoch time stamps.
  • 467. Parsing Date and Time
    • Use strtotime( ),when you want the epoch timestamp for something relative to a time you know.
    • Strtotime( ) understands English description of relative times and returns an appropriate epoch time stamp.
  • 468. Parsing Date and Time
      • Like date() and strftime(),strtotime() also accept an epoch time stamp second argument to use as the starting point for its calculation
  • 469. Dates and Time in Form
      • When you need a user to input a date in a form ,the best thing to do is to <select> menus
      • This restricts the possible input to what ever you display in the menus.
  • 470. Chapter Summary
    • Defining some time and date handling vocabulary such as epoch timestamp , time and date parts and formatted date and time string.
    • Printing formatted time and date string with strftime( ) and date( ).
    • Making an epoch timestamp with mktime ( ).
  • 471. Chapter summary
    • Making an epoch timestamp with strtotime().
    • Displaying form elements to allow for date or time input.
  • 472. CHAPTER 13 DATE AND TIME FUNTIONS
  • 473. checkdate
    • Validate a Gregorian date
    • bool checkdate ( int $month, int $day, int $year )
    • Checks the validity of the date formed by the arguments. A date is considered valid if each parameter is properly defined.
    • Parameters
      • month
        • The month is between 1 and 12 inclusive.
      • day
        • The day is within the allowed number of days for the given month. Leap years are taken into consideration.
  • 474. checkdate
      • year
        • The year is between 1 and 32767 inclusive.
    • Return Values
      • Returns TRUE if the date given is valid; otherwise returns FALSE
    <?php var_dump(checkdate(12, 31, 2000)); var_dump(checkdate(2, 29, 2001)); ?> The above example will output: bool(true) bool(false)
  • 475. date_create
    • Returns new DateTime object
    • DateTime date_create ( [string $time [, DateTimeZone $timezone]] )
    • DateTime DateTime::__construct ( [string $time [, DateTimeZone $timezone]] )
  • 476. date_create
    • Parameters
      • time
        • String in a format accepted by strtotime(), defaults to &quot;now&quot;.
      • timezone
        • Time zone of the time.
    • Return Values
      • Returns DateTime object on success or FALSE on failure.
  • 477. date_date_set
    • Sets the date
    • void date_date_set ( DateTime $object, int $year, int $month, int $day )
    • void DateTime::setDate ( int $year, int $month, int $day )
  • 478. date_date_set
    • Parameters
      • object
        • DateTime object.
      • year
        • Year of the date.
      • month
        • Month of the date.
      • day
        • Day of the date.
    • Return Values
        • Returns NULL on success or FALSE on failure.
  • 479. date_default_timezone_get
    • Gets the default timezone used by all date/time functions in a script
    • string date_default_timezone_get ( void )
  • 480. date_default_timezone_get
      • The TZ environment variable (if non empty)
      • The date.timezone ini option (if set)
      • &quot;magical&quot; guess (if the operating system supports it)
      • If none of the above options succeeds, return UTC
    • Return Values
      • Returns a string
  • 481. 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.
  • 482. date_default_timezone_set
    • Parameters
      • timezone_identifier
        • The timezone identifier, like UTC or Europe/Lisbon. The list of valid identifiers is available in the Appendix I, List of Supported Timezones.
    • Return Values
      • This function returns FALSE if the timezone_identifier isn't valid, or TRUE otherwise.
  • 483. date_format
    • Returns date formatted according to given format
    • string date_format ( DateTime $object, string $format )
    • string DateTime::format ( string $format )
  • 484. date_format
    • Parameters
      • object
        • DateTime object.
      • format
      • Format accepted by date().
    • Return Values
      • Returns formatted date on success or FALSE on failure.
  • 485. date_modify
    • Alters the timestamp
    • void date_modify ( DateTime $object, string $modify )
    • void DateTime::modify ( string $modify )
    • Parameters
      • object
        • DateTime object.
      • modify
        • String in a relative format accepted by strtotime().
    • Return Values
      • Returns NULL on success or FALSE on failure.
  • 486. date_offset_get
    • Returns the daylight saving time offset
    • int date_offset_get ( DateTime $object )
    • int DateTime::getOffset ( void )
    • Parameters
      • object
        • DateTime object.
    • Return Values
      • Returns DST offset in seconds on success or FALSE on failure.
  • 487. 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.
  • 488. date_parse <?php print_r(date_parse(&quot;2006-12-12 10:00:00.5&quot;)); ?> The above example will output: Array ( [year] => 2006 [month] => 12 [day] => 12 [hour] => 10 [minute] => 0 [second] => 0 [fraction] => 0.5 [warning_count] => 0 [warnings] => Array() [error_count] => 0 [errors] => Array() [is_localtime] =>
  • 489. date_sun_info
    • Returns an array with information about sunset/sunrise and twilight begin/end
    • array date_sun_info ( int $time, float $latitude, float $longitude )
    • Parameters
      • time
        • Timestamp.
      • latitude
        • Latitude in degrees.
      • longitude
        • Longitude in degrees.
  • 490. get_sun_info
    • Return Values
      • Returns array on success or FALSE on failure.
    <?php $sun_info = date_sun_info(strtotime(&quot;2006-12-12&quot;), 31.7667, 35.2333); foreach ($sun_info as $key => $val) {    echo &quot;$key: &quot; . date(&quot;H:i:s&quot;, $val) . &quot; &quot;; } ?> The above example will output: 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
  • 491. date_sunrise
    • Returns time of sunrise for a given day and location
    • mixed date_sunrise ( int $timestamp [, int $format [, float $latitude [, float $longitude [, float $zenith [, float $gmt_offset]]]]] )
    • date_sunrise() returns the sunrise time for a given day (specified as a timestamp) and location.
  • 492. date_sunrise
    • Parameters
      • timestamp
        • The timestamp of the day from which the sunrise time is taken.
      • latitude
        • Defaults to North, pass in a negative value for South. See also: date.default_latitude
      • longitude
        • Defaults to East, pass in a negative value for West. See also: date.default_longitude
  • 493. date_sunrise
    • zenith
        • Default: date.sunrise_zenith
      • gmtoffset
        • Specified in hours.
    • Return Values
      • Returns the sunrise time in a specified format on success, or FALSE on failure.
  • 494. date_sunrise Constant description example SUNFUNCS_RET_STRING returns the result as string 16:46 SUNFUNCS_RET_DOUBLE returns the result as float 16.78243132 SUNFUNCS_RET_TIMESTAMP returns the result as integer (timestamp) 1095034606
  • 495. date_sunrise <?php /* calculate the sunrise time for Lisbon, Portugal Latitude: 38.4 North Longitude: 9 West Zenith ~= 90 offset: +1 GMT */ echo date(&quot;D M d Y&quot;). ', sunrise time : ' .date_sunrise(time(), SUNFUNCS_RET_STRING, 38.4, -9, 90, 1); ?> The above example will output something similar to: Mon Dec 20 2004, sunrise time : 08:54
  • 496. date_sunset
    • Returns time of sunset for a given day and location
    • mixed date_sunset ( int $timestamp [, int $format [, float $latitude [, float $longitude [, float $zenith [, float $gmt_offset]]]]] )
    • date_sunset() returns the sunset time for a given day (specified as a timestamp) and location.
  • 497. date_sunset
    • Parameters
      • timestamp
        • The timestamp of the day from which the sunset time is taken.
      • latitude
        • Defaults to North, pass in a negative value for South. See also: date.default_latitude
      • longitude
        • Defaults to East, pass in a negative value for West. See also: date.default_longitude
      • zenith
      • Default: date.sunrise_zenith
      • gmtoffset
      • Specified in hours.
  • 498. date_sunset <?php /* calculate the sunset time for Lisbon, Portugal Latitude: 38.4 North Longitude: 9 West Zenith ~= 90 offset: +1 GMT */ echo date(&quot;D M d Y&quot;). ', sunset time : ' .date_sunset(time(), SUNFUNCS_RET_STRING, 38.4, -9, 90, 1); ?> The above example will output something similar to: Mon Dec 20 2004, sunset time : 18:13
  • 499. date_time_set
    • Sets the time
    • void date_time_set ( DateTime $object, int $hour, int $minute [, int $second] )
    • void DateTime::setTime ( int $hour, int $minute [, int $second] )
  • 500. date_time_set
    • Parameters
      • object
        • DateTime object.
      • hour
        • Hour of the time.
      • minute
        • Minute of the time.
      • second
    • Second of the time.
    • Return Values
      • Returns NULL on success or FALSE on failure.
  • 501. date_timezone_get
    • Return time zone relative to given DateTime
    • DateTimeZone date_timezone_get (DateTime $object)
    • DateTimeZone DateTime::getTimezone(void)
    • Parameters
    • object
      • DateTime object.
    • Return Values
      • Returns DateTimeZone object on success or FALSE on failure.
  • 502. date_timezone_set
    • Sets the time zone for the DateTime object
    • void date_timezone_set ( DateTime $object, DateTimeZone $timezone )
    • void DateTime::setTimezone ( DateTimeZone $timezone )
    • Parameters
      • Object ..DateTime object.
      • Timezone ..Desired time zone.
    • Return Values
      • Returns NULL on success or FALSE on failure.
  • 503. 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. In other words, timestamp is optional and defaults to the value of time().
    • Parameters
    • format
      • The format of the outputted date string.
  • 504. date format character Description Example returned values Day --- --- d Day of the month, 2 digits with leading zeros 01 to 31 D A textual representation of a day, 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.1.0) (for sunday) S English ordinal suffix for the day of the month, st, nd, rd or th. Works well with j
  • 505. getdate
    • Get date/time information
    • array getdate ( [int $timestamp] )
    • Returns an associative array containing the date information of the timestamp, or the current local time if no timestamp is given.
  • 506. 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. In other words, it defaults to the value of time().
    • Return Values
      • Returns an associative array of information related to the typestamp.
  • 507. getdate <?php $today = getdate(); print_r($today); ?> 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 )
  • 508. 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.
  • 509. 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:
          • &quot;sec&quot; - seconds since the Unix Epoch
          • &quot;usec&quot; - microseconds
          • &quot;minuteswest&quot; - minutes west of Greenwich
          • &quot;dsttime&quot; - type of dst correction
  • 510. 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
  • 511. 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).
  • 512. gmdate
    • Parameters
      • 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.
  • 513. gmdate When run in Finland (GMT +0200), the first line below prints &quot;Jan 01 1998 00:00:00&quot;, while the second prints &quot;Dec 31 1997 22:00:00&quot;. <?php echo date(&quot;M d Y H:i:s&quot;, mktime(0, 0, 0, 1, 1, 1998)); echo gmdate(&quot;M d Y H:i:s&quot;, mktime(0, 0, 0, 1, 1, 1998)); ?>
  • 514. CHAPTER 14 CALENDER FUNCTIONS
  • 515. 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!
  • 516. cal_days_in_month
    • cal_days_in_month — Return the number of days in a month for a given year and calendar
    • int cal_days_in_month ( int $calendar, int $month, int $year )
    • This function will return the number of days in the month of year for the specified calendar.
    <?php $num = cal_days_in_month(CAL_GREGORIAN, 8, 2003); // 31 echo &quot;There was $num days in August 2003&quot;; ?>
  • 517. cal_from_jd
    • cal_from_jd — Converts from Julian Day Count to a supported calendar
    • array cal_from_jd ( int $jd, int $calendar )
    • cal_from_jd() converts the Julian day given in jd into a date of the specified calendar. Supported calendar values are CAL_GREGORIAN, CAL_JULIAN, CAL_JEWISH and CAL_FRENCH.
    <?php $today = unixtojd(mktime(0, 0, 0, 8, 16, 2003)); print_r(cal_from_jd($today, CAL_GREGORIAN)); ?> The above example will output: Array ( [date] => 8/16/2003 [month] => 8 [day] => 16 [year] => 2003 [dow] => 6 [abbrevdayname] => Sat [dayname] => Saturday [abbrevmonth] => Aug [monthname] => August )
  • 518. 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.
  • 519. call_info <?php $info = cal_info(0); print_r($info); ?> Array ( [months] => Array ( [1] => January [2] => February [3] => March [4] => April [5] => May [6] => June [7] => July [8] => August [9] => September [10] => October [11] => November [12] => December ) [abbrevmonths] => Array ( [1] => Jan [2] => Feb [3] => Mar [4] => Apr [5] => May [6] => Jun [7] => Jul [8] => Aug [9] => Sep [10] => Oct [11] => Nov [12] => Dec ) [maxdaysinmonth] => 31 [calname] => Gregorian [calsymbol] => CAL_GREGORIAN )
  • 520. cal_to_jd
    • cal_to_jd — Converts from a supported calendar to Julian Day Count
    • int cal_to_jd ( int $calendar, int $month, int $day, int $year )
    • cal_to_jd() calculates the Julian day count for a date in the specified calendar. Supported calendars are CAL_GREGORIAN, CAL_JULIAN, CAL_JEWISH and CAL_FRENCH.
  • 521. easter_date
    • easter_date — Get Unix timestamp for midnight on Easter of a given year
    • int easter_date ( [int $year] )
    • Returns the Unix timestamp corresponding to midnight on Easter of the given year.
    • Since PHP 4.3.0, the year parameter is optional and defaults to the current year according to the localtime if omitted.
    <?php echo date(&quot;M-d-Y&quot;, easter_date(1999));        // Apr-04-1999 echo date(&quot;M-d-Y&quot;, easter_date(2000));        // Apr-23-2000 echo date(&quot;M-d-Y&quot;, easter_date(2001));        // Apr-15-2001 ?>
  • 522. 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. If no year is specified, the current year is assumed.
    • Since PHP 4.3.0, the year parameter is optional and defaults to the current year according to the localtime if omitted.
    • The method parameter was also introduced in PHP 4.3.0 and allows to calculate easter dates based on the Gregorian calendar during the years 1582 - 1752 when set to CAL_EASTER_ROMAN. See the calendar constants for more valid constants.
    • This function can be used instead of easter_date() to calculate Easter for years which fall outside the range of Unix timestamps (i.e. before 1970 or after 2037).
  • 523. easter_days <?php echo easter_days(1999);        // 14, i.e. April 4 echo easter_days(1492);        // 32, i.e. April 22 echo easter_days(1913);        //  2, i.e. March 23 ?>
  • 524. FrenchToJD
    • FrenchToJD — Converts a date from the French Republican Calendar to a Julian Day Count
    • int frenchtojd ( int $month, int $day, int $year )
    • Converts a date from the French Republican Calendar to a Julian Day Count.
    • These routines only convert dates in years 1 through 14 (Gregorian dates 22 September 1792 through 22 September 1806). This more than covers the period when the calendar was in use.
  • 525. GregorianToJD
    • GregorianToJD — Converts a Gregorian date to Julian Day Count
    • int gregoriantojd ( int $month, int $day, int $year )
    • Valid Range for Gregorian Calendar 4714 B.C. to 9999 A.D.
    • Although this function can handle dates all the way back to 4714 B.C., such use may not be meaningful. The Gregorian calendar was not instituted until October 15, 1582 (or October 5, 1582 in the Julian calendar). Some countries did not accept it until much later. For example, Britain converted in 1752, The USSR in 1918 and Greece in 1923. Most European countries used the Julian calendar prior to the Gregorian.
  • 526. JDDayOfWeek
    • JDDayOfWeek — Returns the day of the week
    • mixed jddayofweek ( int $julianday [, int $mode] )
    • Returns the day of the week. Can return a string or an integer depending on the mode.
    MODE MEANING 0 (Default) Returns the day number as an int (0=Sunday, 1=Monday, etc) 1 Returns string containing the day of week (English-Gregorian) 2 Returns a string containing the abbreviated day of week (English-Gregorian)
  • 527. JDMonthName
    • JDMonthName — Returns a month name
    • string jdmonthname ( int $julianday, int $mode )
    • Returns a string containing a month name. mode tells this function which calendar to convert the Julian Day Count to, and what type of month names are to be returned.
  • 528. String functions Mode Meaning Values 0 Gregorian – abbreviated Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct,Nov, Dec 1 Gregorian January, February, March, April, May, June, July, August, September, October, November, December 2 Julian - abbreviated Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec 3 Julian January, February, March, April, May, June, July, August, September, October, November, December 4 Jewish Tishri, Heshvan, Kislev, Tevet, Shevat, AdarI, AdarII, Nisan, Iyyar, Sivan, Tammuz, Av, Elul 5 French Republican Vendemiaire, Brumaire, Frimaire, Nivose, Pluviose, Ventose, Germinal, Floreal, Prairial, Messidor, Thermidor, Fructidor, Extra
  • 529. 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.
  • 530. 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 &quot;month/day/year&quot;.
  • 531. jdtojewish
    • jdtojewish — Converts a Julian day count to a Jewish calendar date
    • string jdtojewish(int $juliandaycount[,bool$hebrew [, int $fl]] )
    • Converts a Julian Day Count to the Jewish Calendar.
    • The optional hebrew and fl parameters became available in PHP 5.0.0
    • If the hebrew parameter is set to TRUE, the fl parameter is used for Hebrew, string based, output format. The available formats are: CAL_JEWISH_ADD_ALAFIM_GERESH, CAL_JEWISH_ADD_ALAFIM,CAL_JEWISH_ADD_GERESHAYIM.
  • 532. 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 &quot;month/day/year&quot;.
  • 533. 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 ). The time returned is localtime (and not GMT).
  • 534. JewishToJD
    • JewishToJD — Converts a date in the Jewish Calendar to Julian Day Count
    • int jewishtojd ( int $month, int $day, int $year )
    • Although this function can handle dates all the way back to the year 1 (3761 B.C.), such use may not be meaningful. The Jewish calendar has been in use for several thousand years, but in the early days there was no formula to determine the start of a month. A new month was started when the new moon was first observed.
  • 535. JulianToJD
    • JulianToJD — Converts a Julian Calendar date to Julian Day Count
    • int juliantojd ( int $month, int $day, int $year )
    • Valid Range for Julian Calendar 4713 B.C. to 9999 A.D.
    • Although this function can handle dates all the way back to 4713 B.C., such use may not be meaningful. The calendar was created in 46 B.C., but the details did not stabilize until at least 8 A.D., and perhaps as late at the 4th century. Also, the beginning of a year varied from one culture to another - not all accepted January as the first month.
  • 536. unixtojd
    • unixtojd — Convert Unix timestamp to Julian Day
    • Description
    • int unixtojd ( [int $timestamp] )
    • Return the Julian Day for a Unix timestamp (seconds since 1.1.1970), or for the current day if no timestamp is given.
  • 537. CHAPTER 15 CLASSES AND OBJECTS
  • 538. Classes and Objects
    • Object basics.
    • Defining classes
    • Creating new objects.
    • Creating constructors.
    • Accessing properties and methods.
  • 539. Object Basics
    • An OBJECT is a structure that combines data about a thing, with actions on that thing.
    • The CLASS describes and holds the variables and functions for a kind of object.
    • The METHOD is the function defined in the class.
    • The PROPERTY is the variable defined in the class.
  • 540. PHP and OOP
    • OOP is a particular approach to solving problem that is not necessarily tied to any language or hardware architecture.
    • PHP is inherently a procedural language that has added the syntax necessary to support solution using OOP technique.
  • 541. 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.
  • 542. 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.
  • 543. 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.
  • 544. Creating new object
    • We can invokeor acces the member variables and functions in the class using -> operator
    • $objectname ->functionname();
  • 545. __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.
  • 546. __autoload()
    • You can define __ autoload function that automatically be called any time a new object attempts to be instantiated.
  • 547. 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
  • 548. 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.
  • 549. 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.
  • 550. 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.
  • 551. 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.
  • 552. 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.
  • 553. Chapter Summary
    • Defining some time and date handling vocabulary such as epoch timestamp , time and date parts and formatted date and time string.
    • Printing formatted time and date string with strftime( ) and date( ).
    • Making an epoch timestamp with mktime ( ).
  • 554. Chapter summary
    • Making an epoch timestamp with strtotime().
    • Displaying form elements to allow for date or time input.
  • 555. CHAPTER 16 CLASSES AND OBJECTS FUNCTIONS
  • 556. classes/object functions
    • These functions allow you to obtain information about classes and instance objects.
    • You can obtain the name of the class to which an object belongs,as well as its member properties and methods.
    • Using these functions, you can find out not only the class membership of an object, but also its parentage (i.e. what class is the object class extending).
  • 557. Classes objects <?php // base class with member properties and methods class Vegetable {    var $edible;    var $color;    function Vegetable($edible, $color=&quot;green&quot;)    {        $this->edible = $edible;        $this->color = $color;    }    function is_edible()    {        return $this->edible;    }    function what_color()    {        return $this->color;    } } // end of class Vegetable
  • 558. Classes objects // extends the base class class Spinach extends Vegetable {    var $cooked = false;    function Spinach()    {        $this->Vegetable(true, &quot;green&quot;);    }    function cook_it()    {        $this->cooked = true;    }    function is_cooked()    {        return $this->cooked;    } } // end of class Spinach ?>
  • 559. Classes object
    • In this example, we first define a base class and an extension of the class. The base class describes a general vegetable, whether it is edible or not and what is its color. The subclass Spinach adds a method to cook it and another to find out if it is cooked.
  • 560. call_user_method
    • call_user_method — Call a user method on an specific object [deprecated]
    • Description
    • mixed call_user_method ( string $method_name, object &$obj [, mixed $parameter [, mixed $...]] )
  • 561. 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, object &$obj, array $paramarr )
  • 562. 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.
    • 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.
  • 563. class_exists <?php // Check the class exists before trying to use it if (class_exists('MyClass')) {    $myclass = new MyClass(); } ?> <?php //autoload parameter example function __autoload($class) {   include($class . '.php');    // Check to see if the include declared the class    if (!class_exists($class, false)) {        trigger_error(&quot;Unable to load class: $class&quot;, E_USER_WARNING);    } } if (class_exists('MyClass')) {    $myclass = new MyClass(); } ?>
  • 564. get_class_methods
    • get_class_methods — Gets the class methods' names
    • array get_class_methods ( mixed $class_name )
    • Gets the class methods names.
    • 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. In case of an error, it returns NULL.
  • 565. get_class_methods $class_methods = get_class_methods('myclass'); // or $class_methods = get_class_methods(new myclass()); foreach ($class_methods as $method_name) {    echo &quot;$method_name &quot;; } ?> The above example will output: myclass myfunc1 myfunc2 <?php class myclass {    // constructor    function myclass()    {        return(true);    }    // method 1    function myfunc1()    {        return(true);    } }    // method 2    function myfunc2()    {        return(true);    }
  • 566. 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. The resulting array elements are in the form of varname => value.
  • 567. get_class_var $my_class = new myclass(); $class_vars = get_class_vars(get_class($my_class)); foreach ($class_vars as $name => $value) {    echo &quot;$name : $value &quot;; } ?> The above example will output: // Before PHP 4.2.0 var2 : xyz var3 : 100 // As of PHP 4.2.0 var1 : var2 : xyz var3 : 100 <?php class myclass { var $var1; // this has no default value...    var $var2 = &quot;xyz&quot;;    var $var3 = 100;    private $var4; // PHP 5 // constructor    function myclass() {        // change some properties        $this->var1 = &quot;foo&quot;;        $this->var2 = &quot;bar&quot;;        return true;    } }
  • 568. 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.
    • Parameters
      • object
        • The tested object
    • Return Values
      • Returns the name of the class of which object is an instance. Returns FALSE if object is not an object.
  • 569. get_class <?php class foo {    function foo()    {    // implements some logic    }    function name()    {        echo &quot;My name is &quot; , get_class($this) , &quot; &quot;;    } } // create an object $bar = new foo(); // external call echo &quot;Its name is &quot; , get_class($bar) , &quot; &quot;; // internal call $bar->name(); ?> The above example will output: Its name is foo My name is foo
  • 570. 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.
    • Return Values
      • Returns an array of the names of the declared classes in the current script.
  • 571. get_declared_classes
    • Note: In PHP 4.0.1, three extra classes are returned at the beginning of the array: stdClass (defined in Zend/zend.c), OverloadedTestClass (defined in ext/standard/basic_functions.c) and Directory (defined in ext/standard/dir.c).
    • Also note that depending on what libraries you have compiled into PHP, additional classes could be present. This means that you will not be able to define your own classes using these names. There is a list of predefined classes in the Predefined Classes section of the appendices.
    <?php print_r(get_declared_classes()); ?> The above example will output something similar to: Array ( [0] => stdClass [1] => __PHP_Incomplete_Class [2] => Directory )
  • 572. get_declared_interfaces
    • get_declared_interfaces — Returns an array of all declared interfaces
    • array get_declared_interfaces ( void )
    • Gets the declared interfaces.
    • Return Values
      • Returns an array of the names of the declared interfaces in the current script.
  • 573. 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 )
  • 574. 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.
    • Parameters
      • object
        • An object instance.
      • Return Values
        • Returns an associative array of defined object properties for the specified object. If a property have not been assigned a value, it will be returned with a NULL value.
  • 575. get_object_vars <?php class Point2D {    var $x, $y;    var $label;    function Point2D($x, $y)    {        $this->x = $x;        $this->y = $y;    }       function getPoint()    {        return array(&quot;x&quot; => $this->x,                      &quot;y&quot; => $this->y,                      &quot;label&quot; => $this->label);    } } // &quot;$label&quot; is declared but not defined $p1 = new Point2D(1.233, 3.445); The above example will output: Array ( [x] => 1.233 [y] => 3.445 [label] => ) Array ( [x] => 1.233 [y] => 3.445 [label] => point #1 ) function setLabel($label)    {        $this->label = $label;    } print_r(get_object_vars($p1)); $p1->setLabel(&quot;point #1&quot;); print_r(get_object_vars($p1)); ?>
  • 576. 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.
    • 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.
    • If called without parameter outside object, this function returns FALSE.
  • 577. get_parent_class [email_address] <?php class dad {    function dad()    {    // implements some logic    } } class child extends dad {    function child()    {        echo &quot;I'm &quot; , get_parent_class($this) , &quot;'s son &quot;;    } } class child2 extends dad {    function child2()    {        echo &quot;I'm &quot; , get_parent_class('child2') , &quot;'s son too &quot;;    } } $foo = new child(); $bar = new child2(); ?> The above example will output: I'm dad's son I'm dad's son too
  • 578. interface_exists
    • interface_exists — Checks if the interface has been defined
    • bool interface_exists ( string $interface_name [, bool $autoload] )
    • Checks if the given interface has been defined.
    • 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, FALSE otherwise.
  • 579. interface_exists <?php // Check the interface exists before trying to use it if (interface_exists('MyInterface')) {    class MyClass implements MyInterface    {        // Methods    } } ?>
  • 580. 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
  • 581. is_a
    • Return Values
        • Returns TRUE if the object is of this class or has this class as one of its parents, FALSE otherwise.
    <?php // define a class class WidgetFactory {   var $oink = 'moo'; } // create a new object $WF = new WidgetFactory(); if (is_a($WF, 'WidgetFactory')) {   echo &quot;yes, $WF is still a WidgetFactory &quot;; } ?> <?php if ($WF instanceof WidgetFactory) {    echo 'Yes, $WF is a WidgetFactory'; } ?>
  • 582. is_subclass_of
    • is_subclass_of — Checks if the object has this class as one of its parents
    • bool is_subclass_of ( mixed $object, string $class_name )
    • Checks if the given object has the class class_name as one of its parents.
    • Parameters
      • Object
        • A class name or an object instance
      • class_name
        • The class name
      • Return Values
        • This function returns TRUE if the object object, belongs to a class which is a subclass of class_name, FALSE otherwise.
  • 583. is_subclass_of <?php // define a class class WidgetFactory {   var $oink = 'moo'; } // define a child class class WidgetFactory_Child extends WidgetFactory {   var $oink = 'oink'; } // create a new object $WF = new WidgetFactory(); $WFC = new WidgetFactory_Child(); if (is_subclass_of($WFC, 'WidgetFactory')) {   echo &quot;yes, $WFC is a subclass of WidgetFactory &quot;; } else {   echo &quot;no, $WFC is not a subclass of WidgetFactory &quot;; } if (is_subclass_of($WF, 'WidgetFactory')) {   echo &quot;yes, $WF is a subclass of WidgetFactory &quot;; } else {   echo &quot;no, $WF is not a subclass of WidgetFactory &quot;; }
  • 584. is_sub_class_of // usable only since PHP 5.0.3 if (is_subclass_of('WidgetFactory_Child', 'WidgetFactory')) {   echo &quot;yes, WidgetFactory_Child is a subclass of WidgetFactory &quot;; } else {   echo &quot;no, WidgetFactory_Child is not a subclass of WidgetFactory &quot;; } ?> The above example will output: yes, $WFC is a subclass of WidgetFactory no, $WF is not a subclass of WidgetFactory yes, WidgetFactory_Child is a subclass of WidgetFactory
  • 585. 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.
  • 586. method_exists
    • Parameters
      • object
        • An object instance
      • method_name
        • The method name
      • Return Values
        • Returns TRUE if the method given by method_name has been defined for the given object, FALSE otherwise.
    <?php $directory = new Directory('.'); var_dump(method_exists($directory,'read')); ?> The above example will output: bool(true)
  • 587. 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.
  • 588. 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(); ?>
  • 589. CHAPTER 17 WORKING WITH FILES
  • 590. 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
  • 591. 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
  • 592. 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
  • 593. 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.
  • 594. 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
  • 595. 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
  • 596. 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()
  • 597. 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 ()
  • 598. 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
  • 599. CHAPTER 18 GETTEXT FUNCTIONS
  • 600. GETTEXT FUNCTIONS
    • The gettext functions implement an NLS (Native Language Support) API which can be used to internationalize your PHP applications.
  • 601. dcgettext
    • dcgettext — Overrides the domain for a single lookup
    • string dcgettext ( string $domain, string $message, int $category )
    • This function allows you to override the current domain for a single message lookup.
    • Parameters
      • domain
        • The domain
      • message
        • The message
      • Category
        • The category
      • Return Values
        • A string on success.
  • 602. dcngettext
    • dcngettext — Plural version of dcgettext
    • string dcngettext ( string $domain, string $msgid1, string $msgid2, int $n, int $category )
    • This function allows you to override the current domain for a single plural message lookup.
    • Parameters
      • domain
        • The domain
      • msgid1
      • msgid2
      • n
      • Category
      • Return Values
        • A string on success.
  • 603. dgettext
    • dgettext — Override the current domain
    • Description
    • string dgettext ( string $domain, string $message )
    • The dgettext() function allows you to override the current domain for a single message lookup.
    • Parameters
    • Domain
      • The domain
    • message
      • The message
      • Return Values
        • A string on success.
  • 604. dngettext
    • dngettext — Plural version of dgettext
    • string dngettext ( string $domain, string $msgid1, string $msgid2, int $n )
    • The dngettext() function allows you to override the current domain for a single plural message lookup.
    • Parameters
      • Domain
        • The domain
      • msgid1
      • msgid2
      • n
      • Return Values
        • A string on success.
  • 605. gettext
    • gettext — Lookup a message in the current domain
    • string gettext ( string $message )
    • Looks up a message in the current domain.
    • Parameters
      • message
    • Return Values
      • Returns a translated string if one is found in the translation table, or the submitted message if not found.
  • 606. ngettext
    • ngettext — Plural version of gettext
    • string ngettext ( string $msgid1, string $msgid2, int $n )
    • The plural version of gettext(). Some languages have more than one form for plural messages dependent on the count.
    • Parameters
      • msgid1
      • msgid2
      • n
    • Return Values
      • Returns correct plural form of message identified by msgid1 and msgid2 for count n.
  • 607. 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(), usually the named after an application.
    • 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.
  • 608. CHAPTER 19 REGULAR EXPRESSION
  • 609. Regular expression
    • A regular expression, often called as pattern,is an expression that describes a set of string.
    • Regular expressions are used to test the sequence of characters (may be in a credit card number, mobile number,Email address)has an allowed pattern of characters.
  • 610. Regex which you use already
    • Search and replace in word processors.
    • Directory listing
      • dir *.eexe
      • dir *.*
      • dir sales04???.xls
      • Online searching
    • In production of code completion systems and syntax highlighting in integrated development environments(IDEs).
  • 611. Regex can be used for
    • Finding doubled words
    • Checking inputs from web forms
    • Changing date formats
    • Finding incorrect case.
  • 612. Matching characters
    • The simplest regular expression involves matching a single character.
    • Most characters and letters mostly match themselves.
    • For example,the regular expression test will match the string “test” exactly.
  • 613. Metacharacters
    • Some characters do not match themselves and are called metacharacters.
    • .^*+?{[]}|() is the complete list of metacharacters.
  • 614. Metacharacters
    • “[“ , ”]” are used for specifying a character class,which is a set of character that you wish to match.
    • 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,”b” or”c”
  • 615. Metacharacters
    • ^ matches a start of the line
    • [^] matches a single character that is not contained within the bracket.
    • $ matches the end of the line.
    • Metacharacters are not active inside classes.
      • For example [akm$] will match any of the characters “a,”k”,”m” or “$”.$ is a metacharacter but inside the character class it stripped of its special nature.
  • 616. Metacharacters
    • is used to strip the special meaning of metacharacters.
      • For example [asd[cdf] here “[“ needed to match inside character class so is used to escape [
    • d matches any decimal digits.[0-9]
    • D Matches any non digit character[^0-9]
    • s matches any white space character[ fv]
  • 617. Metacharacters
    • S matches any non white space characters [^ fv]
    • w matches any alphanumeric character. [a-zA-Z0-9_]
    • W matches any non alphanumeric character.
      • For example [s.,] will match any white apace character or “,” or “.”
  • 618. Metacharacters
    • . matches any thing except new line character.
    • | A vertical bar separates alternatives.
      • For example “gray|grey” ,which could be shortened to the equivalent gr(a|e)y, can match gray or grey
    • () parentheses are used to define the scope and precedence of operator.
  • 619. Quantifier
    • A quantifier after a character or group specifies how often that preceding expression is allowed to occur.
    • The most common quantifiers are ?,* and +
  • 620. Quantifier
    • ? The ? Indicates there is 0 or 1 of previous expression.
      • For example , “colou?r “ matches both color and colour.
    • * The * indicates there are 0,1 or any of the previous expression .
      • For example “go*gle” matches ggle,gogle,google,gooogle etc.
  • 621. Quantifier
    • + The plus sign indicates that there is at least 1 of the previous expression
      • For example “go+gle “ matches gogle,google,gooogle etc
  • 622. Metacharacter
    • {m,n} specifies occurrence of the character minimum of m times and maximum of n times.
      • “ab{2,3}” matches abb or abbb
  • 623. CHAPTER 20 DEBUGGING
  • 624. Debugging
    • Controlling where errors appear
    • Fixing parse errors
    • Inspecting program data
    • Fixing database errors
  • 625. 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, Warning, Notice and Strict notices are the different kinds of errors
  • 626. 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.php.net/tokens Contains the list of all tokens that PHP interpreter uses
  • 627. Inspecting Program Data
    • A program can be syntactically correct but logically flawed.. 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.. use __FILE__ special constant to check filename
    • ob_start(), ob_get_contents(), ob_end_clean
  • 628. Fixing Database Errors
    • Use setErrorHandling() with PEAR_ERROR_CALLBACK
    • $db->setErrorHandling (PEAR_ERROR_CALLBACK, 'my_func');
    • The callback function must accept one argument, which is the error object
    • Invoke getDebugInfo () to get more error info
  • 629. Chapter Summary
    • Configuring error display for a web browser, a web server error log, 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
  • 630. Chapter Summary
    • Printing debugging information with print, var_dump() and error_log()
    • Sending var_dump() output to the error log with output buffering functions
    • Writing a custom database error-handling function
  • 631. CHAPTER 21 WHAT ELSE WITH PHP
  • 632. 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
  • 633. What Else with PHP?
    • Running Shell Commands
    • Encryption
    • Talking to Other Languages
    • IMAP, POP3, and NNTP
    • Command-Line PHP
    • PHP-GTK
  • 634. Even More with PHP!
    • More extensions, add-ons, library and built-in functions are available
    • The PHP Manual http://www.php.net/manual
    • The PEAR Package List http://pear.php.net/packages.php
    • The PECL Package List http://pecl.php.net/packages.php
  • 635. Chapter Summary
    • Printing debugging information with print, var_dump() and error_log()
    • Sending var_dump() output to the error log with output buffering functions
    • Writing a custom database error-handling function
  • 636. IntelliBitz Technologies Training Division 168, Medavakkam Main Road Madipakkam, Chennai 91. PH: +91 044 2247 5106 www.intellibitz.com [email_address]