Jimmy Brion, PHP Programmer at PHPTop Frameworks are beauty of PHP :-) http://www.php-developers.org/blog/php/top10-php-frameworks-2012.html3 months ago
Are you sure you want to
ARNAWSINi m very impressed ....because this is help ful for me..thanks..3 months ago
Are you sure you want to
Netsanet HaftetsionIts Really Helpful for Me........ Thanks a more......4 months ago
Are you sure you want to
Bipin PrajapatiIts Really Helpful for Me........ Thanks a Lot...........4 months ago
Are you sure you want to
Patel Sagardownload kevi rite kar vanu bhai jaldi replay kar ro bhai8 months ago
Are you sure you want to
dimmduhПроверить, подойдет ли для новичков1 year ago
Are you sure you want to
webdeveloper1982need some more info on the setup of a web server, and OOP. I found this pretty useful too: PHP Tutorial to take it further1 year ago
IntelliBitz Technologies Training Division 168, Medavakkam Main Road Madipakkam, Chennai 91. PH: +91 044 2247 5106 www.intellibitz.com [email_address]
PHP WEB PROGRAMMING.
CHAPTER 1 STARTING WITH PHP.
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
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?”
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
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
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.
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
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
Basic Rules of PHP Programs
Start and End Tags
Whitespace and Case-Sensitivity
Comments
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
CHAPTER 2 TEXT AND NUMBERS
Working with Text and Numbers
Defining Text Strings
Validating and formatting text
Manipulating Text
Numbers
Arithmetic Operators
Variables
Putting variables inside strings
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
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.
Manipulating Text
Validating string using trim () and strlen ()
To compare two strings, use the equality operator (==)
Use strcasecmp () to compare strings ignoring case
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 ()
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().
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
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.
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.
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.
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
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.
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
This function returns a copy of str, translating all occurrences of each character in from to the corresponding character in to.
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.
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.
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 ("), backslash () and NUL (the NULL byte).
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.
String functions
Htmlspecialchars()
Convert special characters to HTML entities.
This function returns a string with some of these conversions made
'&' (ampersand) becomes '&'
'"' (double quote) becomes '"' when ENT_NOQUOTES is not set.
''' (single quote) becomes ''' only when ENT_QUOTES is set.
'<' (less than) becomes '<'
'>' (greater than) becomes '>'
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
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
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.
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
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
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.
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.
String functions
wordwrap
Wraps a string to a given number of characters using a string break character
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
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 )
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).
Numbers
Numbers – floating point and decimals
Arithmetic operators
+, -, *, /, %
Operator precedence
Grouping operations inside parentheses, will execute whats inside the parentheses first
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.
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
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)
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.
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).
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.
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.
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 ()
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
Chapter Summary
Naming variables appropriately
Using combined operators with variables
Using increment and decrement operators with variables
Interpolating variables in strings
CHAPTER 3 Making Decisions and Looping
Making Decisions and Looping
Understanding true and false
Making Decisions
Building Complicated Decisions
Repeating Yourself
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
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.
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
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
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 "a is bigger than b"; ?> <?php if ($a > $b) { echo "a is bigger than b"; $b = $a; } ?>
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 "a is bigger than b"; } else { echo "a is NOT bigger than b"; } ?>
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 "a is bigger than b"; } elseif ($a == $b) { echo "a is equal to b"; } else { echo "a is smaller than b"; } ?>
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.
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) */ ?>
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); ?>
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; }
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.
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
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”; } ?>
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.
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 "At 5<br />
"; break 1; /* Exit only the switch. */ case 10: echo "At 10; quitting<br />
"; break 2; /* Exit the switch and the while. */ default: break; } }
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 "Outer<br />
"; while (1) { echo "Middle<br />
"; while (1) { echo "Inner<br />
"; continue 3; } echo "This never gets output.<br />
"; } echo "Neither does this.<br />
"; }
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 "i equals 0"; break; case 1: echo "i equals 1"; break; case 2: echo "i equals 2"; break; } ?>
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 "i equals 0"; case 1: echo "i equals 1"; case 2: echo "i equals 2"; } ?>
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 "a equals 5"; echo "..."; elseif ($a == 6): echo "a equals 6"; echo "!!!"; else: echo "a is neither 5 nor 6"; endif; ?>
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.
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).
require()
The require() statement includes and evaluates the specific file.
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.
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.
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("a.php"); // this will include a.php require_once("A.php"); // this will include a.php //again on Windows! (PHP 4 only) ?>
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.
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 ?>
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.
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("profile"); // 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)), "<br />;"; } } // Display the data stored in the profiler print_r(profile(TRUE)); ?>
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
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
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
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
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
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 ()
CHAPTER 4 WORKING WITH ARRAYS
Working with Arrays
Creating an Array
Creating a Numeric Array
Looping through Arrays
Modifying Arrays
Sorting Arrays
Using Multidimensional Arrays
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
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
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
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
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
array()
Create an array
array array ( [mixed $...] )
Returns an array of the parameters. The parameters can be given an index with the => operator.
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 "Hello {$foo['bar']}!"; // Hello baz! ?>
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("lemon", "orange", "banana", "apple"); sort($fruits); foreach ($fruits as $key => $val) { echo "fruits[" . $key . "] = " . $val . "
"; } ?> The above example will output: fruits[0] = apple fruits[1] = banana fruits[2] = lemon fruits[3] = orange
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.
rsort <?php $fruits = array("lemon", "orange", "banana", "apple"); rsort($fruits); foreach ($fruits as $key => $val) { echo "$key = $val
"; } ?> The above example will output: 0 = orange 1 = lemon 2 = banana 3 = apple
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.
asort <?php $fruits = array("d" => "lemon", "a" => "orange", "b" => "banana", "c" => "apple"); asort($fruits); foreach ($fruits as $key => $val) { echo "$key = $val
"; } ?> 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.
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.
arsort <?php $fruits = array("d" => "lemon", "a" => "orange", "b" => "banana", "c" => "apple"); arsort($fruits); foreach ($fruits as $key => $val) { echo "$key = $val
"; } ?> 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.
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("d"=>"lemon", "a"=>"orange", "b"=>"banana", "c"=>"apple"); ksort($fruits); foreach ($fruits as $key => $val) { echo "$key = $val
"; } ?> The above example will output: a = orange b = banana c = apple d = lemon
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("d"=>"lemon", "a"=>"orange", "b"=>"banana", "c"=>"apple"); krsort($fruits); foreach ($fruits as $key => $val) { echo "$key = $val
"; } ?> The above example will output: d = lemon c = apple b = banana a = orange
natsort
Sort an array using a "natural order" algorithm
bool natsort ( array &$array )
This function implements a sort algorithm that orders alphanumeric strings in the way a human being would while maintaining key/value associations. This is described as a "natural ordering". An example of the difference between this algorithm and the regular computer string sorting algorithms (used in sort()) can be seen below:
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.
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, "cmp"); foreach ($a as $key => $value) { echo "$key: $value
"; } ?> The above example will output: 0: 1 1: 2 2: 3 3: 5 4: 6
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.
uasort
Sort an array with a user-defined comparison function and maintain index association
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.
uksort
Sort an array by keys using a user-defined comparison 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.
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("John" => 1, "the Earth" => 2, "an apple" => 3, "a banana" => 4); uksort($a, "cmp"); foreach ($a as $key => $value) { echo "$key: $value
"; } ?>
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 "$drink is $color and $power makes it special.
"; // Listing some of them list($drink, , $power) = $info; echo "$drink has $power.
"; // Or let's skip to only the third one list( , , $power) = $info; echo "I need $power!
"; ?>
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.
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 ) )
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 ) )
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 "apple" while ($fruit_name = current($array)) { if ($fruit_name == 'apple') { echo key($array).'<br />'; } next($array); } ?>
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.
Every array has an internal pointer to its "current" 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
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.
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.
each <?php $foo = array("bob", "fred", "jussi", "jouni", "egon", "marliese"); $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("Robert" => "Bob", "Seppo" => "Sepi"); $bar = each($foo); print_r($bar); ?> $bar now contains the following key/value pairs: Array ( [1] => Bob [value] => Bob [0] => Robert [key] => Robert )
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.
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.
reset <?php $array = array('step one', 'step two', 'step three', 'step four'); // by default, the pointer is on the first element echo current($array) . "<br />
"; // "step one" // skip two steps next($array); next($array); echo current($array) . "<br />
"; // "step three" // reset pointer, start again on step one reset($array); echo current($array) . "<br />
"; // "step one" ?>
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.
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.
in_array <?php $os = array("Mac", "NT", "Irix", "Linux"); if (in_array("Irix", $os)) { echo "Got Irix"; } if (in_array("mac", $os)) { echo "Got mac"; } ?> The second condition fails because in_array() is case-sensitive, so the program above will display: Got Irix
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.
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, "hello", 1, "world", "hello"); print_r(array_count_values($array)); ?> The above example will output: Array ( [1] => 2 [hello] => 2 [world] => 1 )
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.
array_values() returns all the values from the input array and indexes numerically the array.
<?php $array = array("size" => "XL", "color" => "gold"); print_r(array_values($array)); ?> The above example will output: Array ( [0] => XL [1] => gold )
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, "noop"); // not padded ?> www.intellibitz.com [email_address]
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("orange", "banana", "apple", "raspberry"); $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.
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("orange", "banana"); array_push($stack, "apple", "raspberry"); print_r($stack); ?> The above example will output: Array ( [0] => orange [1] => banana [2] => apple [3] => raspberry )
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.
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.
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 "product(a) = " . array_product($a) . "
"; ?> The above example will output: product(a) = 384
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.
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.
array_walk <?php $fruits = array("d" => "lemon", "a" => "orange", "b" => "banana", "c" => "apple"); function test_alter(&$item1, $key, $prefix) { $item1 = "$prefix: $item1"; } function test_print($item2, $key) { echo "$key. $item2<br />
"; } 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 "Before ...:
"; array_walk($fruits, 'test_print'); array_walk($fruits, 'test_alter', 'fruit'); echo "... and after:
"; array_walk($fruits, 'test_print'); ?>
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.
array_unique <?php $input = array("a" => "green", "red", "b" => "green", "blue", "red"); $result = array_unique($input); print_r($result); ?> The above example will output: Array ( [a] => green [0] => red [1] => blue ) <?php $input = array(4, "4", "3", 4, 3, "3"); $result = array_unique($input); var_dump($result); ?> The above example will output: array(2) { [0] => int(4) [2] => string(1) "3" }
array_map
Applies the callback to the elements of the given arrays
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()
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.
array_reverse <?php $input = array("php", 4.0, array("green", "red")); $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.
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.
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.
array_shift <?php $stack = array("orange", "banana", "apple", "raspberry"); $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.
array_unshift
Prepend one or more elements to the beginning of an array
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("orange", "banana"); array_unshift($queue, "apple", "raspberry"); print_r($queue); ?> The above example will output: Array ( [0] => apple [1] => raspberry [2] => orange [3] => banana )
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.
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.
array_slice <?php $input = array("a", "b", "c", "d", "e"); $output = array_slice($input, 2); // returns "c", "d", and "e" $output = array_slice($input, -2, 1); // returns "d" $output = array_slice($input, 0, 3); // returns "a", "b", and "c" // 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 )
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("red", "green", "blue", "yellow"); array_splice($input, 2); // $input is now array("red", "green") $input = array("red", "green", "blue", "yellow"); array_splice($input, 1, -1); // $input is now array("red", "yellow")
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.
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( "color" => "red", 2, 4); $array2 = array( "a", "b", "color" => "green", "shape" => "trapezoid",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 )
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.
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 (===).
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 "The 'first' element is in the array"; } ?> <?php $search_array = array('first' => null, 'second' => 4); // returns false isset($search_array['first']); // returns true array_key_exists('first', $search_array); ?>
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.
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("a" => 1, "b" => 1, "c" => 2); $trans = array_flip($trans); print_r($trans); ?> now $trans is: Array ( [1] => b [2] => c )
array_intersect_key() returns an array containing all the values of array1 which have matching keys that are present in all the arguments.
array_intersect_key
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.
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("a" => "green", "b" => "brown", "c" => "blue", "red"); $array2 = array("a" => "GREEN", "B" => "brown", "yellow", "red"); print_r(array_intersect_uassoc($array1, $array2, "strcasecmp")); ?> The above example will output: Array ( [b] => brown )
array_intersect_assoc
Computes the intersection of arrays with additional index check
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("a" => "green", "b" => "brown", "c" => "blue", "red"); $array2 = array("a" => "green", "yellow", "red"); $result_array = array_intersect_assoc($array1, $array2); print_r($result_array); ?> The above example will output: Array ( [a] => green )
array_intersect_assoc
In our example you see that only the pair "a" => "green" is present in both arrays and thus is returned. The value "red" is not returned because in $array1 its key is 0 while the key of "red" 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.
array_intersect_ukey
Computes the intersection of arrays using a callback function on the keys for comparison
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.
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("a" => "green", "b" => "brown", "c" => "blue", "red"); $array2 = array("a" => "GREEN", "B" => "brown", "yellow", "red"); print_r(array_uintersect($array1, $array2, "strcasecmp")); ?> The above example will output: Array ( [a] => green [b] => brown [0] => red )
array_uintersect_assoc
Computes the intersection of arrays with additional index check, compares data by a callback function
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("a" => "green", "b" => "brown", "c" => "blue", "red"); $array2 = array("a" => "GREEN", "B" => "brown", "yellow", "red"); print_r(array_uintersect_uassoc($array1, $array2, "strcasecmp", "strcasecmp")); ?> The above example will output: Array ( [a] => green [b] => brown )
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.
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.
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("a" => "green", "b" => "brown", "c" => "blue", "red"); $array2 = array("a" => "green", "yellow", "red"); $result = array_diff_uassoc($array1, $array2, "key_compare_func"); print_r($result); ?> The above example will output: Array ( [b] => brown [c] => blue [0] => red )
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.
array_diff_ukey
Computes the difference of arrays using a callback function on the keys for comparison
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.
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.
array_udiff_uassoc
Computes the difference of arrays with additional index check, compares data and indexes by a callback function
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().
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
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
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()
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
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
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
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()
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
CHAPTER 5 FUNCTIONS
Functions
Declaring and Calling Functions
Passing Arguments to Functions
Returning Values from Functions
Understanding Variable Scope
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
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
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
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
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
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
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
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
CHAPTER 6 HTML AN INTRODUCTION TO WEB FORMS
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
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.
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
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.
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.
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
BODY
<BODY> encloses the content that has to be displayed in the browser.
<p> tag encloses the paragraph.
Attribute
Attributes provide additional information to an HTML element.
Attributes always come in name/value pairs like this: name="value".
Attributes are always specified in the start tag of an HTML element.
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="0">
Attribute values should always be enclosed in quotes. Double style quotes are the most common, but single style quotes are also allowed.
Attribute
In some rare situations, like when the attribute value itself contains quotes, it is necessary to use single quotes:
name='John "ShotGun" Nelson'
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.
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.
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.
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
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
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
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.
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: < or <
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 character entity.
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.
Link
With the target attribute, you can define where the linked document will be opened.
<a href="http://www.IntelliBitz.com/"
target="_blank">Visit IntelliBitz!</a>
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.
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
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
Frames
The <frame> tag defines what HTML document to put into each frame
The "alt" 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 "alt" attribute for each image on a page, to improve the display
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.
<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.
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]
<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]
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.
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]
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]
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]
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]
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]
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]
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
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.
Lists and drop-down lists
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.
Image
<input type = “image”> is identical to <input type = “submit”>except thet instead of displaying a button it displays a specific image.
Hidden
Along with user editable data,HTML also allows to send uneditable hidden data to the server.
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
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.
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.
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
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.
CHAPTER 7 PHP AND WEB FORMS
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
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.
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
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.
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.
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.
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.
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.
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
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
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
Chapter Summary
Removing submitted HTML and JavaScript before displaying it.
Displaying default values for form elements.
Using helper functions to display form elements.
CHAPTER 8 PHP AND DATABASE
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
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
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
Connecting to a Database
Use require 'DB.php';
Use include in place of require if you want strict checking
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.
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.
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.
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.
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.
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); ?>
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.
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.
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()); } ?>
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.
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.
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.
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("Records deleted: %d
", mysql_affected_rows()); /* with a where clause that is never true, it should return 0 */ mysql_query('DELETE FROM mytable WHERE 0'); printf("Records deleted: %d
", mysql_affected_rows()); ?> The above example will output something similar to: Records deleted: 10 Records deleted: 0
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("UPDATE mytable SET used=1 WHERE id < 10"); printf ("Updated records: %d
", mysql_affected_rows()); mysql_query("COMMIT"); ?> The above example will output something similar to: Updated Records: 10
mysql_change_user
mysql_change_user — Change logged in user of the active connection
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.
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.
mysql_client_encoding
mysql_client_encoding — Returns the name of the character set
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.
mysql_client_encoding <?php $link = mysql_connect('localhost', 'mysql_user', 'mysql_password'); $charset = mysql_client_encoding($link); echo "The current character set is: $charset
"; ?> The above example will output something similar to: The current character set is: latin1
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.
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
mysql_connect
mysql_connect — Open a connection to a MySQL Server
The MySQL server. It can also include a port number. e.g. "hostname:port" or a path to a local socket e.g. ":/path/to/socket" 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.
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.
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.
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); ?>
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.
mysql_create_db() attempts to create a new database on the server associated with the specified link identifier.
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 "Database my_db created successfully
"; } else { echo 'Error creating database: ' . mysql_error() . "
"; } ?> The above example will output something similar to: Database my_db created successfully
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.
mysql_data_seek
Parameters
result
The result resource that is being evaluated. This result comes from a call to mysql_query().
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.
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 "DB Error, could not query the database
"; echo 'MySQL Error: ' . mysql_error(); exit; } while ($row = mysql_fetch_assoc($result)) { echo $row['foo']; } mysql_free_result($result); ?>
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.
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.
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 "Database my_db was successfully dropped
"; } else { echo 'Error dropping database: ' . mysql_error() . "
"; } ?>
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.
mysql_errno <?php $link = mysql_connect("localhost", "mysql_user", "mysql_password"); if (!mysql_select_db("nonexistentdb", $link)) { echo mysql_errno($link) . ": " . mysql_error($link). "
"; } mysql_select_db("kossu", $link); if (!mysql_query("SELECT * FROM nonexistenttable", $link)) { echo mysql_errno($link) . ": " . mysql_error($link) . "
"; } ?> The above example will output something similar to: 1049: Unknown database 'nonexistentdb' 1146: Table 'kossu.nonexistenttable' doesn't exist
mysql_error
Returns the text of the error message from previous MySQL operation
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.
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.
mysql_error <?php $link = mysql_connect("localhost", "mysql_user", "mysql_password"); mysql_select_db("nonexistentdb", $link); echo mysql_errno($link) . ": " . mysql_error($link). "
"; mysql_select_db("kossu", $link); mysql_query("SELECT * FROM nonexistenttable", $link); echo mysql_errno($link) . ": " . mysql_error($link) . "
"; ?> The above example will output something similar to: 1049: Unknown database 'nonexistentdb' 1146: Table 'kossu.nonexistenttable' doesn't exist
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.
mysql_escape_string
Parameters
unescaped_string
The string that is to be escaped.
Return Values
Returns the escaped string.
<?php $item = "Zak's Laptop"; $escaped_item = mysql_escape_string($item); printf("Escaped string: %s
", $escaped_item); ?> The above example will output: Escaped string: Zak's Laptop
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.
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.
mysql_fetch_array <?php mysql_connect("localhost", "mysql_user", "mysql_password") or die("Could not connect: " . mysql_error()); mysql_select_db("mydb"); $result = mysql_query("SELECT id, name FROM mytable"); while ($row = mysql_fetch_array($result, MYSQL_NUM)) { printf("ID: %s Name: %s", $row[0], $row[1]); } mysql_free_result($result); ?>
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.
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.
array_fetch_assoc <?php $conn = mysql_connect("localhost", "mysql_user", "mysql_password"); if (!$conn) { echo "Unable to connect to DB: " . mysql_error(); exit; } if (!mysql_select_db("mydbname")) { echo "Unable to select mydbname: " . mysql_error(); exit; } $sql = "SELECT id as userid, fullname, userstatus FROM sometable WHERE userstatus = 1"; $result = mysql_query($sql); if (!$result) { echo "Could not successfully run query ($sql) from DB: " . mysql_error(); exit; } if (mysql_num_rows($result) == 0) { echo "No rows found, nothing to print so am exiting"; exit; }
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.
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
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.
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("SELECT id,email FROM people WHERE id = '42'"); 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 )
Returns an object with properties that correspond to the fetched row and moves the internal data pointer ahead.
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.
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.
mysql_fetch_object <?php mysql_connect("hostname", "user", "password"); mysql_select_db("mydb"); $result = mysql_query("select * from mytable"); 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; ?>
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().
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.
mysql_fetch_row <?php $result = mysql_query("SELECT id,email FROM people WHERE id = '42'"); 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 ?>
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().
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.
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: "not_null", "primary_key", "unique_key", "multiple_key", "blob", "unsigned", "zerofill", "binary", "enum", "auto_increment" and "timestamp".
mysql_field_flags <?php $result = mysql_query("SELECT id,email FROM people WHERE id = '42'"); 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 )
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.
mysql_field_len <?php $result = mysql_query("SELECT id,email FROM people WHERE id = '42'"); 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; ?>
mysql_field_len <?php $result = mysql_query("SELECT id,email FROM people WHERE id = '42'"); 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; ?>
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.
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("Could not set $dbname: " . mysql_error()); } $res = mysql_query('select * from users', $link); echo mysql_field_name($res, 0) . "
"; echo mysql_field_name($res, 2); ?> The above example will output: user_id password
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.
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.
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.
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.
mysql_field_table <?php $result = mysql_query("SELECT name,comment FROM people,comments"); 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 ?>
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.
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 "int", "real", "string", "blob", and others as detailed in the » MySQL documentation.
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
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.
mysql_free_result <?php $result = mysql_query("SELECT id,email FROM people WHERE id = '42'"); 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']; ?>
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("MySQL client info: %s
", mysql_get_client_info()); ?> The above example will output something similar to: MySQL client info: 3.23.39
Describes the type of connection in use for the connection, including the server host name.
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.
mysql_host_info <?php $link = mysql_connect('localhost', 'mysql_user', 'mysql_password'); if (!$link) { die('Could not connect: ' . mysql_error()); } printf("MySQL host info: %s
", mysql_get_host_info()); ?> The above example will output something similar to: MySQL host info: Localhost via UNIX socket
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.
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("MySQL protocol version: %s
", mysql_get_proto_info()); ?> The above example will output something similar to: MySQL protocol version: 10
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.
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("MySQL server version: %s
", mysql_get_server_info()); ?> The above example will output something similar to: MySQL server version: 4.0.1-alpha
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.
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.
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.
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.
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("INSERT INTO mytable (product) values ('intelli')"); printf("Last inserted record has id %d
", mysql_insert_id()); ?>
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().
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.
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 . "
"; } ?> The above example will output something similar to: database1 database2 database3
This function is deprecated. It is preferable to use mysql_query() to issue a SQL SHOW COLUMNS FROM table [LIKE 'name'] statement instead.
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.
mysql_list_fields Alternate to deprecated mysql_list_fields() <?php $result = mysql_query("SHOW COLUMNS FROM sometable"); 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] => )
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.
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("%s %s %s %s %s
", $row["Id"], $row["Host"], $row["db"], $row["Command"], $row["Time"]); } mysql_free_result($result); ?> The above example will output something similar to: 1 localhost test Processlist 0 4 localhost mysql sleep 5
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.
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.
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 = "SHOW TABLES FROM $dbname"; $result = mysql_query($sql); if (!$result) { echo "DB Error, could not list tables
"; echo 'MySQL Error: ' . mysql_error(); exit; } while ($row = mysql_fetch_row($result)) { echo "Table: {$row[0]}
"; } mysql_free_result($result); ?>
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.
mysql_num_fields <?php $result = mysql_query("SELECT id,email FROM people WHERE id = '42'"); if (!$result) { echo 'Could not run query: ' . mysql_error(); exit; } /* returns 2 because id,email === two fields */ echo mysql_num_fields($result); ?>
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().
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.
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'.
mysql_pconnect
Parameters
server
The MySQL server. It can also include a port number. e.g. "hostname:port" or a path to a local socket e.g. ":/path/to/socket" 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.
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.
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.
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.
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); ?>
mysql_real_escape_string
Escapes special characters in a string for use in a SQL statement
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,
,
, , ', " and x1a.
This function must always (with few exceptions) be used to make data safe before sending a query to MySQL .
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.
mysql_real_escape_string <?php // Connect $link = mysql_connect('mysql_host', 'mysql_user', 'mysql_password') OR die(mysql_error()); // Query $query = sprintf("SELECT * FROM users WHERE user='%s' AND password='%s'", mysql_real_escape_string($user), mysql_real_escape_string($password)); ?>
mysql_stat
Get current system status
string mysql_stat ( [resource $link_identifier] )
mysql_stat() returns the current server status.
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.
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 )
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)
mysql_tablename
Return Values
The name of the table on success, or FALSE on failure.
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.
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.
mysql_thread_id <?php $link = mysql_connect('localhost', 'mysql_user', 'mysql_password'); $thread_id = mysql_thread_id($link); if ($thread_id){ printf("current thread id is %d
", $thread_id); } ?> The above example will output something similar to: current thread id is 73
mysql_unbuffered_query
Send an SQL query to MySQL, without fetching and buffering the result rows
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.
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.
CHAPTER 10 PHP AND PEAR DB
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.
PHP databse abstraction layer
Web browser
Apache/IIS
PHP engine
Pear DB
DB extension
Mysql ,sqlite
DB server
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
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
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.
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.
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.
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.
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.
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.
CHAPTER 11 COOKIES AND SESSIONS
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.
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.
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 .
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.
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.
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
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()
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
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
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
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.
CHAPTER 12 WORKING WITH DATES AND TIMES
Handling Dates And Times
Displaying the Date or Time.
Parsing a Date or Time.
Dates and Times in Forms.
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.
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.
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.
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.
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.
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.
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
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.
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 ( ).
Chapter summary
Making an epoch timestamp with strtotime().
Displaying form elements to allow for date or time input.
CHAPTER 13 DATE AND TIME FUNTIONS
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.
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)
date_sunrise() returns the sunrise time for a given day (specified as a timestamp) and location.
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
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.
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
date_sunrise <?php /* calculate the sunrise time for Lisbon, Portugal Latitude: 38.4 North Longitude: 9 West Zenith ~= 90 offset: +1 GMT */ echo date("D M d Y"). ', 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
date_sunset
Returns time of sunset for a given day and location
date_sunset() returns the sunset time for a given day (specified as a timestamp) and location.
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.
date_sunset <?php /* calculate the sunset time for Lisbon, Portugal Latitude: 38.4 North Longitude: 9 West Zenith ~= 90 offset: +1 GMT */ echo date("D M d Y"). ', 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
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] )
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.
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.
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.
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
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.
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.
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 )
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.
gettimeofday
Parameters
return_float
When set to TRUE, a float instead of an array is returned.
Return Values
By default an array is returned. If return_float is set, then a float is returned.
Array keys:
"sec" - seconds since the Unix Epoch
"usec" - microseconds
"minuteswest" - minutes west of Greenwich
"dsttime" - type of dst correction
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
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).
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.
gmdate When run in Finland (GMT +0200), the first line below prints "Jan 01 1998 00:00:00", while the second prints "Dec 31 1997 22:00:00". <?php echo date("M d Y H:i:s", mktime(0, 0, 0, 1, 1, 1998)); echo gmdate("M d Y H:i:s", mktime(0, 0, 0, 1, 1, 1998)); ?>
CHAPTER 14 CALENDER FUNCTIONS
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!
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 "There was $num days in August 2003"; ?>
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 )
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.
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 )
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.
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.
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).
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 ?>
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.
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.
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)
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.
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
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.
JDToGregorian
JDToGregorian — Converts Julian Day Count to Gregorian date
string jdtogregorian ( int $julianday )
Converts Julian Day Count to a string containing the Gregorian date in the format of "month/day/year".
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.
JDToJulian
JDToJulian — Converts a Julian Day Count to a Julian Calendar Date
string jdtojulian ( int $julianday )
Converts Julian Day Count to a string containing the Julian Calendar Date in the format of "month/day/year".
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).
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.
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.
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.
CHAPTER 15 CLASSES AND OBJECTS
Classes and Objects
Object basics.
Defining classes
Creating new objects.
Creating constructors.
Accessing properties and methods.
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.
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.
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.
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.
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.
Creating new object
We can invokeor acces the member variables and functions in the class using -> operator
$objectname ->functionname();
__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.
__autoload()
You can define __ autoload function that automatically be called any time a new object attempts to be instantiated.
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
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.
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.
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.
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.
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.
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 ( ).
Chapter summary
Making an epoch timestamp with strtotime().
Displaying form elements to allow for date or time input.
CHAPTER 16 CLASSES AND OBJECTS FUNCTIONS
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).
Classes objects <?php // base class with member properties and methods class Vegetable { var $edible; var $color; function Vegetable($edible, $color="green") { $this->edible = $edible; $this->color = $color; } function is_edible() { return $this->edible; } function what_color() { return $this->color; } } // end of class Vegetable
Classes objects // extends the base class class Spinach extends Vegetable { var $cooked = false; function Spinach() { $this->Vegetable(true, "green"); } function cook_it() { $this->cooked = true; } function is_cooked() { return $this->cooked; } } // end of class Spinach ?>
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.
call_user_method
call_user_method — Call a user method on an specific object [deprecated]
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.
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("Unable to load class: $class", E_USER_WARNING); } } if (class_exists('MyClass')) { $myclass = new MyClass(); } ?>
get_class_methods
get_class_methods — Gets the class methods' names
array get_class_methods ( mixed $class_name )
Gets the class methods names.
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.
get_class_methods $class_methods = get_class_methods('myclass'); // or $class_methods = get_class_methods(new myclass()); foreach ($class_methods as $method_name) { echo "$method_name
"; } ?> 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); }
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.
get_class_var $my_class = new myclass(); $class_vars = get_class_vars(get_class($my_class)); foreach ($class_vars as $name => $value) { echo "$name : $value
"; } ?> 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 = "xyz"; var $var3 = 100; private $var4; // PHP 5 // constructor function myclass() { // change some properties $this->var1 = "foo"; $this->var2 = "bar"; return true; } }
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.
get_class <?php class foo { function foo() { // implements some logic } function name() { echo "My name is " , get_class($this) , "
"; } } // create an object $bar = new foo(); // external call echo "Its name is " , get_class($bar) , "
"; // internal call $bar->name(); ?> The above example will output: Its name is foo My name is foo
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.
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 )
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.
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 )
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.
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("x" => $this->x, "y" => $this->y, "label" => $this->label); } } // "$label" 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("point #1"); print_r(get_object_vars($p1)); ?>
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.
get_parent_class [email_address] <?php class dad { function dad() { // implements some logic } } class child extends dad { function child() { echo "I'm " , get_parent_class($this) , "'s son
"; } } class child2 extends dad { function child2() { echo "I'm " , get_parent_class('child2') , "'s son too
"; } } $foo = new child(); $bar = new child2(); ?> The above example will output: I'm dad's son I'm dad's son too
interface_exists
interface_exists — Checks if the interface has been defined
Returns TRUE if the interface given by interface_name has been defined, FALSE otherwise.
interface_exists <?php // Check the interface exists before trying to use it if (interface_exists('MyInterface')) { class MyClass implements MyInterface { // Methods } } ?>
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
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 "yes, $WF is still a WidgetFactory
"; } ?> <?php if ($WF instanceof WidgetFactory) { echo 'Yes, $WF is a WidgetFactory'; } ?>
is_subclass_of
is_subclass_of — Checks if the object has this class as one of its parents
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.
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 "yes, $WFC is a subclass of WidgetFactory
"; } else { echo "no, $WFC is not a subclass of WidgetFactory
"; } if (is_subclass_of($WF, 'WidgetFactory')) { echo "yes, $WF is a subclass of WidgetFactory
"; } else { echo "no, $WF is not a subclass of WidgetFactory
"; }
is_sub_class_of // usable only since PHP 5.0.3 if (is_subclass_of('WidgetFactory_Child', 'WidgetFactory')) { echo "yes, WidgetFactory_Child is a subclass of WidgetFactory
"; } else { echo "no, WidgetFactory_Child is not a subclass of WidgetFactory
"; } ?> 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
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.
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(); ?>
CHAPTER 17 WORKING WITH FILES
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
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
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
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.
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
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
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()
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 ()
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
CHAPTER 18 GETTEXT FUNCTIONS
GETTEXT FUNCTIONS
The gettext functions implement an NLS (Native Language Support) API which can be used to internationalize your PHP applications.
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.
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.
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.
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.
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.
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.
CHAPTER 19 REGULAR EXPRESSION
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.
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).
Regex can be used for
Finding doubled words
Checking inputs from web forms
Changing date formats
Finding incorrect case.
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.
Metacharacters
Some characters do not match themselves and are called metacharacters.
.^*+?{[]}|() is the complete list of metacharacters.
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”
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.
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]
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 “.”
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.
Quantifier
A quantifier after a character or group specifies how often that preceding expression is allowed to occur.
The most common quantifiers are ?,* and +
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.
Quantifier
+ The plus sign indicates that there is at least 1 of the previous expression
For example “go+gle “ matches gogle,google,gooogle etc
Metacharacter
{m,n} specifies occurrence of the character minimum of m times and maximum of n times.
“ab{2,3}” matches abb or abbb
CHAPTER 20 DEBUGGING
Debugging
Controlling where errors appear
Fixing parse errors
Inspecting program data
Fixing database errors
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
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
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
1–10 of 23 previous next Post a comment
1–10 of 23 previous next