PHP 46349 23034.odp
PHP 46349 23034.odp
Training Division
168, Medavakkam Main Road
Madipakkam, Chennai 91.
PH: +91 044 2247 5106
www.intellibitz.com
[email protected]
www.intellibitz.com [email protected]
PHP WEB
PROGRAMMING.
www.intellibitz.com [email protected]
CHAPTER 1
www.intellibitz.com [email protected]
PHP First Steps - Overview
●
PHP and the WWW
●
PHP as a server-side language
●
What's so great about PHP?
●
PHP in action
●
PHP basics
www.intellibitz.com [email protected]
PHP and the Web
●
www.intellibitz.com Is typed in firefox
●
Firefox sends a message over the internet to the computer
named www.intellibitz.com
●
Apache, a program running on www.intellibitz.com, gets the
message and asks the PHP interpreter, another program
running on the www.intellibitz.com computer, “what
does /index.php look like?”
www.intellibitz.com [email protected]
PHP and the Web
●
The PHP interpreter reads the file /var/www/html/index.php
from disk drive
●
The PHP interpreter runs the commands in index.php,
possibly exchanging data with a database program such
as MySQL
●
The PHP interpreter takes the index.php program output
and sends it back to Apache as answer
www.intellibitz.com [email protected]
PHP and the Web
●
Apache sends the page contents it got from the PHP
interpreter back to your computer over the Internet in
response to Firefox
●
Firefox displays the page on the screen, following the
instructions of the HTML tags in the page
www.intellibitz.com [email protected]
PHP – a server-side language
●
PHP runs on the web server
●
Javascript and Flash in contrast, are client-side because
they run on a web client
●
The instructions in a PHP program cause the PHP
interpreter on a web server to output a web page. The
instructions in Javascript cause Firefox to run browser
commands.
www.intellibitz.com [email protected]
What's So Great About PHP?
●
PHP is free
●
PHP is cross-platform
●
PHP is widely used
●
PHP hides its complexity
●
PHP is built for Web Programming
www.intellibitz.com [email protected]
PHP in action
●
The PHP interpreter runs the commands between <?php ?
> tags
●
PHP processing form data via $_POST
●
String syntax called a 'here document'
●
Using PHP internal library functions like number_format ()
●
Displaying infromation from a database
www.intellibitz.com [email protected]
Basic Rules of PHP Programs
●
Start and End Tags
●
Whitespace and Case-Sensitivity
●
Comments
www.intellibitz.com [email protected]
Chapter Summary
●
PHP's usage by a web server to create a response to send
back to browser
●
PHP as a server-side language, contrasting with a
Javascript a client-side language
●
PHP is free, cross-platform, widely-used
●
PHP basics, program structure, process form, and talk to
databases
www.intellibitz.com [email protected]
CHAPTER 2
www.intellibitz.com [email protected]
Working with Text and Numbers
●
Defining Text Strings
●
Validating and formatting text
●
Manipulating Text
●
Numbers
●
Arithmetic Operators
●
Variables
●
Putting variables inside strings
www.intellibitz.com [email protected]
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
www.intellibitz.com [email protected]
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.
www.intellibitz.com [email protected]
Manipulating Text
●
Validating string using trim () and strlen ()
●
To compare two strings, use the equality operator (==)
●
Use strcasecmp () to compare strings ignoring case
www.intellibitz.com [email protected]
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 ()
www.intellibitz.com [email protected]
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().
www.intellibitz.com [email protected]
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
www.intellibitz.com [email protected]
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.
www.intellibitz.com [email protected]
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.
www.intellibitz.com [email protected]
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.
www.intellibitz.com [email protected]
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
www.intellibitz.com [email protected]
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.
www.intellibitz.com [email protected]
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
www.intellibitz.com [email protected]
String functions
●
strrev
Reverse a string
●
●
chunk_split — Split a string into smaller chunks
●
string chunk_split ( string $body [, int
$chunklen [, string $end]] )
●
string convert_cyr_string ( string $str, string $from, string
$to )
www.intellibitz.com [email protected]
String functions
●
strstr
●
Find first occurrence of a string
– string strstr ( string $haystack, string
$needle )
●
Returns part of haystack string from the first
occurrence of needle to the end of haystack.
●
If needle is not found, returns FALSE.
●
If needle is not a string, it is converted to an
integer and applied as the ordinal value of a
character.
●
Stristr() - case insensitive
●
Strchr
●
Alias of strstr()
www.intellibitz.com [email protected]
String functions
●
Strtok()
●
string strtok ( string $str, string $token )
– strtok() splits a string (str) into smaller
strings (tokens), with each token being
delimited by any character from token.
●
Strtr()
●
string strtr ( string $str, string $from, string $to )
– This function returns a copy of str,
translating all occurrences of each
character in from to the corresponding
character in to.
www.intellibitz.com [email protected]
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.
www.intellibitz.com [email protected]
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.
www.intellibitz.com [email protected]
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).
●
addcslashes(),stripcslashes(), stripslashes().
●
str_shuffle
●
Randomly shuffles a string
●
str_split
●
Convert a string to an array
www.intellibitz.com [email protected]
String functions
●
string htmlentities ( string $string [, int $quote_style [, string
$charset]] )
●
Convert all applicable characters to HTML
entities
●
ENT_COMPATWill 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.
www.intellibitz.com [email protected]
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_QUOTES is set.
●
'<' (less than) becomes '<'
●
'>' (greater than) becomes '>'
www.intellibitz.com [email protected]
String functions
htmlspecialchars_decode
●
www.intellibitz.com [email protected]
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.
www.intellibitz.com [email protected]
String functions
●
Metaphone
Calculate the metaphone key of a string.
●
●
quoted_printable_decode
●
Convert a quoted-printable string to an 8 bit
string
www.intellibitz.com [email protected]
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.
www.intellibitz.com [email protected]
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.
www.intellibitz.com [email protected]
String functions
●
wordwrap
Wraps a string to a given number of characters
–
using a string break character
●
string wordwrap ( string $str [, int $width [, string
$break [, bool $cut]]] )
– Returns a string with str wrapped at the column
number specified by the optional width
parameter. The line is broken using the
(optional) break parameter.
– wordwrap() will automatically wrap at column
75 and break using '\n' (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
www.intellibitz.com [email protected]
String functions
●
vfprintf
●
Write a formatted string to a stream
●
vprintf
●
Output a formatted string
●
vsprintf
●
Return a formatted string
– string vsprintf ( string $format, array
$args )
www.intellibitz.com [email protected]
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).
www.intellibitz.com [email protected]
Numbers
●
Numbers – floating point and decimals
●
Arithmetic operators
●
+, -, *, /, %
●
Operator precedence
●
Grouping operations inside parentheses, will execute whats
inside the parentheses first
www.intellibitz.com [email protected]
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.
www.intellibitz.com [email protected]
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
www.intellibitz.com [email protected]
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)
www.intellibitz.com [email protected]
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.
www.intellibitz.com [email protected]
Number functions
●
$maximum = max ($array);
●
$minimum = min($array);
●
$newNumber = base_convert($number,$oldbase,
$newbase);
●
This function converts a number in any base ,
up to base 36,to a number in any other
base,again upto base 36.
●
$result = rand($min,$max)
●
Generates random numbers between $min
and $max
www.intellibitz.com [email protected]
Number functions
●
$result = exp($power);
●
The function returns the natural base 'e'
raised to the specified power.
●
$result = log($number,$base);
●
This function returns the logarithm of the
specified number to the base provided.
www.intellibitz.com [email protected]
Number functions
●
sin,cos,tan,sinh,cosh,tanh,asin,asinh,acos,
acosh,atan,atanh.
●
Float atan2(float $y,float $x)
●
This function calculates the arc tangent of the
two variables x and y. It is similar to
calculating the arc tangent of y / x, except
that the signs of both arguments are used to
determine the quadrant of the result.
●
The function returns the result in radians,
which is between -PI and PI (inclusive).
www.intellibitz.com [email protected]
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.
www.intellibitz.com [email protected]
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.
www.intellibitz.com [email protected]
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 ()
www.intellibitz.com [email protected]
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
www.intellibitz.com [email protected]
Chapter Summary
●
Naming variables appropriately
●
Using combined operators with variables
●
Using increment and decrement operators with variables
●
Interpolating variables in strings
www.intellibitz.com [email protected]
CHAPTER 3
www.intellibitz.com [email protected]
Making Decisions and Looping
●
Understanding true and false
●
Making Decisions
●
Building Complicated Decisions
●
Repeating Yourself
www.intellibitz.com [email protected]
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
www.intellibitz.com [email protected]
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.
www.intellibitz.com [email protected]
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
www.intellibitz.com [email protected]
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
www.intellibitz.com [email protected]
If statements
●
Often you'd want to have more than one <?php
statement to be executed conditionally. if ($a > $b)
●
In such case there's no need to wrap each
statement with an if clause. Instead, you echo "a is bigger than b";
?>
www.intellibitz.com [email protected]
If else statement
●
Often you'd want to execute a statement <?php
if a certain condition is met, and a
if ($a > $b) {
different statement if the condition is
not met. This is what else is for. echo "a is bigger than b";
●
else extends an if statement to execute } else {
a statement in case the expression in
the if statement evaluates to FALSE. echo "a is NOT bigger than b";
●
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
www.intellibitz.com [email protected]
else if
●
elseif, as its name suggests, is a <?php
combination of if and else.
if ($a > $b) {
●
It extends an if statement to execute a
different statement in case the original if echo "a is bigger than b";
expression evaluates to FALSE. } elseif ($a == $b) {
●
However, unlike else, it will execute that
alternative expression only if the elseif echo "a is equal to b";
conditional expression evaluates to } else {
TRUE.
echo "a is smaller than b";
?>
www.intellibitz.com [email protected]
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.
www.intellibitz.com [email protected]
while()
●
While statements tells PHP to execute the nested
while (expr)
statement(s) repeatedly, as long as the while statement
expression evaluates to TRUE.
●
The value of the expression is checked each <?php
time at the beginning of the loop, so even if $i = 1;
this value changes during the execution of the
nested statement(s), execution will not stop while ($i <= 10) {
until the end of the iteration (each time PHP echo $i++;
runs the statements in the loop is one
iteration). }
●
Sometimes, if the while expression evaluates to /* the printed value would be $i
FALSE from the very beginning, the nested before the increment (post
statement(s) won't even be run once. increment) */
?>
www.intellibitz.com [email protected]
do while
●
do-while loops are very similar to while loops, <?php
except the truth expression is checked at the
$i = 0;
end of each iteration instead of in the beginning.
●
The main difference from regular while loops is that do {
the first iteration of a do-while loop is echo $i;
guaranteed to run as the truth expression is only
checked at the end of the iteration). } while ($i > 0);
●
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.
www.intellibitz.com [email protected]
for statement
●
A variable can be initialised once for (initialise;
test condition;
unconditionally at the beginning of the loop. increment value)
●
In the beginning of each iteration, test condition statement
is checked. If it evaluates to TRUE, the loop
continues and the nested statement(s) are for ($i = 1; $i <= 10; $i++) {
executed. If it evaluates to FALSE, the echo $i;
execution of the loop ends.
}
●
At the end of each iteration, increment value is
evaluated (executed). for ($i = 1; ; $i++) {
if ($i > 10) {
break;
}
echo $i;
}
www.intellibitz.com [email protected]
for loop
●
Each of the expressions can be empty or
$i = 1;
contain multiple expressions separated by
commas. for (; ; ) {
●
Comma separated expressions in test
if ($i > 10) {
condition are treated similarly to being
separated by the || operator but has a lower break;
precedence than ||. expr2 being empty
}
means the loop should be run indefinitely
(PHP implicitly considers it as TRUE, like echo $i;
C). $i++;
●
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 for ($i = 1, $j = 0; $i <= 10; $j
using the for truth expression. += $i, print $i, $i++);
www.intellibitz.com [email protected]
foreach loop
●
PHP 4 introduced a foreach construct, much like Perl
●
This simply gives an easy way to iterate over arrays.
●
foreach works only on arrays, and will issue an error when you try to use
it on a variable with a different data type or an uninitialized variable.
●
There are two syntaxes; the second is a minor but useful extension of the
first:
www.intellibitz.com [email protected]
foreach
●
The first form loops over the array given by
array_expression. On each loop, the value of <?php
the current element is assigned to $value and $arr = array(1, 2, 3, 4);
the internal array pointer is advanced by one
foreach ($arr as &$value) {
(so on the next loop, you'll be looking at the
next element). $value = $value * 2;
●
The second form does the same thing, except
}
that the current element's key will be assigned
to the variable $key on each loop. // $arr is now array(2, 4, 6, 8)
●
you can easily modify array's elements by
foreach($arr as $key =>$val){
preceding $value with &. This will assign
reference instead of copying the value. print”$key=$val”;
?>
www.intellibitz.com [email protected]
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.
www.intellibitz.com [email protected]
break
$i = 0; while (++$i) {
●
break ends execution of the current
for, foreach, while, do-while or switch ($i) {
switch structure. case 5:
●
break accepts an optional numeric
echo "At 5<br />\n";
argument which tells it how many
nested enclosing structures are to break 1; /* Exit only the switch. */
be broken out of.
case 10:
echo "At 10; quitting<br />\n";
break 2; /* Exit the switch and the
while. */
default:
break;
}
www.intellibitz.com [email protected]
}
continue
$i = 0;
●
continue is used within looping
while ($i++ < 5) {
structures to skip the rest of the
current loop iteration and continue echo "Outer<br />\n";
execution at the condition while (1) {
evaluation and then the beginning
of the next iteration. echo "Middle<br />\n";
●
Note that in PHP the switch while (1) {
statement is considered a looping
echo "Inner<br />\n";
structure for the purposes of
continue. continue 3;
●
continue accepts an optional numeric
}
argument which tells it how many
levels of enclosing loops it should echo "This never gets output.<br />\n";
skip to the end of. }
echo "Neither does this.<br />\n";
}
www.intellibitz.com [email protected]
switch
<?php
●
The switch statement is similar to a series of
IF statements on the same expression. In switch ($i) {
many occasions, you may want to
case 0:
compare the same variable (or
expression) with many different values, echo "i equals 0";
and execute a different piece of code break;
depending on which value it equals to.
This is exactly what the switch statement case 1:
is for. echo "i equals 1";
●
Note that unlike some other languages, the
break;
continue statement applies to switch and
acts similar to break. If you have a switch case 2:
inside a loop and wish to continue to the echo "i equals 2";
next iteration of the outer loop, use
continue 2. break;
}
www.intellibitz.com [email protected]
?>
switch
●
The switch statement executes line by line ?php
(actually, statement by statement).
switch ($i) {
●
In the beginning, no code is executed. Only
when a case statement is found with a case 0:
value that matches the value of the switch echo "i equals 0";
expression does PHP begin to execute
the statements. case 1:
●
PHP continues to execute the statements echo "i equals 1";
until the end of the switch block, or the
first time it sees a break statement. case 2:
●
Thus, it is important not to forget break echo "i equals 2";
statements to avoid mistakes.
}
?>
www.intellibitz.com [email protected]
Alternative syntax
<?php
●
PHP offers an alternative <?php if ($a == 5): ?>
syntax for some of its if ($a == 5):
A is equal to 5
control structures; namely, echo "a equals 5";
if, while, for, foreach, and <?php endif; ?>
echo "...";
switch. In each case, the
basic form of the alternate elseif ($a == 6):
syntax is to change the
echo "a equals 6";
opening brace to a colon
(:) and the closing brace echo "!!!";
to endif;, endwhile;,
else:
endfor;, endforeach;, or
endswitch;, respectively. echo "a is neither 5 nor 6";
endif;
?>
www.intellibitz.com [email protected]
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.
www.intellibitz.com [email protected]
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).
www.intellibitz.com [email protected]
require()
●
The require() statement includes <?php
require $somefile;
require ('somefile.txt');
?>
www.intellibitz.com [email protected]
include()
●
The include() statement includes and evaluates the specified file.
●
The difference between include() and require() The two constructs are
identical in every way except how they handle failure.
●
They both produce a Warning, but require() results in a Fatal Errorand
stops execution.
●
include() does not behave this way, the script will continue regardless.
●
use require() if you want a missing file to halt processing of the page.
www.intellibitz.com [email protected]
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.
www.intellibitz.com [email protected]
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)
?>
www.intellibitz.com [email protected]
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.
www.intellibitz.com [email protected]
declare
●
The declare construct is used to set declare (directive)
statement
execution directives for a block of code.
The syntax of declare is similar to the
<?php
syntax of other flow control constructs
●
A tick is an event that occurs for every N // these are the same:
low-level statements executed by the
// you can use this:
parser within the declare block.
●
The value for N is specified using ticks=N declare(ticks=1) {
within the declare blocks's directive
// entire script here
section.
●
The event(s) that occur on each tick are }
specified using the // or you can use this:
register_tick_function()
declare(ticks=1);
// entire script here
?>
www.intellibitz.com [email protected]
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.
www.intellibitz.com [email protected]
<?php
ticks // Set up a tick handler
// A function that records the time when it is called
register_tick_function("profile");
function profile($dump = FALSE) // Initialize the function before the declare block
{ profile();
static $profile; // Run a block of code, throw a tick every
// Return the times stored in profile, then erase it
2nd statement
if ($dump) { declare(ticks=2) {
$temp = $profile; for ($x = 1; $x < 50; ++$x) {
unset($profile); echo similar_text(md5($x), md5($x*$x)), "<br />;";
return $temp; }
} }
$profile[] = microtime(); // Display the data stored in the profiler
} print_r(profile(TRUE));
www.intellibitz.com [email protected]
?>
Building Complicated Decisions
●
Complicated expressions can be put together with
comparison and logical operators
●
Beware of assignment versus comparison
●
Beware of floating-point comparison
●
Strings are compared like dictionary lookup
●
Beware of strings containing numbers
●
Use strcmp() to compare like dictionary for strings
containing numbers
www.intellibitz.com [email protected]
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
www.intellibitz.com [email protected]
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
www.intellibitz.com [email protected]
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
www.intellibitz.com [email protected]
Chapter Summary
●
Comparing two floating-point numbers with abs()
●
Comparing two strings with operators
●
Comparing two strings with strcmp() or strcasecmp()
●
Using the negation operator (!) in test expressions
www.intellibitz.com [email protected]
Chapter Summary
●
Using the logical operators (&& and ||) to build more
complicated test expressions
●
Repeating a code block with while ()
●
Repeating a code block with for ()
www.intellibitz.com [email protected]
CHAPTER 4
www.intellibitz.com [email protected]
Working with Arrays
●
Creating an Array
●
Creating a Numeric Array
●
Looping through Arrays
●
Modifying Arrays
●
Sorting Arrays
●
Using Multidimensional Arrays
www.intellibitz.com [email protected]
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
www.intellibitz.com [email protected]
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
www.intellibitz.com [email protected]
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
www.intellibitz.com [email protected]
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
www.intellibitz.com [email protected]
Looping through Arrays
●
Use array_key_exists(), to check for an element with a
certain key
●
Use in_array(), to check for an element with a particular
value
●
in_array is case-sensitive
●
Use array_search to find the element key for a given
element value
www.intellibitz.com [email protected]
array()
●
Create an array <?php
●
array array ( [mixed $...] ) $fruits = array (
●
Returns an array of the
parameters. The parameters "fruits" => array("a" => "orange", "b" =>
can be given an index with the "banana", "c" => "apple"),
=> operator. "numbers" => array(1, 2, 3, 4, 5, 6),
"holes" => array("first", 5 => "second",
"third")
);
?>
www.intellibitz.com [email protected]
array
Array
<?php (
$array = array(1, 1, 1, 1, 1, 8 => 1, [0] => 1
4 => 1, 19, 3 => 13);
[1] => 1
print_r($array);
[2] => 1
?>
[3] => 13
[4] => 1
[8] => 1
[9] => 19
www.intellibitz.com [email protected]
array()
1based index with array()
<?php <?php
$firstquarter = array(1 => 'January', 'February',
'March');
$foo = array('bar' =>
'baz'); print_r($firstquarter);
echo "Hello ?>
{$foo['bar']}!"; // Hello baz!
The above example will output:
Array
(
?> [1] => January
[2] => February
[3] => March
)
www.intellibitz.com [email protected]
sort
●
Sort an array <?php
●
Description
●
bool sort ( array &$array [, int $fruits = array("lemon", "orange",
$sort_flags] ) "banana", "apple");
●
This function sorts an array. Elements sort($fruits);
will be arranged from lowest to
highest when this function has foreach ($fruits as $key => $val) {
completed. echo "fruits[" . $key . "] = " . $val .
●
Note: This function assigns new keys "\n";
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 The above example will output:
on failure. fruits[0] = apple
fruits[1] = banana
fruits[2] = lemon
fruits[3] = orange
www.intellibitz.com [email protected]
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.
www.intellibitz.com [email protected]
rsort
<?php
$fruits = array("lemon", "orange", "banana", "apple");
rsort($fruits);
foreach ($fruits as $key => $val) {
echo "$key = $val\n";
?>
The above example will output:
0 = orange
1 = lemon
2 = banana
3 = apple
www.intellibitz.com [email protected]
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.
www.intellibitz.com [email protected]
asort
<?php
$fruits = array("d" => "lemon", "a" => "orange",
"b" => "banana", "c" => "apple");
asort($fruits);
foreach ($fruits as $key => $val) {
echo "$key = $val\n";
The fruits have been sorted in
alphabetical order, and the index
}
associated with each element has
?> been maintained.
The above example will output:
c = apple
b = banana
d = lemon
a = orange
www.intellibitz.com [email protected]
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.
www.intellibitz.com [email protected]
arsort
<?php
$fruits = array("d" => "lemon", "a" => "orange",
"b" => "banana", "c" => "apple");
arsort($fruits);
foreach ($fruits as $key => $val) {
echo "$key = $val\n";
} The fruits have been sorted in reverse
?> alphabetical order, and the index
associated with each element has been
The above example will output:
maintained.
a = orange
d = lemon
b = banana
c = apple
www.intellibitz.com [email protected]
ksort
●
Sort an array by key
<?php
●
bool ksort ( array &$array [, int $sort_flags] )
●
Sorts an array by key, maintaining key to $fruits = array("d"=>"lemon", "a"=>"orange",
data correlations. This is useful mainly
for associative arrays. "b"=>"banana", "c"=>"apple");
Returns TRUE on success or FALSE on
ksort($fruits);
●
failure.
foreach ($fruits as $key => $val) {
echo "$key = $val\n";
?>
The above example will output:
a = orange
b = banana
c = apple
d = lemon
www.intellibitz.com [email protected]
krsort
●
Sort an array by key in reverse order
<?php
●
bool krsort ( array &$array [, int
$sort_flags] ) $fruits = array("d"=>"lemon", "a"=>"orange",
●
●
Sorts an array by key in reverse order, "b"=>"banana", "c"=>"apple");
maintaining key to data correlations.
krsort($fruits);
This is useful mainly for associative
arrays. foreach ($fruits as $key => $val) {
●
●
Returns TRUE on success or FALSE on echo "$key = $val\n";
failure.
●
}
●
?>
The above example will output:
d = lemon
c = apple
b = banana
a = orange
www.intellibitz.com [email protected]
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:
●
Returns TRUE on success or FALSE on failure.
●
natcasesort -- case insensitive.
www.intellibitz.com [email protected]
<?php
$array1 = $array2 = array("img12.png", natsort
"img10.png", "img2.png", "img1.png");
The above example will output:
www.intellibitz.com [email protected]
usort
●
Sort an array by values using a user-defined comparison function
●
Description
●
bool usort ( array &$array, callback $cmp_function )
●
●
This function will sort an array by its values using a user-supplied
comparison function. If the array you wish to sort needs to be sorted
by some non-trivial criteria, you should use this function.
●
●
The comparison function must return an integer less than, equal to, or
greater than zero if the first argument is considered to be
respectively less than, equal to, or greater than the second.
www.intellibitz.com [email protected]
<?php
function cmp($a, $b)
{
usort
if ($a == $b) {
$a = array(3, 2, 5, 6, 1);
return 0;
}
usort($a, "cmp");
return ($a < $b) ? 1 : 1;
}
foreach ($a as $key => $value) {
echo "$key: $value\n";
?>
The above example will output:
0: 1
1: 2
2: 3
3: 5
4: 6
www.intellibitz.com [email protected]
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.
www.intellibitz.com [email protected]
uasort
●
Sort an array with a user-defined comparison function and maintain
index association
●
bool uasort ( array &$array, callback $cmp_function )
●
This function sorts an array such that array indices maintain their
correlation with the array elements they are associated with. This is
used mainly when sorting associative arrays where the actual
element order is significant. The comparison function is user-
defined.
●
Returns TRUE on success or FALSE on failure.
www.intellibitz.com [email protected]
uksort
●
Sort an array by keys using a user-defined comparison function
●
bool uksort ( array &$array, callback $cmp_function )
●
●
uksort() will sort the keys of an array using a user-supplied comparison
function. If the array you wish to sort needs to be sorted by some
non-trivial criteria, you should use this function.
●
●
Function cmp_function should accept two parameters which will be
filled by pairs of array keys. The comparison function must return an
integer less than, equal to, or greater than zero if the first argument
is considered to be respectively less than, equal to, or greater than
the second.
●
●
Returns TRUE on success or FALSE on failure.
www.intellibitz.com [email protected]
<?php
function cmp($a, $b)
uksort
{
$a = array("John" => 1, "the Earth" => 2, "an apple" => 3,
$a = ereg_replace('^(a|an|the) ', '', $a);
"a banana" => 4);
$b = ereg_replace('^(a|an|the) ', '', $b);
return strcasecmp($a, $b);
uksort($a, "cmp");
}
foreach ($a as $key => $value) {
echo "$key: $value\n";
?> The above example will output:
an apple: 3
a banana: 4
the Earth: 2
John: 1
www.intellibitz.com [email protected]
list
<?php
●
Assign variables as if they were an
array $info = array('coffee', 'brown',
●
void list ( mixed $varname, mixed $... ) 'caffeine');
●
●
Like array(), this is not really a // Listing all the variables
function, but a language construct.
list() is used to assign a list of list($drink, $color, $power) = $info;
variables in one operation. echo "$drink is $color and $power
●
makes it special.\n";
●
Note: list() only works on numerical
arrays and assumes the numerical // Listing some of them
indices start at 0.
list($drink, , $power) = $info;
echo "$drink has $power.\n";
// Or let's skip to only the third one
list( , , $power) = $info;
echo "I need $power!\n";
www.intellibitz.com [email protected]
?>
shuffle
●
Shuffle an array
●
bool shuffle ( array &$array )
●
This function shuffles (randomizes the order of the elements in) an
array. Note: This function assigns new keys for the elements in
array. It will remove any existing keys you may have assigned,
rather than just reordering the keys.
<?php
$numbers = range(1, 20);
shuffle($numbers);
foreach ($numbers as $number) {
echo "$number ";
?>
www.intellibitz.com [email protected]
array_change_key_case
●
Returns an array with all string keys
lowercased or uppercased <?php
– array array_change_key_case $input_array = array("FirSt" => 1,
( array $input [, int $case] ) "SecOnd" => 4);
– array_change_key_case()
changes the keys in the input print_r(array_change_key_case($input
array to be all lowercase or _array, CASE_UPPER));
uppercase. ?>
– The change depends on the last
optional case parameter. The above example will output:
– You can pass two constants Array
(
there, CASE_UPPER and [FIRST] => 1
CASE_LOWER. The default is [SECOND] => 4
)
CASE_LOWER.
– The function will leave number
indices as is.
www.intellibitz.com [email protected]
array_chunk()
●
Split an array into chunks The below example will output:
– array array_chunk ( array $input, int $size [,
Array
bool $preserve_keys] ) (
– array_chunk() splits the array into several [0] => Array
(
arrays with size values in them. You may [0] => a
[1] => b
also have an array with less values at the )
end. You get the arrays as members of a [1] => Array
(
multidimensional array indexed with [0] => c
numbers starting from zero. [1] => d
)
[2] => Array
<?php (
[0] => e
)
$input_array = array('a', 'b', 'c', 'd', 'e');
)
print_r(array_chunk($input_array, 2));
?>
www.intellibitz.com [email protected]
array_chunk()
The below example will output:
●
By setting the optional Array
(
preserve_keys parameter to [0] => Array
TRUE, you can force PHP to (
[0] => a
preserve the original keys from [1] => b
the input array. )
[1] => Array
●
If you specify FALSE new number (
indices will be used in each [2] => c
[3] => d
resulting array with indices )
starting from zero. The default is [2] => Array
(
FALSE. [4] => e
)
<?php )
$input_array = array('a', 'b', 'c', 'd', 'e');
print_r(array_chunk($input_array, 2, true));
?>
www.intellibitz.com [email protected]
key
<?php
/ this cycle echoes all associative array
$array = array(
●
Fetch a key from an // key where value equals "apple"
associative array 'fruit1' => 'apple',
●
mixed key ( array while ($fruit_name = current($array)) {
'fruit2' => 'orange',
&$array ) if ($fruit_name == 'apple') {
● 'fruit3' => 'grape',
●
key() returns the echo key($array).'<br />';
'fruit4' => 'apple',
index element of }
the current array 'fruit5' => 'apple');
position. next($array);
/
}
?>
www.intellibitz.com [email protected]
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.
www.intellibitz.com [email protected]
<?php count
$a[0] = 1;
$a[1] = 3;
$a[2] = 5; $result = count(null);
$b[0] = 7;
$result = count($a); // $result == 0
$b[5] = 9;
// $result == 3
$b[10] = 11;
$result = count(false);
$result = count($b);
// $result == 1
// $result == 3
?>
sizeof — Alias of count()
www.intellibitz.com [email protected]
current
●
Return the current element in an array
●
Description
●
mixed current ( array &$array )
●
●
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
www.intellibitz.com [email protected]
next
●
Advance the internal array pointer of an <?php
array
●
mixed next ( array &$array ) $transport = array('foot',
● 'bike', 'car', 'plane');
●
Returns the array value in the next place
that's pointed to by the internal array $mode =
pointer, or FALSE if there are no current($transport); // $mode
more elements. = 'foot';
●
●
next() behaves like current(), with one $mode = next($transport); //
difference. It advances the internal $mode = 'bike';
array pointer one place forward
before returning the element value. $mode = next($transport); //
That means it returns the next array $mode = 'car';
value and advances the internal array
pointer by one. If advancing the $mode = prev($transport);
internal array pointer results in going // $mode = 'bike';
beyond the end of the element list,
next() returns FALSE. $mode = end($transport); //
$mode = 'plane';
www.intellibitz.com [email protected]
?>
prev
●
Rewind the internal array <?php
pointer
●
mixed prev ( array &$array )$transport = array('foot', 'bike', 'car', 'plane');
$mode = current($transport); // $mode = 'foot';
●
●
Returns the array value in the
previous place $mode = next($transport); // $mode = 'bike';
that's
pointed to by the internal
$mode = next($transport); // $mode = 'car';
array pointer, or FALSE if
$mode = prev($transport); // $mode = 'bike';
there are no more
elements. $mode = end($transport); // $mode = 'plane';
?>
www.intellibitz.com [email protected]
each
●
Return the current key and value pair from an array and advance the
array cursor
●
Description
●
array each ( array &$array )
●
●
Returns the current key and value pair from the array array and
advances the array cursor. This pair is returned in a four-element
array, with the keys 0, 1, key, and value. Elements 0 and key contain
the key name of the array element, and 1 and value contain the
data.
●
●
If the internal pointer for the array points past the end of the array
contents, each() returns FALSE.
www.intellibitz.com [email protected]
each
<?php
<?php
$foo = array("bob", "fred", "jussi",
"jouni", "egon", "marliese"); $foo = array("Robert" => "Bob", "Seppo" => "Sepi");
$bar = each($foo); $bar = each($foo);
print_r($bar); print_r($bar);
?> ?>
$bar now contains the following $bar now contains the following key/value pairs:
key/value pairs: Array
(
Array [1] => Bob
( [value] => Bob
[1] => bob [0] => Robert
[value] => bob [key] => Robert
[0] => 0 )
[key] => 0
)
www.intellibitz.com [email protected]
end
●
Set the internal pointer of an array to its last element
●
mixed end ( array &$array )
●
●
end() advances array's internal pointer to the last element, and returns
its value.
<?php
$fruits = array('apple', 'banana', 'cranberry');
echo end($fruits); // cranberry
?>
www.intellibitz.com [email protected]
reset
●
Set the internal pointer of an array
to its first element
●
mixed reset ( array &$array )
●
reset() rewinds array's internal
pointer to the first element and
returns the value of the first
array element, or FALSE if the
array is empty.
www.intellibitz.com [email protected]
reset
<?php
// skip two steps
next($array);
$array = array('step one', 'step two', 'step
next($array);
three', 'step four');
echo current($array) . "<br />\n"; // "step three"
// by default, the pointer is on the first element
// reset pointer, start again on step one
echo current($array) . "<br />\n"; // "step one"
reset($array);
echo current($array) . "<br />\n"; // "step one"
?>
www.intellibitz.com [email protected]
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.
www.intellibitz.com [email protected]
range
?php
// array('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i');
// array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12)
foreach (range('a', 'i') as $letter) {
foreach (range(0, 12) as $number) {
echo $letter;
echo $number;
}
}
// array('c', 'b', 'a');
foreach (range('c', 'a') as $letter) {
// The step parameter was introduced in 5.0.0
echo $letter;
// array(0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100)
}
foreach (range(0, 100, 10) as $number) {
?>
echo $number;
www.intellibitz.com [email protected]
in_array()
●
Checks if a value exists in an array
●
bool in_array ( mixed $needle, array $haystack [, bool $strict] )
●
●
Searches haystack for needle and returns TRUE if it is found in the
array, FALSE otherwise.
●
If the third parameter strict is set to TRUE then the in_array() function
will also check the types of the needle in the haystack.
●
Note: If needle is a string, the comparison is done in a case-sensitive
manner.
●
Note: In PHP versions before 4.2.0 needle was not allowed to be an
array.
●
www.intellibitz.com [email protected]
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
www.intellibitz.com [email protected]
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.
www.intellibitz.com [email protected]
array_count_values
●
Counts all the values of an array <?php
– array array_count_values (
array $input ) $array = array(1, "hello", 1, "world", "hello");
●
array_count_value print_r(array_count_values($array));
s() returns an
array using the ?>
values of the The above example will output:
input array as Array
keys and their (
[1] => 2
frequency in [hello] => 2
input as values. [world] => 1
)
www.intellibitz.com [email protected]
array_sum
●
Calculate the sum of values in an array
●
number array_sum ( array $array )
●
array_sum() returns the sum of values in an array as an integer or float.
<?php
$a = array(2, 4, 6, 8);
echo "sum(a) = " . array_sum($a) . "\n";
$b = array("a" => 1.2, "b" => 2.3, "c" => 3.4);
echo "sum(b) = " . array_sum($b) . "\n";
?>
The above example will output:
sum(a) = 20
sum(b) = 6.9
www.intellibitz.com [email protected]
array_values
●
Return all the values of an array
●
array array_values ( array $input ) <?php
●
array_values() returns all the
$array = array("size" => "XL", "color" =>
values from the input array and
"gold");
indexes numerically the array.
print_r(array_values($array));
?>
The above example will output:
Array
[0] => XL
[1] => gold
)
www.intellibitz.com [email protected]
array_pad
Pad array to the specified length <?php
●
with a value.
●
array array_pad ( array $input, $input = array(12, 10, 9);
int $pad_size, mixed
$pad_value )
●
array_pad() returns a copy of the $result = array_pad($input, 5, 0);
input padded to size specified // result is array(12, 10, 9, 0, 0)
by pad_size with value
pad_value. If pad_size is
positive then the array is $result = array_pad($input, 7, 1);
padded on the right, if it's
negative then on the left. If the // result is array(1, 1, 1, 1, 12, 10, 9)
absolute value of pad_size is
less than or equal to the
length of the input then no $result = array_pad($input, 2, "noop");
padding takes place. It is // not padded
possible to add most 1048576
?>
www.intellibitz.com
elements at a time.
www.intellibitz.com [email protected]
[email protected]
array_pop
<?php
●
Pop the element off the $stack = array("orange", "banana", "apple", "raspberry");
end of array
●
mixed array_pop ( array $fruit = array_pop($stack);
&$array ) print_r($stack);
●
array_pop() pops and
returns the last value ?>
of the array, After this, $stack will have only 3 elements:
shortening the array
by one element. If Array
array is empty (or is (
not an array), NULL
will be returned. [0] => orange
[1] => banana
[2] => apple
) and raspberry will be assigned to $fruit.
www.intellibitz.com [email protected]
array_push
<?php
●
Push one or more elements $stack = array("orange", "banana");
onto the end of array
●
int array_push ( array &$array, array_push($stack, "apple", "raspberry");
mixed $var [, mixed $...] ) print_r($stack);
●
array_push() treats array as a
stack, and pushes the ?>
passed variables onto the The above example will output:
end of array. The length of
array increases by the Array
number of variables (
pushed.
[0] => orange
[1] => banana
[2] => apple
[3] => raspberry
www.intellibitz.com [email protected]
)
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.
www.intellibitz.com [email protected]
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.
www.intellibitz.com [email protected]
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) . "\n";
?>
The above example will output:
product(a) = 384
www.intellibitz.com [email protected]
array_rand
●
Pick one or more random entries out of an
array
●
mixed array_rand ( array $input [, int
$num_req] ) <?php
●
array_rand() is rather useful when you want to
$input = array("Neo", "Morpheus",
pick one or more random entries out of an
"Trinity", "Cypher", "Tank");
array. It takes an input array and an optional
argument num_req which specifies how$rand_keys = array_rand($input, 2);
many entries you want to pick - if notecho $input[$rand_keys[0]] . "\n";
specified, it defaults to 1.
●
If you are picking only one entry, array_rand()echo $input[$rand_keys[1]] . "\n";
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.
www.intellibitz.com [email protected]
array_walk
●
Apply a user function to every member of an array
●
bool array_walk ( array &$array, callback $funcname [, mixed
$userdata] )
●
●
Returns TRUE on success or FALSE on failure.
●
●
Applies the user-defined function funcname to each element of the
array array. Typically, funcname takes on two parameters. The array
parameter's value being the first, and the key/index second. If the
optional userdata parameter is supplied, it will be passed as the third
parameter to the callback funcname.
www.intellibitz.com [email protected]
array_walk
<?php echo "Before ...:\n"; This example will
output:
$fruits = array("d" => "lemon", "a" => array_walk($fruits, 'test_print');
"orange", "b" => "banana", "c" => "apple"); Before ...:
array_walk($fruits, 'test_alter', 'fruit');
function test_alter(&$item1, $key, $prefix) d. lemon
echo "... and after:\n";
{ a. orange
array_walk($fruits, 'test_print');
$item1 = "$prefix: $item1"; b. banana
?>
} c. apple
function test_print($item2, $key) ... and after:
{ d. fruit: lemon
echo "$key. $item2<br />\n"; a. fruit: orange
} b. fruit: banana
c. fruit: apple
www.intellibitz.com [email protected]
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.
www.intellibitz.com [email protected]
array_unique
<?php
<?php
$input = array("a" => "green", "red", "b"
$input = array(4, "4", "3", 4, 3, "3");
=> "green", "blue", "red");
$result = array_unique($input);
$result = array_unique($input);
var_dump($result);
print_r($result);
?>
?>
The above example will output:
The above example will output:
array(2) {
Array
[0] => int(4)
(
[2] => string(1) "3"
[a] => green
}
[0] => red
[1] => blue
www.intellibitz.com [email protected]
)
array_map
●
Applies the callback to the ?php
elements of the given This makes $b have:
function cube($n)
arrays Array
(
●
array array_map ( callback { [0] => 1
$callback, array $arr1 [, [1] => 8
return($n * $n * $n); [2] => 27
array $...] ) [3] => 64
●
array_map() returns an array } [4] => 125
)
containing all the elements $a = array(1, 2, 3, 4, 5);
of arr1 after applying the
callback function to each $b = array_map("cube", $a);
one. The number of print_r($b);
parameters that the
callback function accepts ?>
should match the number of
arrays passed to the
array_map()
www.intellibitz.com [email protected]
array_reduce
●
Iteratively reduce the array to a single value using a callback function
●
mixed array_reduce ( array $input, callback $function [, int $initial] )
<?php
function rmul($v, $w) $a = array(1, 2, 3, 4, 5);
function rsum($v, $w)
{ $x = array();
{
$v *= $w; $b = array_reduce($a, "rsum");
$v += $w;
return $v; $c = array_reduce($a, "rmul", 10);
return $v;
} $d = array_reduce($x, "rsum", 1);
}
?>
This will result in $b containing 15, $c
containing 1200 (= 10*1*2*3*4*5), and $d
containing 1.
www.intellibitz.com [email protected]
array_reduce
●
array_reduce() applies iteratively the function function to the elements
of the array input, so as to reduce the array to a single value.
●
If the optional initial is available, it will be used at the beginning of the
process, or as a final result in case the array is empty.
●
If the array is empty and initial is not passed, array_reduce() returns
NULL.
www.intellibitz.com [email protected]
array_reverse
●
Return an array with elements in reverse order
●
array array_reverse ( array $array [, bool $preserve_keys] )
●
●
array_reverse() takes input array and returns a new array with the
order of the elements reversed, preserving the keys if
preserve_keys is TRUE.
www.intellibitz.com [email protected]
array_reverse
$result will be
$result_keyed will be:
Array
<?php Array
(
$input = array("php", 4.0, array("green", "red")); (
[0] => Array
$result = array_reverse($input); [2] => Array
(
$result_keyed = array_reverse($input, true); (
[0] => green
?> [0] => green
[1] => red
[1] => red
This makes both $result and $result_keyed )
)
have the same elements, [1] => 4
but note the difference between the keys. [1] => 4
[2] => php
[0] => php
)
)
www.intellibitz.com [email protected]
array_search
●
Searches the array for a given value and returns the corresponding key if
successful mixed array_search ( mixed $needle, array $haystack [, bool
$strict] )
●
Searches haystack for needle and returns the key if it is found in the array,
FALSE otherwise.
●
If needle is a string, the comparison is done in a case-sensitive manner.
●
Prior to PHP 4.2.0, array_search() returns NULL on failure instead of
FALSE.
●
If the optional third parameter strict is set to TRUE then the array_search()
will also check the types of the needle in the haystack.
<?php
$array = array(0 => 'blue', 1 => 'red', 2 => 'green', 3 => 'red');
$key = array_search('green', $array); // $key = 2;
$key = array_search('red', $array); // $key = 1;
www.intellibitz.com [email protected]
?>
array_shift
●
Shift an element off the beginning of array
●
mixed array_shift ( array &$array )
●
array_shift() shifts the first value of the array off and returns it, shortening the
array by one element and moving everything down.
●
All numerical array keys will be modified to start counting from zero while
literal keys won't be touched. If array is empty (or is not an array), NULL
will be returned.
●
This function will reset() the array pointer after use.
www.intellibitz.com [email protected]
array_shift
<?php
$stack = array("orange", "banana", "apple", "raspberry");
$fruit = array_shift($stack);
This would result in $stack having 3 elements left:
print_r($stack);
Array
?>
(
[0] => banana
[1] => apple
[2] => raspberry
and orange will be assigned to $fruit.
www.intellibitz.com [email protected]
array_unshift
<?php
●
Prepend one or more elements to $queue = array("orange", "banana");
the beginning of an array
array_unshift($queue, "apple", "raspberry");
●
int array_unshift ( array &$array,
mixed $var [, mixed $...] ) print_r($queue);
●
array_unshift() prepends passed ?>
elements to the front of the array.
Note that the list of elements is The above example will output:
prepended as a whole, so that the Array
prepended elements stay in the
same order. All numerical array (
keys will be modified to start [0] => apple
counting from zero while literal
keys won't be touched. [1] => raspberry
●
Returns the new number of elements [2] => orange
in the array
[3] => banana
)
www.intellibitz.com [email protected]
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.
www.intellibitz.com [email protected]
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.
www.intellibitz.com [email protected]
array_slice
<?php
$input = array("a", "b", "c", "d", "e");
Array
(
[0] => c
$output = array_slice($input, 2); // [1] => d
returns "c", "d", and "e" )
Array
$output = array_slice($input, 2, 1); // (
[2] => c
returns "d" [3] => 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));
www.intellibitz.com [email protected]
array_splice
●
Remove a portion of the array <?php
and
replace it with something else
$input = array("red", "green", "blue", "yellow");
●
array array_splice ( array &$input,
array_splice($input, 2);
int $offset [, int $length [, array
$replacement]] ) // $input is now array("red", "green")
$input = array("red", "green", "blue", "yellow");
array_splice($input, 1, 1);
// $input is now array("red", "yellow")
www.intellibitz.com [email protected]
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.
www.intellibitz.com [email protected]
array_merge
●
array array_merge ( array $array1 This example will
<?php output:
[, array $array2 [, array $...]] )
●
array_merge() merges the $array1 = array( Array
elements of one or more arrays
"color" => "red", 2, 4); (
together so that the values of
one are appended to the end of $array2 = array( [color] => green
the previous one. It returns the
"a", "b", [0] => 2
resulting array.
●
If the input arrays have the same "color" => "green", [1] => 4
string keys, then the later value "shape" =>
for that key will overwrite the "trapezoid",4); [2] => a
previous one. If, however, the [3] => b
$result =
arrays contain numeric keys,
array_merge($array1, [shape] => trapezoid
the later value will not overwrite
$array2);
the original value, but will be [4] => 4
appended. print_r($result);
)
?>
www.intellibitz.com [email protected]
array_merge_recursive
Array
●
If the input arrays have <?php
(
the same string keys, $ar1 = array("color" =>
[color] => Array
then the values for
these keys are array("favorite" => "red"), 5);
(
merged together into $ar2 = array(10, "color" =>
[favorite] => Array
an array, and this is array("favorite" => "green", "blue"));
done recursively, so (
$result = array_merge_recursive($ar1,
that if one of the [0] => red
$ar2);
values is an array
[1] => green
itself, the function will print_r($result);
merge it with a )
?>
corresponding entry [0] => blue
in another array too.
)
[0] => 5
[1] => 10
www.intellibitz.com [email protected]
)
array_key
●
Return all the keys of an array
●
array array_keys ( array $input [, mixed $search_value [,
bool $strict]] )
●
array_keys() returns the keys, numeric and string, from
the input array.
●
If the optional search_value is specified, then only the
keys for that value are returned. Otherwise, all the
keys from the input are returned. As of PHP 5, you can
use strict parameter for comparison including type
(===).
www.intellibitz.com [email protected]
array_key
The above example will output:
<?php
Array
$array = array(0 => 100, "color" => "red"); (
[0] => 0
print_r(array_keys($array)); [1] => color
)
Array
(
[0] => 0
$array = array("blue", "red", "green", "blue", "blue"); [1] => 3
[2] => 4
print_r(array_keys($array, "blue")); )
Array
(
[0] => color
$array = array("color" => array("blue", "red", "green"), [1] => size
)
"size" => array("small", "medium", "large"));
print_r(array_keys($array));
?>
www.intellibitz.com [email protected]
array_key_exists
●
Checks if the given key or index exists in the array
●
bool array_key_exists ( mixed $key, array $search )
●
array_key_exists() returns TRUE if the given key is set in the array. key
can be any value possible for an array index. array_key_exists()
also works on objects. The name of this function is key_exists() in
PHP 4.0.6.
<?php
<?php
$search_array = array('first' => null, 'second' =>
$search_array = array('first' => 1, 'second' => 4); 4);
if (array_key_exists('first', $search_array)) { // returns false
echo "The 'first' element is in the array"; isset($search_array['first']);
} // returns true
?> array_key_exists('first', $search_array);
?>
www.intellibitz.com [email protected]
array_fill
●
Fill an array with values ?php
– array array_fill ( int $start_index, int
$a = array_fill(5, 6, 'banana');
$num, mixed $value )
– array_fill() fills an array with num print_r($a);
entries of the value of the value ?>
parameter, keys starting at the
start_index parameter. Note that $a now is:
num must be a number greater Array
(
than zero, or PHP will throw a [5] => banana
warning. [6] => banana
[7] => banana
[8] => banana
[9] => banana
[10] => banana
)
www.intellibitz.com [email protected]
array_fill_keys
●
Fill an array with values, <?php
specifying keys
$keys = array('foo', 5, 10, 'bar');
●
array array_fill_keys ( array
$keys, mixed $value ) $a = array_fill_keys($keys, 'banana');
●
array_fill_keys() fills an array print_r($a);
with the value of the value
parameter, using the values ?>
of the keys array as keys. $a now is:
Array
(
[foo] => banana
[5] => banana
[10] => banana
[bar] => banana
)
www.intellibitz.com [email protected]
array_flip
●
Exchanges all keys with their associated values
<?php
in an array
●
array array_flip ( array $trans ) $trans = array("a" => 1, "b" => 1, "c"
●
array_flip() returns an array in flip order, i.e. keys => 2);
from trans become values and values from
$trans = array_flip($trans);
trans become keys.
●
Note that the values of trans need to be valid print_r($trans);
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 now $trans is:
question will not be flipped. Array
●
If a value has several occurrences, the latest key(
[1] => b
will be used as its values, and all others will be [2] => c
lost. )
●
array_flip() returns FALSE if it fails.
www.intellibitz.com [email protected]
array_intersect
●
Computes the intersection of arrays <?php
●
array array_intersect ( array $array1,
$array1 = array("a" => "green", "red", "blue");
array $array2 [, array $ ...] )
●
array_intersect() returns an array $array2 = array("b" => "green", "yellow", "red");
containing all the values of array1$result = array_intersect($array1, $array2);
that are present in all the
arguments. Note that keys are print_r($result);
preserved. ?>
– Two elements are
considered equal if and The above example will output:
only if (string) $elem1 ===Array
(string) $elem2. In words:
when the string (
representation is the [a] => green
same.
[0] => red
)
www.intellibitz.com [email protected]
array_intersect_key
●
Computes the intersection of arrays using keys for
comparison
– array array_intersect_key ( array $array1,
array $array2 [, array $ ...] )
– array_intersect_key() returns an array
containing all the values of array1 which
have matching keys that are present in all
the arguments.
www.intellibitz.com [email protected]
array_intersect_key
<?php
●
In our example you see that only the $array1 = array('blue' => 1, 'red' => 2,
keys 'blue' and 'green' are present 'green' => 3, 'purple' => 4);
in both arrays and thus returned.
$array2 = array('green' => 5, 'blue' => 6,
Also notice that the values for the
'yellow' => 7, 'cyan' => 8);
keys 'blue' and 'green' differ
between the two arrays. A match
still occurs because only the keys
var_dump(array_intersect_key($array1,
are checked. The values returned
$array2));
are those of array1.
●
The two keys from the key => value ?>
pairs are considered equal only if
The above example will output:
(string) $key1 === (string) $key2 . In
array(2) {
other words a strict type check is ["blue"]=>
executed so the string int(1)
["green"]=>
representation must be the same. int(3)
}
www.intellibitz.com [email protected]
array_intersect_uassoc
<?php
●
Computes the intersection of arrays with
additional index check, compares indexes by $array1 = array("a" => "green", "b" =>
a callback function "brown", "c" => "blue", "red");
– array array_intersect_uassoc ( array
$array2 = array("a" => "GREEN", "B"
$array1, array $array2 [, array $ ...,
callback $key_compare_func] ) => "brown", "yellow", "red");
– array_intersect_uassoc() returns an array
containing all the values of array1 that
are present in all the arguments. Note print_r(array_intersect_uassoc($array
that the keys are used in the comparison 1, $array2, "strcasecmp"));
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 The above example will output:
than zero if the first argument is Array
considered to be respectively less than, (
equal to, or greater than the second. [b] => brown
)
www.intellibitz.com [email protected]
array_intersect_assoc
<?php
●
Computes the intersection of
arrays with additional index $array1 = array("a" => "green", "b" =>
check "brown", "c" => "blue", "red");
●
array array_intersect_assoc ( array $array2 = array("a" => "green", "yellow",
$array1, array $array2 [, array $ "red");
...] )
$result_array =
●
array_intersect_assoc() returns an
array_intersect_assoc($array1, $array2);
array containing all the values of
array1 that are present in all the print_r($result_array);
arguments. Note that the keys
?>
are used in the comparison
unlike in array_intersect(). The above example will output:
Array
(
[a] => green
)
www.intellibitz.com [email protected]
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.
www.intellibitz.com [email protected]
array_intersect_ukey
●
Computes the intersection of arrays using a callback function on the
keys for comparison
●
array array_intersect_ukey ( array $array1, array $array2 [, array $...,
callback $key_compare_func] )
●
array_intersect_ukey() returns an array containing all the values of
array1 which have matching keys that are present in all the
arguments.
●
This comparison is done by a user supplied callback function. It must
return an integer less than, equal to, or greater than zero if the first
key is considered to be respectively less than, equal to, or greater
than the second.
www.intellibitz.com [email protected]
array_intersect_ukey
$array1 = array('blue' => 1, 'red' => 2, 'green' => 3,
<?php
'purple' => 4);
function key_compare_func($key1, $key2)
$array2 = array('green' => 5, 'blue' => 6, 'yellow' => 7,
{ 'cyan' => 8);
if ($key1 == $key2)
return 0; var_dump(array_intersect_ukey($array1, $array2,
'key_compare_func'));
else if ($key1 > $key2)
?>
return 1;
else The above example will output:
array(2) {
return 1; ["blue"]=>
int(1)
} ["green"]=>
int(3)
}
www.intellibitz.com [email protected]
array_uintersect
<?php
●
Computes the intersection of
$array1 = array("a" => "green", "b" => "brown",
arrays, compares data by
a callback function "c" => "blue", "red");
●
array array_uintersect ( array
$array1, array $array2 [,$array2 = array("a" => "GREEN",
array $ ..., callback "B" => "brown", "yellow", "red");
$data_compare_func] )
●
array_uintersect() returns an
array containing all the print_r(array_uintersect($array1, $array2, "strcasecmp"));
values of array1 that are
?>
present in all the
arguments. The data is The above example will output:
compared by using a Array
callback function. (
[a] => green
[b] => brown
[0] => red
)
www.intellibitz.com [email protected]
array_uintersect_assoc
●
Computes the intersection of <?php
arrays with additional index $array1 = array("a" => "green", "b" =>
check, compares data by a "brown", "c" => "blue", "red");
callback function
●
rray array_uintersect_assoc ( array $array2 = array("a" => "GREEN", "B" =>
$array1, array $array2 [, array $ "brown", "yellow", "red");
..., callback
$data_compare_func] )
● print_r(array_uintersect_assoc($array1,
●
array_uintersect_assoc() returns $array2, "strcasecmp"));
an array containing all the ?>
values of array1 that are
The above example will output:
present in all the arguments.
Array
(
[a] => green
)
www.intellibitz.com [email protected]
array_uintersect_uassoc
<?php
●
Computes the intersection of arrays with
additional index check, compares $array1 = array("a" => "green", "b" => "brown", "c"
data and indexes by a callback
functions => "blue", "red");
●
array array_uintersect_uassoc ( array
$array2 = array("a" => "GREEN", "B" => "brown",
$array1, array $array2 [, array $ ...,
callback $data_compare_func, "yellow", "red");
callback $key_compare_func] )
●
array_uintersect_uassoc() returns an
print_r(array_uintersect_uassoc($array1, $array2,
●
www.intellibitz.com [email protected]
array_diff_key
●
Computes the difference of arrays using keys for comparison
– array array_diff_key ( array $array1, array $array2 [, array
$ ...] )
●
array_diff_key() returns an array containing all the values of
array1 that have keys that are not present in any of the
other arguments. Note that the associativity is preserved.
This function is like array_diff() except the comparison is
done on the keys instead of the values.
– The two keys from the key => value pairs are considered equal
only if (string) $key1 === (string) $key2 . In other words a
<?php
strict type check is executed so the string representation
must be the same.
$array1 = array('blue' => 1, 'red' => 2, 'green' => 3, 'purple' => 4); This example will output
array(2) {
$array2 = array('green' => 5, 'blue' => 6, 'yellow' => 7, 'cyan' => 8); ["red"]=>
int(2)
["purple"]=>
int(4)
}
var_dump(array_diff_key($array1, $array2));
?>
www.intellibitz.com [email protected]
array_diff_assoc
●
Computes the difference of arrays with additional index check
– array array_diff_assoc ( array $array1, array $array2 [, array $ ...] )
– array_diff_assoc() returns an array containing all the values from
array1 that are not present in any of the other arguments.
<?php – Note that the keys are used in the comparison unlike array_diff().
$array1 = array("a" => "green", "b" =>
"brown", "c" => "blue", "red");
This example will
$array2 = array("a" => "green", "yellow",
output:
"red");
Array
$result = array_diff_assoc($array1, (
[b] =>
$array2); brown
[c] =>
print_r($result); blue
[0] => red
?> )
www.intellibitz.com [email protected]
array_udiff
●
Computes the difference of arrays by using a callback function for data
comparison
●
array array_udiff ( array $array1, array $array2 [, array $ ..., callback
$data_compare_func] )
●
●
array_udiff() returns an array containing all the values of array1 that are
not present in any of the other arguments. Note that keys are
preserved.
www.intellibitz.com [email protected]
array_diff_uassoc
Computes the difference of arrays with additional index check which is
●
<?php array1 that are not present in any of the other arguments.
function key_compare_func($a, $b)
$array1 = array("a" => "green", "b" => "brown", "c" => "blue", "red");
{
$array2 = array("a" => "green", "yellow", "red");
if ($a === $b) {
$result = array_diff_uassoc($array1, $array2, "key_compare_func");
return 0;
print_r($result);
} The above example will output:
?>
Array
return ($a > $b)? 1:1; (
[b] => brown
} [c] => blue
[0] => red
)
www.intellibitz.com [email protected]
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.
www.intellibitz.com [email protected]
array_diff_ukey
●
Computes the difference of arrays using a callback function on the keys
for comparison
– array array_diff_ukey ( array $array1, array $array2 [, array
$ ..., callback $key_compare_func] )
●
array_diff_ukey() returns an array containing all the
values of array1 that have keys that are not present
in any of the other arguments. Note that the
associativity is preserved. This function is like
array_diff() except the comparison is done on the
keys instead of the values.
●
This comparison is done by a user supplied callback
function. It must return an integer less than, equal to,
or greater than zero if the first key is considered to be
respectively less than, equal to, or greater than the
second.
www.intellibitz.com [email protected]
array_diff_ukey
<?php $array1 = array('blue' => 1, 'red' => 2,
'green' => 3, 'purple' => 4);
function
key_compare_func($key1 $array2 = array('green' => 5, 'blue' => 6,
, $key2) 'yellow' => 7, 'cyan' => 8);
if ($key1 == $key2) var_dump(array_diff_ukey($array1,
$array2, 'key_compare_func'));
return 0;
?>
else if ($key1 > $key2)
The above example will output:
return 1; array(2) {
["red"]=>
else int(2)
["purple"]=>
return 1; int(4)
}
}
www.intellibitz.com [email protected]
array_udiff_assoc
●
Computes the difference of arrays with additional index check,
compares data by a callback function
●
array array_udiff_assoc ( array $array1, array $array2 [, array $ ...,
callback $data_compare_func] )
●
array_udiff_assoc() returns an array containing all the values from
array1 that are not present in any of the other arguments.
●
Note that the keys are used in the comparison unlike array_diff() and
array_udiff(). The comparison of arrays' data is performed by using
an user-supplied callback.
●
In this aspect the behaviour is opposite to the behaviour of
array_diff_assoc() which uses internal function for comparison.
www.intellibitz.com [email protected]
array_udiff_uassoc
●
Computes the difference of arrays with additional index check,
compares data and indexes by a callback function
●
array array_udiff_uassoc ( array $array1, array $array2 [, array $ ...,
callback $data_compare_func, callback $key_compare_func] )
●
array_udiff_uassoc() returns an array containing all the values from
array1 that are not present in any of the other arguments. Note that
the keys are used in the comparison unlike array_diff() and
array_udiff().
www.intellibitz.com [email protected]
Modifying Arrays
●
Array elements operate just like regular scalar variables
using operators
●
Don't put quotes around element key when interpolating
array elements in strings
●
If array key has whitespace or other punctuation, use curly
braces
www.intellibitz.com [email protected]
Modifying Arrays
●
Use unset() to remove elements from array
●
Use implode() to quickly print all array values as a string
●
Use explode() to turn a string into an array
www.intellibitz.com [email protected]
Sorting Arrays
●
Use sort() only on numeric arrays, because it resets the
keys of the array when it sorts
●
Use asort() to sort an associative array
●
Use ksort() to sort arrays by key
●
The reverse sorting functions are rsort(), arsort() and
krsort()
www.intellibitz.com [email protected]
Using Multidimensional Arrays
●
Use array() construct to create arrays that have more
arrays as element values
●
Access element in multidimensional arrays by using more
sets of square brackets to identify elements
●
Use nested foreach() to iterate through each dimension of a
multidimensional array
www.intellibitz.com [email protected]
Chapter Summary
●
Understanding the components of an array: elements, keys
and values
●
Defining an array in your programs two ways: with array()
and with square brackets
●
Understanding the shortcuts PHP provide for arrays with
numeric keys
●
Counting the number of elements in array
www.intellibitz.com [email protected]
Chapter Summary
●
Visiting each element of array with foreach()
●
Modifying array element values inside a foreach() code
block
●
Visiting each element of a numeric key with for()
●
Understanding the order in which foreach() and for() visit
array elements
www.intellibitz.com [email protected]
Chapter Summary
●
Checking for an array element with a particular key
●
Checking for an array element with a particular value
●
Interpolating array element values in strings
●
Removing an element from an array
●
Generating a string from array with implode()
●
Generating array from string with explode()
www.intellibitz.com [email protected]
Chapter Summary
●
Sorting an array with sort(), asort(), or ksort()
●
Sorting an array in reverse
●
Defining a multidimensional array
●
Accessing individual elements of a multidimensional array
●
Visiting each element in a multidimensional array with
foreach() or for()
●
Interpolating multidimensional array elements
www.intellibitz.com [email protected]
CHAPTER 5
FUNCTIONS
www.intellibitz.com [email protected]
Functions
●
Declaring and Calling Functions
●
Passing Arguments to Functions
●
Returning Values from Functions
●
Understanding Variable Scope
www.intellibitz.com [email protected]
Functions
●
Functions allows you to reuse code
●
Functions are named set of statements that you can
execute by invoking the function name instead of
retyping the statements
●
Functions can take arguments as well return value
●
Variables inside a function and outside a function live in two
separate worlds
www.intellibitz.com [email protected]
Declaring and Calling Functions
●
Function names follow the same rules as variable names
●
Functions can be defined before or after they are called
●
Avoid using the same name for a function and a variable
www.intellibitz.com [email protected]
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
www.intellibitz.com [email protected]
Passing Arguments to
Functions
●
Changes made to a variable passed as an argument don't
affect the variable outside the function
●
Modifying arguments doesn't affect variables outside the
function even if the argument has the same name as a
variable outside the function
www.intellibitz.com [email protected]
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
www.intellibitz.com [email protected]
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
www.intellibitz.com [email protected]
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
www.intellibitz.com [email protected]
Chapter Summary
●
Defining your own functions and calling them in your
programs
●
Defining a function with mandatory arguments
●
Defining a function with optional arguments
●
Returning a value from a function
●
Understanding variable scope
●
Using global variables inside a function
www.intellibitz.com [email protected]
CHAPTER 6
HTML AN INTRODUCTION TO
WEB FORMS
www.intellibitz.com [email protected]
HTML
●
HTML stands for Hyper Text Markup Language
●
An HTML file is a text file containing small markup tags
●
The markup tags tell the Web browser how to display the
page
www.intellibitz.com [email protected]
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.
www.intellibitz.com [email protected]
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
www.intellibitz.com [email protected]
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.
www.intellibitz.com [email protected]
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.
www.intellibitz.com [email protected]
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
www.intellibitz.com [email protected]
BODY
●
<BODY> encloses the content that has to be displayed
in the browser.
●
<p> tag encloses the paragraph.
www.intellibitz.com [email protected]
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.
www.intellibitz.com [email protected]
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.
www.intellibitz.com [email protected]
Attribute
●
In some rare situations, like when the attribute value itself
contains quotes, it is necessary to use single quotes:
– name='John "ShotGun" Nelson'
www.intellibitz.com [email protected]
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.
www.intellibitz.com [email protected]
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.
www.intellibitz.com [email protected]
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.
www.intellibitz.com [email protected]
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
www.intellibitz.com [email protected]
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
www.intellibitz.com [email protected]
Formatting
●
<abbr> Defines an abbreviation
●
<acronym> Defines an acronym
●
<address> Defines an address element
●
<bdo> Defines the text direction
●
<blockquote> Defines a long quotation
●
<q> Defines a short quotation
●
<cite> Defines a citation
●
<dfn> Defines a definition term
www.intellibitz.com [email protected]
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.
www.intellibitz.com [email protected]
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 <
www.intellibitz.com [email protected]
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.
www.intellibitz.com [email protected]
Html entities
●
non-breaking space  
●
< less than < <
●
> greater than > >
●
& ampersand & &
●
" quotation mark " "
●
' apostrophe ' '
www.intellibitz.com [email protected]
Html entities
●
¢ cent ¢ ¢
●
£ pound £ £
●
¥ yen ¥ ¥
●
§ section § §
●
© copyright © ©
●
® registered trademark ® ®
●
× multiplication × ×
●
÷ division ÷ ÷
www.intellibitz.com [email protected]
Links
●
HTML uses a hyperlink to link to another document on the
Web.
●
The <a> tag is used to create an anchor to link from, the
href attribute is used to address the document to link to,
and the words between the open and close of the anchor
tag will be displayed as a hyperlink.
www.intellibitz.com [email protected]
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>
www.intellibitz.com [email protected]
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.
www.intellibitz.com [email protected]
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
www.intellibitz.com [email protected]
Frames
●
The <frameset> tag defines how to divide the window into
frames
●
Each frameset defines a set of rows or columns
●
The values of the rows/columns indicate the amount of
screen area each row/column will occupy
www.intellibitz.com [email protected]
Frames
●
The <frame> tag defines what HTML document to put into
each frame
<frameset cols="25%,75%">
<frame src="frame_a.htm">
<frame src="frame_b.htm">
</frameset>
www.intellibitz.com [email protected]
Frames
●
if you add a <noframes> tag containing some text for
browsers that do not support frames, you will have to
enclose the text in <body></body> tags!
www.intellibitz.com [email protected]
Tables
●
Tables are defined with the <table> tag.
●
A table is divided into rows (with the <tr> tag)
●
Each row is divided into data cells (with the <td> tag).
●
A data cell can contain text, images, lists, paragraphs,
forms, horizontal rules, tables, etc.
www.intellibitz.com [email protected]
Tables
<table border="1"> <table border="1">
<tr> <tr>
<td>row 1, cell 1</td> <th>Heading</th>
<td>row 1, cell 2</td> <th>Another Heading</th>
</tr> </tr>
<tr> <tr>
<td>row 2, cell 1</td> <td>row 1, cell 1</td>
<td>row 2, cell 2</td> <td>row 1, cell 2</td>
</tr> </tr>
</table> <tr>
<td>row 2, cell 1</td>
<td>row 2, cell 2</td>
</tr>
</table>
www.intellibitz.com [email protected]
List
●
An unordered list is a list of items. The list items are marked
with bullets (typically small black circles).
●
An ordered list is also a list of items. The list items are
marked with numbers.
●
A definition list is not a list of items. This is a list of terms
and explanation of the terms.
www.intellibitz.com [email protected]
List
<dl>
<ul> <ol> <dt>Coffee</dt>
<li>Coffee</li> <li>Coffee</li> <dd>Black hot drink</dd>
<li>Milk</li> <li>Milk</li> <dt>Milk</dt>
</ul> </ol> <dd>White cold drink</dd>
</dl>
www.intellibitz.com [email protected]
Image
●
With HTML you can display images in a document.
●
The src attribute of img tag should be assigned with the
path of the file.
●
Img tag has no closing tag.
www.intellibitz.com [email protected]
Image
●
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
www.intellibitz.com [email protected]
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.
www.intellibitz.com [email protected]
<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.
www.intellibitz.com [email protected]
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 protected]
www.intellibitz.com [email protected]
<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 protected]
www.intellibitz.com [email protected]
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.
www.intellibitz.com [email protected]
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 protected]
www.intellibitz.com [email protected]
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 protected]
www.intellibitz.com [email protected]
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 protected]
www.intellibitz.com [email protected]
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 protected]
www.intellibitz.com [email protected]
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 protected]
www.intellibitz.com [email protected]
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 protected]
www.intellibitz.com [email protected]
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
www.intellibitz.com [email protected]
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.
www.intellibitz.com [email protected]
Lists and drop-down lists
www.intellibitz.com [email protected]
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.
www.intellibitz.com [email protected]
Image
●
<input type = “image”> is identical to <input type =
“submit”>except thet instead of displaying a button it
displays a specific image.
www.intellibitz.com [email protected]
Hidden
●
Along with user editable data,HTML also allows to send
uneditable hidden data to the server.
www.intellibitz.com [email protected]
Textarea
●
Textarea is the multiline text field.
●
Attributes
– Name
●
Name of the field
– Cols
●
Number of columns wide (in characters)of the
text field
– Rows
●
Number of rows long
www.intellibitz.com [email protected]
Textarea
– Wrap
Determines how the text should be submitted
●
www.intellibitz.com [email protected]
Textarea
– Soft
●
Text will be wrap to text field but sent exactly
as typed
– Hard
●
Text will wrap to text field
●
The submission will contain new character at
every wrapping point.
www.intellibitz.com [email protected]
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
www.intellibitz.com [email protected]
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.
www.intellibitz.com [email protected]
CHAPTER 7
www.intellibitz.com [email protected]
Making Web Forms
●
Useful Server Variables
●
Accessing Form Parameters
●
Form Processing with Functions
●
Validating Data
●
HTML and JavaScript
●
Displaying Default Values
●
Putting it all together
www.intellibitz.com [email protected]
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.
www.intellibitz.com [email protected]
Accessing Form Parameters
●
A form element with multiple values needs to have a name
that ends in []
●
Forms can be made flexible by putting the display code and
processing code in separate functions
●
Data validation is also made easy by using form processing
functions
www.intellibitz.com [email protected]
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.
www.intellibitz.com [email protected]
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.
www.intellibitz.com [email protected]
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.
www.intellibitz.com [email protected]
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.
www.intellibitz.com [email protected]
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.
www.intellibitz.com [email protected]
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
www.intellibitz.com [email protected]
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
www.intellibitz.com [email protected]
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
www.intellibitz.com [email protected]
Chapter Summary
●
Removing submitted HTML and JavaScript before
displaying it.
●
Displaying default values for form elements.
●
Using helper functions to display form elements.
www.intellibitz.com [email protected]
CHAPTER 8
www.intellibitz.com [email protected]
Databases
●
Organizing Data in a Database
●
Connecting to a Database Program
●
Putting Data into the Database
●
Inserting Form Data Safely
●
Generating Unique ID's
●
A Complete Data Insertion Form
●
Retrieving Data from a Database
●
MySQL without PEAR DB
www.intellibitz.com [email protected]
PEAR DB
●
PEAR DB is an add-on to PHP that simplifies
communication between PHP and Database
●
PEAR (PHP Extension and Application Repository) is a
collection of useful modules and libraries for PHP
●
DB module is one of the most popular PEAR modules and
is bundled with PHP
www.intellibitz.com [email protected]
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
www.intellibitz.com [email protected]
Connecting to a Database
●
Use require 'DB.php';
●
Use include in place of require if you want strict checking
●
DSN is passed to DB::connect ()
●
$db = DB::connect ('db://user:pass@host/schema');
●
DB::isError () checks if object contains error information
www.intellibitz.com [email protected]
Creating a Table
●
CREATE TABLE dishes (
●
dish_id INT,
●
dish_name VARCHAR(255),
●
price DECIMAL(4,2),
●
is_spicy INT
●
)
●
DROP TABLE dishes
www.intellibitz.com [email protected]
Putting Data into Database
●
Pass an INSERT statement to the object's query() function
●
$q = $db->query(“INSERT here...”);
●
Use setErrorHandling() to have your program automatically
print an error message and exit if a query fails
www.intellibitz.com [email protected]
Inserting Form Data Safely
●
Beware of SQL injection attack
●
Some databases let you pass multiple queries seperated by
semicolons in one call of query()
●
Escape special characters (apostrophe)
●
PEAR DB provides a helpful feature called placeholders
www.intellibitz.com [email protected]
Generating Unique IDs
●
To identify individual database records, give them each a
unique identifier
●
PEAR DB helps you generate unique integer Ids with its
support for sequences
●
Use nextID() to get the next value from a sequence
www.intellibitz.com [email protected]
Retrieving Data from Database
●
Use fetchRow() to get the next row returned from the query,
when no rows left, fetchRow() returns false
●
Use numrows() to find number of rows returned by a
SELECT query
●
Wildcards _ matches one character and the % sign
matches any number including zero
www.intellibitz.com [email protected]
MySQL without PEAR DB
●
A program that uses the built-in PHP functions tailored to a
particular database is faster than the one that uses
PEAR DB
●
For database access without PEAR DB, mysqli extension
can be used
●
$db = mysqli_connect ('db.intellibitz.com', 'user', 'pass',
'schema');
www.intellibitz.com [email protected]
Chapter Summary
●
Figuring out what kinds of information belong in a database
●
Understanding how data is organized in a database
●
Loading an external file with require
●
Establishing a database connection
●
Creating a table in the database
●
Removing a table from the database
www.intellibitz.com [email protected]
Chapter Summary
●
Using the SQL INSERT command
●
Inserting data into the database with query ()
●
Checking for database errors with DB::isError()
●
Setting up automatic error handling with setErrorHandling()
●
Using the SQL UPDATE and DELETE commands
www.intellibitz.com [email protected]
Chapter Summary
●
Changing or deleting data with query()
●
Counting the number of rows affected by a query
●
Using placeholders to insert data safely
●
Generating unique ID values with sequences
●
Using the SQL SELECT command
●
Retrieving data from the database with query() and
fetchRow()
www.intellibitz.com [email protected]
Chapter Summary
●
Counting the number of rows retrieved by query()
●
Retrieving data with getAll(), getRow(), and getOne()
●
Using the SQL ORDER BY and LIMIT keywords with
SELECT
●
Retrieving rows as string-keyed arrays or objects
www.intellibitz.com [email protected]
Chapter Summary
●
Using the SQL wildcards with LIKE % and _
●
Escaping SQL wildcards in SELECT
●
Saving submitted form parameters in the database
●
Using data from the database in form elements
●
Using the mysqli functions instead of PEAR DB
www.intellibitz.com [email protected]
CHAPTER 9
www.intellibitz.com [email protected]
mysql_query
●
Send a MySQL query
●
resource mysql_query ( string $query [, resource
$link_identifier] )
●
mysql_query() sends an unique query (multiple queries are
not supported) to the currently active database on the
server that's associated with the specified link_identifier.
www.intellibitz.com [email protected]
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.
www.intellibitz.com [email protected]
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.
www.intellibitz.com [email protected]
mysql_result
●
Get result data
●
string mysql_result ( resource $result, int $row [, mixed
$field] )
●
Retrieves the contents of one cell from a MySQL result set.
●
When working on large result sets, you should consider
using one of the functions that fetch an entire row
(specified below). As these functions return the contents
of multiple cells in one function call, they're MUCH
quicker than mysql_result(). Also, note that specifying a
numeric offset for the field argument is much quicker
than specifying a fieldname or tablename.fieldname
argument.
www.intellibitz.com [email protected]
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.
www.intellibitz.com [email protected]
mysql_result
●
Return Values <?php
●
The contents $link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
of one cell if (!$link) {
from a
die('Could not connect: ' . mysql_error());
MySQL
}
result set
on $result = mysql_query('SELECT name FROM work.employee');
success, or if (!$result) {
FALSE on die('Could not query:' . mysql_error());
failure.
}
echo mysql_result($result, 2); // outputs third employee's name
mysql_close($link);
?>
www.intellibitz.com [email protected]
mysql_selest_db
●
Select a MySQL database
●
bool mysql_select_db ( string $database_name [, resource
$link_identifier] )
●
Sets the current active database on the server that's
associated with the specified link identifier. Every
subsequent call to mysql_query() will be made on the
active database.
www.intellibitz.com [email protected]
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.
www.intellibitz.com [email protected]
mysql_select_db
●
Return Values
<?php
●
Returns TRUE on
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
success or
FALSE on
if (!$link) {
failure.
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());
?>
www.intellibitz.com [email protected]
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.
www.intellibitz.com [email protected]
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.
●
www.intellibitz.com [email protected]
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.
www.intellibitz.com [email protected]
mysql_affected_row
<?php
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
die('Could not connect: ' . mysql_error()); /* with a where clause that is never true, it should return
} 0 */
mysql_select_db('mydb'); mysql_query('DELETE FROM mytable WHERE 0');
printf("Records deleted: %d\n", mysql_affected_rows());
/* this should return the correct numbers of deleted records */?>
mysql_query('DELETE FROM mytable WHERE id < 10'); The above example will output something similar to:
Records deleted: 10
printf("Records deleted: %d\n", mysql_affected_rows()); Records deleted: 0
www.intellibitz.com [email protected]
mysql_affected_rows
<?php
/* Update records */
$link = mysql_connect('localhost', 'mysql_user',
'mysql_password'); mysql_query("UPDATE mytable SET used=1 WHERE id
< 10");
if (!$link) {
printf ("Updated records: %d\n", mysql_affected_rows());
die('Could not connect: ' . mysql_error());
mysql_query("COMMIT");
}
?>
mysql_select_db('mydb');
The above example will output something similar to:
Updated Records: 10
www.intellibitz.com [email protected]
mysql_change_user
●
mysql_change_user — Change logged in user of the active
connection
●
int mysql_change_user ( string $user, string $password [,
string $database [, resource $link_identifier]] )
●
mysql_change_user() changes the logged in user of the
current active connection, or the connection given by the
optional link_identifier parameter. If a database is
specified, this will be the current database after the user
has been changed. If the new user and password
authorization fails, the current connected user stays
active.
●
This function is deprecated and no longer exists in PHP.
www.intellibitz.com [email protected]
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.
www.intellibitz.com [email protected]
mysql_client_encoding
●
mysql_client_encoding — Returns the name of the character set
●
string mysql_client_encoding ( [resource $link_identifier] )
●
Retrieves the character_set variable from MySQL.
●
Parameters
– link_identifier
●
The MySQL connection. If the link identifier is not
specified, the last link opened by mysql_connect() is
assumed. If no such link is found, it will try to create
one as if mysql_connect() was called with no
arguments. If by chance no connection is found or
established, an E_WARNING level warning is
generated.
www.intellibitz.com [email protected]
mysql_client_encoding
<?php
$link = mysql_connect('localhost',
'mysql_user', 'mysql_password');
$charset = mysql_client_encoding($link);
www.intellibitz.com [email protected]
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.
www.intellibitz.com [email protected]
<?php
mysql_close
$link = mysql_connect('localhost',
'mysql_user', 'mysql_password');
if (!$link) {
die('Could not connect: ' .
mysql_error());
}
echo 'Connected successfully';
mysql_close($link);
?>
Connected successfully
www.intellibitz.com [email protected]
mysql_connect
●
mysql_connect — Open a connection to a MySQL Server
●
resource mysql_connect ( [string $server [, string $username [, string
$password [, bool $new_link [, int $client_flags]]]]] )
●
Opens or reuses a connection to a MySQL server.
www.intellibitz.com [email protected]
mysql_connect
●
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'. 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.
www.intellibitz.com [email protected]
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.
–
www.intellibitz.com [email protected]
mysql_connect
●
client_flags
The client_flags parameter can be a combination of
●
www.intellibitz.com [email protected]
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'; // we connect to localhost at port 3307
mysql_close($link); $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);
?>
www.intellibitz.com [email protected]
mysql_connect
●
Parameters
– database_name
●
The name of the database being created.
– link_identifier
●
The MySQL connection. If the link identifier is not
specified, the last link opened by mysql_connect() is
assumed. If no such link is found, it will try to create
one as if mysql_connect() was called with no
arguments. If by chance no connection is found or
established, an E_WARNING level warning is
generated.
●
Return Values
– Returns TRUE on success or FALSE on failure.
www.intellibitz.com [email protected]
mysql_create_db
●
Create a MySQL database
●
bool mysql_create_db ( string $database_name [, resource
$link_identifier] )
●
mysql_create_db() attempts to create a new database on the server
associated with the specified link identifier.
www.intellibitz.com [email protected]
<?php
mysql_create_db
$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\n";
} else {
echo 'Error creating database: ' . mysql_error() . "\n";
?>
The above example will output something similar to:
Database my_db created successfully
www.intellibitz.com [email protected]
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.
www.intellibitz.com [email protected]
mysql_data_seek
●
Parameters
– result
The result resource that is being evaluated. This
●
www.intellibitz.com [email protected]
mysql_db_name
●
Get result data
●
Description
●
string mysql_db_name ( resource $result, int $row [, mixed $field] )
●
●
Retrieve the database name from a call to mysql_list_dbs().
www.intellibitz.com [email protected]
mysql_db_name
●
Parameters
– result
●
The result pointer from a call to mysql_list_dbs().
– row
●
The index into the result set.
– field
The field name.
●
– Return Values
●
Returns the database name on success, and FALSE
on failure. If FALSE is returned, use mysql_error() to
determine the nature of the error.
www.intellibitz.com [email protected]
mysql_db_name
<?php
error_reporting(E_ALL);
$link = mysql_connect('dbhost', 'username', 'password');
$db_list = mysql_list_dbs($link);
$i = 0;
$cnt = mysql_num_rows($db_list);
while ($i < $cnt) {
echo mysql_db_name($db_list, $i) . "\n";
$i++;
}
www.intellibitz.com [email protected]
?>
mysql_db_query
●
Send a MySQL query
●
resource mysql_db_query ( string $database, string $query [, resource $link_identifier] )
●
mysql_db_query() selects a database, and executes a query on it.
●
Parameters
– database
●
The name of the database that will be selected.
– query
●
The MySQL query.
– link_identifier
●
●
The MySQL connection. If the link identifier is not specified, the
last link opened by mysql_connect() is assumed. If no such link is
found, it will try to create one as if mysql_connect() was called with
no arguments. If by chance no connection is found or established,
an E_WARNING level warning is generated.
●
Return Values
●
Returns a positive MySQL result resource to the query result, or
FALSE on error. The function also returns TRUE/FALSE for
INSERT/UPDATE/DELETE queries to indicate success/failure.
www.intellibitz.com [email protected]
mysql_db_query
$sql = 'SELECT foo FROM bar WHERE id = 42';
<?php
$result = mysql_query($sql, $link);
if (!$result) {
if (!$link = mysql_connect('mysql_host',
'mysql_user', 'mysql_password')) { echo "DB Error, could not query the database\n";
echo 'Could not connect to mysql'; echo 'MySQL Error: ' . mysql_error();
exit; exit;
} }
while ($row = mysql_fetch_assoc($result)) {
if (!mysql_select_db('mysql_dbname', $link)) { echo $row['foo'];
echo 'Could not select database'; }
exit; mysql_free_result($result);
} ?>
www.intellibitz.com [email protected]
mysql_drop_db
●
Drop (delete) a MySQL database
●
bool mysql_drop_db ( string $database_name [, resource
$link_identifier] )
●
mysql_drop_db() attempts to drop (remove) an entire database from
the server associated with the specified link identifier. This function
is deprecated, it is preferable to use mysql_query() to issue a sql
DROP DATABASE statement instead.
www.intellibitz.com [email protected]
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.
www.intellibitz.com [email protected]
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\n";
} else {
echo 'Error dropping database: ' . mysql_error() . "\n";
}
www.intellibitz.com [email protected]
?>
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.
www.intellibitz.com [email protected]
mysql_errno
<?php
$link = mysql_connect("localhost", "mysql_user",
"mysql_password");
if (!mysql_select_db("nonexistentdb", $link)) {
echo mysql_errno($link) . ": " . mysql_error($link). "\n";
mysql_select_db("kossu", $link);
if (!mysql_query("SELECT * FROM nonexistenttable", $link)) {
echo mysql_errno($link) . ": " . mysql_error($link) . "\n";
}
The above example will output something similar to:
?> 1049: Unknown database 'nonexistentdb'
1146: Table 'kossu.nonexistenttable' doesn't
exist
www.intellibitz.com [email protected]
mysql_error
●
Returns the text of the error message from previous MySQL operation
●
string mysql_error ( [resource $link_identifier] )
●
Returns the error text from the last MySQL function. Errors coming
back from the MySQL database backend no longer issue warnings.
Instead, use mysql_error() to retrieve the error text. Note that this
function only returns the error text from the most recently executed
MySQL function (not including mysql_error() and mysql_errno()), so
if you want to use it, make sure you check the value before calling
another MySQL function.
www.intellibitz.com [email protected]
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.
www.intellibitz.com [email protected]
mysql_error
<?php
$link = mysql_connect("localhost", "mysql_user", "mysql_password");
mysql_select_db("nonexistentdb", $link);
echo mysql_errno($link) . ": " . mysql_error($link). "\n";
mysql_select_db("kossu", $link);
mysql_query("SELECT * FROM nonexistenttable", $link);
echo mysql_errno($link) . ": " . mysql_error($link) . "\n";
?>
The above example will output something similar to:
1049: Unknown database 'nonexistentdb'
1146: Table 'kossu.nonexistenttable' doesn't exist
www.intellibitz.com [email protected]
mysql_escape_string
●
Escapes a string for use in a mysql_query
●
string mysql_escape_string ( string $unescaped_string )
●
This function will escape the unescaped_string, so that it is
safe to place it in a mysql_query(). This function is
deprecated.
●
This function is identical to mysql_real_escape_string()
except that mysql_real_escape_string() takes a
connection handler and escapes the string according to
the current character set. mysql_escape_string() does
not take a connection argument and does not respect the
current charset setting.
www.intellibitz.com [email protected]
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\n",
$escaped_item);
?>
The above example will output:
Escaped string: Zak\'s Laptop
www.intellibitz.com [email protected]
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.
www.intellibitz.com [email protected]
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.
www.intellibitz.com [email protected]
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);
?>
www.intellibitz.com [email protected]
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.
www.intellibitz.com [email protected]
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
www.intellibitz.com [email protected]
about aliases.
<?php
array_fetch_assoc
$sql = "SELECT id as userid, fullname, userstatus
$conn = mysql_connect("localhost",
FROM sometable
"mysql_user", "mysql_password");
WHERE userstatus = 1";
if (!$conn) {
$result = mysql_query($sql);
echo "Unable to connect to DB: " .
mysql_error(); if (!$result) {
exit; echo "Could not successfully run query ($sql) from DB: " .
mysql_error();
}
exit;
if (!mysql_select_db("mydbname")) {
}
echo "Unable to select mydbname: " .
mysql_error(); if (mysql_num_rows($result) == 0) {
exit; echo "No rows found, nothing to print so am exiting";
} exit;
}
www.intellibitz.com [email protected]
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.
www.intellibitz.com [email protected]
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 nonunique
key
* numeric 1 if the column is numeric
* blob 1 if the column is a BLOB
* type the type of the column
www.intellibitz.com [email protected]
* unsigned 1 if the column is unsigned
mysql_fetch_fields
$i = 0; not_null: $meta>not_null
while ($i < mysql_num_fields($result)) { numeric: $meta>numeric
echo "Information for column $i:<br />\n"; primary_key: $meta>primary_key
echo "<pre>
$meta = mysql_fetch_field($result, $i); table: $meta>table
blob: $meta>blob
if (!$meta) { type: $meta>type
max_length: $meta>max_length
echo "No information available<br />\n"; default: $meta>def
} multiple_key: $meta>multiple_key unique_key: $meta>unique_key
name: $meta>name unsigned: $meta>unsigned
zerofill: $meta>zerofill
</pre>";
$i++;
}
www.intellibitz.com [email protected]
mysql_fetch_length
●
Get the length of each output in a result
●
array mysql_fetch_lengths ( resource $result )
●
Returns an array that corresponds to the lengths of each
field in the last row fetched by MySQL.
●
mysql_fetch_lengths() stores the lengths of each result
column in the last row returned by mysql_fetch_row(),
mysql_fetch_assoc(), mysql_fetch_array(), and
mysql_fetch_object() in an array, starting at offset 0.
www.intellibitz.com [email protected]
<?php
mysql_fetch_length $result = mysql_query("SELECT id,email
FROM people WHERE id = '42'");
●
Parameters if (!$result) {
– result
Array
●
The result echo 'Could not run query: ' . mysql_error();
(
resource that [id] => 42
is being exit; [email] =>
evaluated. This [email protected]
result comes } )
from a call to Array
mysql_query(). $row = mysql_fetch_assoc($result); (
●
Return Values [0] => 2
– An array of lengths on $lengths = mysql_fetch_lengths($result); [1] => 16
)
success, or FALSE on
failure.
print_r($row);
print_r($lengths);
?>
www.intellibitz.com [email protected]
mysql_fetch_object
●
Fetch a result row as an object
●
object mysql_fetch_object ( resource $result [, string
$class_name [, array $params]] )
●
Returns an object with properties that correspond to the
fetched row and moves the internal data pointer ahead.
www.intellibitz.com [email protected]
mysql_fetch_object
●
Parameters
– Result
The result resource that is being evaluated.
●
www.intellibitz.com [email protected]
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.
www.intellibitz.com [email protected]
mysql_fetch_object
<?php
<?php
mysql_connect("hostname", "user",
"password");
$row = mysql_fetch_object($result);
mysql_select_db("mydb");
$result = mysql_query("select * from
mytable"); /* this is valid */
while ($row = echo $row>field;
mysql_fetch_object($result)) {
/* this is invalid */
echo $row>user_id;
// echo $row>0;
echo $row>fullname;
}
?>
mysql_free_result($result);
?>
www.intellibitz.com [email protected]
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().
www.intellibitz.com [email protected]
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.
www.intellibitz.com [email protected]
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
?>
www.intellibitz.com [email protected]
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().
www.intellibitz.com [email protected]
mysql_field_flags
●
Parameters
– Result
The result resource that is being evaluated.
●
www.intellibitz.com [email protected]
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".
www.intellibitz.com [email protected]
<?php mysql_field_flags
$result = mysql_query("SELECT id,email
FROM people WHERE id = '42'");
if (!$result) {
not_null primary_key
echo 'Could not run query: ' . mysql_error(); auto_increment
Array
(
exit; [0] => not_null
[1] =>
} primary_key
[2] =>
$flags = mysql_field_flags($result, 0); auto_increment
)
echo $flags;
print_r(explode(' ', $flags));
?>
www.intellibitz.com [email protected]
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.
www.intellibitz.com [email protected]
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;
?>
www.intellibitz.com [email protected]
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;
www.intellibitz.com [email protected]
?>
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.
www.intellibitz.com [email protected]
mysql_field_name
<?php $dbname = 'mydb';
/* The users table consists of three fields: $db_selected = mysql_select_db($dbname, $link);
* user_id
if (!$db_selected) {
* username die("Could not set $dbname: " . mysql_error());
* password. }
*/ $res = mysql_query('select * from users', $link);
$link = @mysql_connect('localhost', echo mysql_field_name($res, 0) . "\n";
'mysql_user', 'mysql_password');
echo mysql_field_name($res, 2);
if (!$link) {
?>
die('Could not connect to MySQL server: ' .
mysql_error()); The above example will output:
user_id
} password
www.intellibitz.com [email protected]
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.
www.intellibitz.com [email protected]
mysql_field_seek
●
Parameters
– result
The result resource that is being
●
www.intellibitz.com [email protected]
mysql_field_table
●
Get name of the table the specified field is in
●
string mysql_field_table ( resource $result, int
$field_offset )
●
Returns the name of the table that the specified field is
in.
www.intellibitz.com [email protected]
mysql_field_table
●
Parameters
– result
The result resource that is being
●
www.intellibitz.com [email protected]
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
?>
www.intellibitz.com [email protected]
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.
www.intellibitz.com [email protected]
mysql_field_type
●
Parameters
– result
The result resource that is being evaluated.
●
mysql_free_result($result);
mysql_close();
?>
www.intellibitz.com [email protected]
mysql_field_type
www.intellibitz.com [email protected]
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.
www.intellibitz.com [email protected]
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'];
www.intellibitz.com [email protected]
?>
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\n",
mysql_get_client_info());
?>
The above example will output something similar
to:
MySQL client info: 3.23.39
www.intellibitz.com [email protected]
mysql_host_info
●
Get MySQL host info
●
string mysql_get_host_info ( [resource $link_identifier] )
●
Describes the type of connection in use for the connection,
including the server host name.
www.intellibitz.com [email protected]
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.
www.intellibitz.com [email protected]
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\n", mysql_get_host_info());
?>
The above example will output something similar to:
MySQL host info: Localhost via UNIX socket
www.intellibitz.com [email protected]
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.
www.intellibitz.com [email protected]
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\n", mysql_get_proto_info());
?>
The above example will output something similar to:
MySQL protocol version: 10
www.intellibitz.com [email protected]
mysql_get_server_info
●
Get MySQL server info
●
string mysql_get_server_info ( [resource $link_identifier] )
●
Retrieves the MySQL server version.
●
Parameters
– link_identifier
●
The MySQL connection. If the link identifier is
not specified, the last link opened by
mysql_connect() is assumed. If no such link
is found, it will try to create one as if
mysql_connect() was called with no
arguments. If by chance no connection is
found or established, an E_WARNING level
warning is generated.
www.intellibitz.com [email protected]
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\n", mysql_get_server_info());
?>
The above example will output something similar to:
MySQL server version: 4.0.1-alpha
www.intellibitz.com [email protected]
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.
www.intellibitz.com [email protected]
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.
www.intellibitz.com [email protected]
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.
www.intellibitz.com [email protected]
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.
www.intellibitz.com [email protected]
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\n", mysql_insert_id());
?>
www.intellibitz.com [email protected]
mysql_list_dbs
●
List databases available on a MySQL server
●
resource mysql_list_dbs ( [resource $link_identifier] )
●
Returns a result pointer containing the databases available
from the current mysql daemon.
●
function to traverse this result pointer, or any function for
result tables, such as mysql_fetch_array().
www.intellibitz.com [email protected]
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.
www.intellibitz.com [email protected]
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 . "\n";
?>
The above example will output something similar to:
database1
database2
database3
www.intellibitz.com [email protected]
mysql_list_fields
●
List MySQL table fields
●
resource mysql_list_fields ( string $database_name, string
$table_name [, resource $link_identifier] )
●
Retrieves information about the given table name.
●
This function is deprecated. It is preferable to use
mysql_query() to issue a SQL SHOW COLUMNS FROM
table [LIKE 'name'] statement instead.
www.intellibitz.com [email protected]
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.
www.intellibitz.com [email protected]
mysql_list_fields
Alternate to deprecated mysql_list_fields()
<?php This example will output something
similar to:
$result = mysql_query("SHOW COLUMNS FROM sometable");
Array
if (!$result) { (
[Field] => id
[Type] => int(7)
echo 'Could not run query: ' . mysql_error(); [Null] =>
[Key] => PRI
exit; [Default] =>
[Extra] =>
} auto_increment
)
if (mysql_num_rows($result) > 0) { Array
(
while ($row = mysql_fetch_assoc($result)) { [Field] => email
[Type] => varchar(100)
[Null] =>
print_r($row); [Key] =>
[Default] =>
} [Extra] =>
)
}
?>
www.intellibitz.com [email protected]
mysql_list_process
●
List MySQL processes
●
resource mysql_list_processes ( [resource $link_identifier] )
●
Retrieves the current MySQL server threads.
●
Parameters
– link_identifier
●
The MySQL connection. If the link identifier is
not specified, the last link opened by
mysql_connect() is assumed. If no such link
is found, it will try to create one as if
mysql_connect() was called with no
arguments. If by chance no connection is
found or established, an E_WARNING level
warning is generated.
www.intellibitz.com [email protected]
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\n", $row["Id"], $row["Host"], $row["db"],
$row["Command"], $row["Time"]);
} The above example will output something similar
to:
mysql_free_result($result);
1 localhost test Processlist 0
4 localhost mysql sleep 5
?>
www.intellibitz.com [email protected]
mysql_list_tables
●
List tables in a MySQL database
●
resource mysql_list_tables ( string $database [, resource
$link_identifier] )
●
Retrieves a list of table names from a MySQL database.
●
This function is deprecated. It is preferable to use
mysql_query() to issue a SQL SHOW TABLES [FROM
db_name] [LIKE 'pattern'] statement instead.
www.intellibitz.com [email protected]
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.
www.intellibitz.com [email protected]
mysql_list_tables
mysql_list_tables() alternative example if (!$result) {
<?php echo "DB Error, could not list tables\n";
$dbname = 'mysql_dbname'; echo 'MySQL Error: ' . mysql_error();
if (!mysql_connect('mysql_host', 'mysql_user', exit;
'mysql_password')) {
}
echo 'Could not connect to mysql';
while ($row = mysql_fetch_row($result)) {
exit;
echo "Table: {$row[0]}\n";
}
}
$sql = "SHOW TABLES FROM $dbname";
mysql_free_result($result);
$result = mysql_query($sql);
?>
www.intellibitz.com [email protected]
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.
www.intellibitz.com [email protected]
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);
?>
www.intellibitz.com [email protected]
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().
www.intellibitz.com [email protected]
mysql_num_rows
●
Parameters
– result
The result resource that is being evaluated.
●
www.intellibitz.com [email protected]
mysql_num_rows
<?php
$link = mysql_connect("localhost", "mysql_user", "mysql_password");
mysql_select_db("database", $link);
$result = mysql_query("SELECT * FROM table1", $link);
$num_rows = mysql_num_rows($result);
echo "$num_rows Rows\n";
?>
www.intellibitz.com [email protected]
mysql_pconnect
●
Open a persistent connection to a MySQL server
●
resource mysql_pconnect ( [string $server [, string
$username [, string $password [, int $client_flags]]]] )
●
Establishes a persistent connection to a MySQL server.
●
mysql_pconnect() acts very much like mysql_connect() with
two major differences.
●
First, when connecting, the function would first try to find a (persistent) link
that's already open with the same host, username and password. If one
is found, an identifier for it will be returned instead of opening a new
connection.
●
Second, the connection to the SQL server will not be closed when the
execution of the script ends. Instead, the link will remain open for future
use (mysql_close() will not close links established by mysql_pconnect()).
●
This type of link is therefore called 'persistent'.
www.intellibitz.com [email protected]
mysql_pconnect
●
Parameters
– server
The MySQL server. It can also include a port
●
www.intellibitz.com [email protected]
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.
www.intellibitz.com [email protected]
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.
www.intellibitz.com [email protected]
mysql_ping
/* Make sure the connection is still alive, if not, try to
<?php reconnect */
set_time_limit(0); if (!mysql_ping($conn)) {
$conn = mysql_connect('localhost', echo 'Lost connection, exiting after query #1';
'mysqluser', 'mypass');
exit;
$db = mysql_select_db('mydb');
}
/* Assuming this query will take a long
mysql_free_result($result);
time */
/* So the connection is still alive, let's run another query */
$result = mysql_query($sql);
$result2 = mysql_query($sql2);
if (!$result) {
?>
echo 'Query #1 failed, exiting.';
exit;
www.intellibitz.com [email protected]
mysql_real_escape_string
●
Escapes special characters in a string for use in a SQL
statement
●
string mysql_real_escape_string ( string $unescaped_string
[, resource $link_identifier] )
●
Escapes special characters in the unescaped_string, taking
into account the current character set of the connection
so that it is safe to place it in a mysql_query(). If binary
data is to be inserted, this function must be used.
●
mysql_real_escape_string() calls MySQL's library function
mysql_real_escape_string, which prepends backslashes
to the following characters: \x00, \n, \r, \, ', " and \x1a.
●
This function must always (with few exceptions) be used to
make data safe before sending a query to MySQL.
www.intellibitz.com [email protected]
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.
www.intellibitz.com [email protected]
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));
?>
www.intellibitz.com [email protected]
mysql_stat
●
Get current system status
●
string mysql_stat ( [resource $link_identifier] )
●
mysql_stat() returns the current server status.
www.intellibitz.com [email protected]
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.
www.intellibitz.com [email protected]
mysql_stat <?php
$link = mysql_connect('localhost', 'mysql_user',
'mysql_password');
Return Values
●
www.intellibitz.com [email protected]
mysql_tablename
●
Return Values <?php
– The name of the table
mysql_connect("localhost", "mysql_user",
on success, or "mysql_password");
FALSE on failure. $result = mysql_list_tables("mydb");
$num_rows = mysql_num_rows($result);
for ($i = 0; $i < $num_rows; $i++) {
echo "Table: ", mysql_tablename($result, $i),
"\n";
mysql_free_result($result);
?>
www.intellibitz.com [email protected]
mysql_thread_id
●
Return the current thread ID
●
int mysql_thread_id ( [resource $link_identifier] )
●
Retrieves the current thread ID. If the connection is
lost, and a reconnect with mysql_ping() is
executed, the thread ID will change. This means
only retrieve the thread ID when needed.
www.intellibitz.com [email protected]
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.
www.intellibitz.com [email protected]
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\n", $thread_id);
?>
The above example will output something similar to:
current thread id is 73
www.intellibitz.com [email protected]
mysql_unbuffered_query
●
Send an SQL query to MySQL, without fetching and buffering the result
rows
●
resource mysql_unbuffered_query ( string $query [, resource
$link_identifier] )
●
mysql_unbuffered_query() sends a SQL query query to MySQL, without
fetching and buffering the result rows automatically, as
mysql_query() does. On the one hand, this saves a considerable
amount of memory with SQL queries that produce large result sets.
On the other hand, you can start working on the result set
immediately after the first row has been retrieved: you don't have to
wait until the complete SQL query has been performed. When using
multiple DB-connects, you have to specify the optional parameter
link_identifier.
www.intellibitz.com [email protected]
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.
www.intellibitz.com [email protected]
CHAPTER 10
www.intellibitz.com [email protected]
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.
www.intellibitz.com [email protected]
PHP databse abstraction layer
●
Web browser
●
●
Apache/IIS
●
PHP engine
●
Pear DB
●
DB extension
●
Mysql ,sqlite
●
●
DB server
www.intellibitz.com [email protected]
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
www.intellibitz.com [email protected]
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
www.intellibitz.com [email protected]
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.
www.intellibitz.com [email protected]
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.
www.intellibitz.com [email protected]
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.
www.intellibitz.com [email protected]
Error handling in PEAR
●
DB::isError () 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.
www.intellibitz.com [email protected]
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.
www.intellibitz.com [email protected]
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.
www.intellibitz.com [email protected]
CHAPTER 11
www.intellibitz.com [email protected]
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.
www.intellibitz.com [email protected]
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.
www.intellibitz.com [email protected]
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 .
www.intellibitz.com [email protected]
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.
www.intellibitz.com [email protected]
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.
www.intellibitz.com [email protected]
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
www.intellibitz.com [email protected]
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()
www.intellibitz.com [email protected]
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
www.intellibitz.com [email protected]
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
www.intellibitz.com [email protected]
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
www.intellibitz.com [email protected]
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.
www.intellibitz.com [email protected]
CHAPTER 12
www.intellibitz.com [email protected]
Handling Dates And Times
●
Displaying the Date or Time.
●
Parsing a Date or Time.
●
Dates and Times in Forms.
www.intellibitz.com [email protected]
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.
www.intellibitz.com [email protected]
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.
www.intellibitz.com [email protected]
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.
www.intellibitz.com [email protected]
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.
www.intellibitz.com [email protected]
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.
www.intellibitz.com [email protected]
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.
www.intellibitz.com [email protected]
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
www.intellibitz.com [email protected]
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.
www.intellibitz.com [email protected]
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 ( ).
www.intellibitz.com [email protected]
Chapter summary
●
Making an epoch timestamp with strtotime().
●
Displaying form elements to allow for date or time input.
www.intellibitz.com [email protected]
CHAPTER 13
www.intellibitz.com [email protected]
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.
www.intellibitz.com [email protected]
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)
www.intellibitz.com [email protected]
date_create
●
Returns new DateTime object
●
DateTime date_create ( [string $time [, DateTimeZone
$timezone]] )
●
DateTime DateTime::__construct ( [string $time [,
DateTimeZone $timezone]] )
www.intellibitz.com [email protected]
date_create
●
Parameters
– time
String in a format accepted by strtotime(),
●
defaults to "now".
– timezone
●
Time zone of the time.
●
Return Values
– Returns DateTime object on success or FALSE on
failure.
www.intellibitz.com [email protected]
date_date_set
●
Sets the date
●
void date_date_set ( DateTime $object, int $year, int
$month, int $day )
●
void DateTime::setDate ( int $year, int $month, int $day )
www.intellibitz.com [email protected]
date_date_set
●
Parameters
– object
●
DateTime object.
– year
●
Year of the date.
– month
●
Month of the date.
– day
Day of the date.
●
●
Return Values
●
Returns NULL on success or FALSE on
failure.
www.intellibitz.com [email protected]
date_default_timezone_get
●
Gets the default timezone used by all date/time functions in
a script
●
string date_default_timezone_get ( void )
www.intellibitz.com [email protected]
date_default_timezone_get
The TZ environment variable (if non empty)
–
– The date.timezone ini option (if set)
– "magical" guess (if the operating system supports it)
– If none of the above options succeeds, return UTC
●
Return Values
– Returns a string
www.intellibitz.com [email protected]
date_default_timezone_set
●
Sets the default timezone used by all date/time functions in
a script
●
bool date_default_timezone_set ( string
$timezone_identifier )
●
date_default_timezone_set() sets the default timezone
used by all date/time functions.
www.intellibitz.com [email protected]
date_default_timezone_set
●
Parameters
– timezone_identifier
●
The timezone identifier, like UTC or
Europe/Lisbon. The list of valid identifiers is
available in the Appendix I, List of Supported
Timezones.
●
Return Values
– This function returns FALSE if the
timezone_identifier isn't valid, or TRUE otherwise.
www.intellibitz.com [email protected]
date_format
●
Returns date formatted according to given format
●
string date_format ( DateTime $object, string $format )
●
string DateTime::format ( string $format )
www.intellibitz.com [email protected]
date_format
●
Parameters
– object
●
DateTime object.
format
–
– Format accepted by date().
●
Return Values
– Returns formatted date on success or FALSE on
failure.
www.intellibitz.com [email protected]
date_modify
●
Alters the timestamp
●
void date_modify ( DateTime $object, string $modify )
●
void DateTime::modify ( string $modify )
●
Parameters
– object
●
DateTime object.
– modify
●
String in a relative format accepted by
strtotime().
●
Return Values
– Returns NULL on success or FALSE on failure.
www.intellibitz.com [email protected]
date_offset_get
●
Returns the daylight saving time offset
●
int date_offset_get ( DateTime $object )
●
int DateTime::getOffset ( void )
●
Parameters
– object
●
DateTime object.
●
Return Values
– Returns DST offset in seconds on success or FALSE
on failure.
www.intellibitz.com [email protected]
date_parse
●
date_parse — Returns associative array with detailed info
about given date
●
array date_parse ( string $date )
●
Parameters
– date
– Date in format accepted by strtotime().
●
Return Values
●
Returns array on success or FALSE on failure.
www.intellibitz.com [email protected]
date_parse
<?php
print_r(date_parse("20061212 10:00:00.5"));
?>
The above example will output:
Array
(
[year] => 2006
[month] => 12
[day] => 12
[hour] => 10
[minute] => 0
[second] => 0
[fraction] => 0.5
[warning_count] => 0
[warnings] => Array()
[error_count] => 0
[errors] => Array()
[is_localtime] =>
www.intellibitz.com [email protected]
date_sun_info
●
Returns an array with information about sunset/sunrise and
twilight begin/end
●
array date_sun_info ( int $time, float $latitude, float
$longitude )
●
Parameters
– time
●
Timestamp.
– latitude
●
Latitude in degrees.
– longitude
●
Longitude in degrees.
www.intellibitz.com [email protected]
get_sun_info
●
Return Values
– Returns array on success or FALSE on failure.
<?php
$sun_info = date_sun_info(strtotime("20061212"), 31.7667, 35.2333);
foreach ($sun_info as $key => $val) {
The above example will output:
echo "$key: " . date("H:i:s", $val) . "\n"; sunrise: 05:52:11
sunset: 15:41:21
} transit: 10:46:46
civil_twilight_begin: 05:24:08
?> civil_twilight_end: 16:09:24
nautical_twilight_begin: 04:52:25
nautical_twilight_end: 16:41:06
astronomical_twilight_begin:
04:21:32
astronomical_twilight_end: 17:12:00
www.intellibitz.com [email protected]
date_sunrise
●
Returns time of sunrise for a given day and location
●
mixed date_sunrise ( int $timestamp [, int $format [, float
$latitude [, float $longitude [, float $zenith [, float
$gmt_offset]]]]] )
●
date_sunrise() returns the sunrise time for a given day
(specified as a timestamp) and location.
www.intellibitz.com [email protected]
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
www.intellibitz.com [email protected]
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.
www.intellibitz.com [email protected]
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
www.intellibitz.com [email protected]
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
www.intellibitz.com [email protected]
date_sunset
●
Returns time of sunset for a given day and location
●
mixed date_sunset ( int $timestamp [, int $format [, float
$latitude [, float $longitude [, float $zenith [, float
$gmt_offset]]]]] )
●
date_sunset() returns the sunset time for a given day
(specified as a timestamp) and location.
www.intellibitz.com [email protected]
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.
www.intellibitz.com [email protected]
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
www.intellibitz.com [email protected]
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] )
www.intellibitz.com [email protected]
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.
www.intellibitz.com [email protected]
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.
www.intellibitz.com [email protected]
date_timezone_set
●
Sets the time zone for the DateTime object
●
void date_timezone_set ( DateTime $object, DateTimeZone
$timezone )
●
void DateTime::setTimezone ( DateTimeZone $timezone )
●
Parameters
– Object ..DateTime object.
– Timezone ..Desired time zone.
●
Return Values
– Returns NULL on success or FALSE on failure.
www.intellibitz.com [email protected]
date
●
Format a local time/date
●
string date ( string $format [, int $timestamp] )
●
Returns a string formatted according to the given format
string using the given integer timestamp or the current
time if no timestamp is given. In other words, timestamp
is optional and defaults to the value of time().
●
Parameters
●
format
– The format of the outputted date string.
www.intellibitz.com [email protected]
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 ISO8601 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
www.intellibitz.com [email protected]
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.
www.intellibitz.com [email protected]
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.
www.intellibitz.com [email protected]
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
)
www.intellibitz.com [email protected]
gettimeofday
●
Get current time
●
mixed gettimeofday ( [bool $return_float] )
●
This is an interface to gettimeofday(2). It returns an
associative array containing the data returned from the
system call.
www.intellibitz.com [email protected]
gettimeofday
●
Parameters
– return_float
●
When set to TRUE, a float instead of an array
is returned.
●
Return Values
– By default an array is returned. If return_float is set,
then a float is returned.
●
Array keys:
– "sec" - seconds since the Unix Epoch
– "usec" - microseconds
– "minuteswest" - minutes west of
Greenwich
– "dsttime" - type of dst correction
www.intellibitz.com [email protected]
gettimeofday
<?php
print_r(gettimeofday());
echo gettimeofday(true);
?>
The above example will output something similar to:
Array
(
[sec] => 1073504408
[usec] => 238215
[minuteswest] => 0
[dsttime] => 1
)
1073504408.23910
www.intellibitz.com [email protected]
gmdate
●
Format a GMT/UTC date/time
●
string gmdate ( string $format [, int $timestamp] )
●
Identical to the date() function except that the time returned
is Greenwich Mean Time (GMT).
www.intellibitz.com [email protected]
●
Parameters
gmdate
– format
The format of the outputted date string. See
●
www.intellibitz.com [email protected]
gmdate
When run in Finland (GMT +0200), the first line below prints "Jan 01 1998 00:00:00", while the second
prints "Dec 31 1997 22:00:00".
<?php
echo date("M d Y H:i:s", mktime(0, 0, 0, 1, 1, 1998));
echo gmdate("M d Y H:i:s", mktime(0, 0, 0, 1, 1, 1998));
?>
www.intellibitz.com [email protected]
CHAPTER 14
CALENDER FUNCTIONS
www.intellibitz.com [email protected]
Calendar functions
●
The calendar extension presents a series of functions to
simplify converting between different calendar formats.
●
The intermediary or standard it is based on is the Julian
Day Count. The Julian Day Count is a count of days
starting from January 1st, 4713 B.C.
●
To convert between calendar systems, you must first
convert to Julian Day Count, then to the calendar system
of your choice. Julian Day Count is very different from the
Julian Calendar!
www.intellibitz.com [email protected]
cal_days_in_month
●
cal_days_in_month —
Return the number of <?php
www.intellibitz.com [email protected]
cal_from_jd
<?php
●
cal_from_jd — Converts from
$today = unixtojd(mktime(0, 0, 0, 8, 16, 2003));
Julian Day Count to a
supported calendar print_r(cal_from_jd($today,
●
array cal_from_jd ( int $jd, int CAL_GREGORIAN));
$calendar ) ?>
●
cal_from_jd() converts the The above example will output:
Julian day given in jd into Array
(
a date of the specified [date] => 8/16/2003
calendar. Supported [month] => 8
[day] => 16
calendar values are [year] => 2003
[dow] => 6
CAL_GREGORIAN, [abbrevdayname] => Sat
[dayname] => Saturday
CAL_JULIAN, [abbrevmonth] => Aug
[monthname] => August
CAL_JEWISH and )
CAL_FRENCH.
www.intellibitz.com [email protected]
cal_info
●
cal_info — Returns information about a particular calendar
●
Description
●
array cal_info ( [int $calendar] )
●
cal_info() returns information on the specified calendar.
●
Calendar information is returned as an array containing the elements
calname, calsymbol, month, abbrevmonth and maxdaysinmonth.
The names of the different calendars which can be used as calendar
are as follows:
●
* 0 or CAL_GREGORIAN - Gregorian Calendar
●
* 1 or CAL_JULIAN - Julian Calendar
●
* 2 or CAL_JEWISH - Jewish Calendar
●
* 3 or CAL_FRENCH - French Revolutionary Calendar
●
If no calendar is specified information on all supported calendars is
returned as an array. This functionality is available beginning with
PHP 5.
www.intellibitz.com [email protected]
call_info
Array
(
<?php [months] => Array
(
$info = cal_info(0); [1] => January [abbrevmonths] => Array
[2] => February (
print_r($info); [3] => March [1] => Jan
[4] => April [2] => Feb
?> [5] => May [3] => Mar
[6] => June [4] => Apr
[7] => July [5] => May
[8] => August [6] => Jun
[9] => September [7] => Jul
[10] => October [8] => Aug
[11] => November [9] => Sep
[12] => December [10] => Oct
) [11] => Nov
[12] => Dec
)
[maxdaysinmonth] => 31
[calname] => Gregorian
[calsymbol] =>
CAL_GREGORIAN
)
www.intellibitz.com [email protected]
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.
www.intellibitz.com [email protected]
easter_date
●
easter_date — Get Unix <?php
timestamp for midnight on
Easter of a given year echo date("MdY", easter_date(1999)); //
●
int easter_date ( [int $year] ) Apr041999
●
Returns the Unix timestamp echo date("MdY", easter_date(2000)); //
corresponding to midnight on Apr232000
Easter of the given year. echo date("MdY", easter_date(2001)); //
●
Since PHP 4.3.0, the year Apr152001
parameter is optional and
defaults to the current year
according to the localtime if ?>
omitted.
www.intellibitz.com [email protected]
easter_days
●
easter_days — Get number of days after March 21 on which Easter
falls for a given year
●
int easter_days ( [int $year [, int $method]] )
●
Returns the number of days after March 21 on which Easter falls for a
given year. If no year is specified, the current year is assumed.
●
Since PHP 4.3.0, the year parameter is optional and defaults to the
current year according to the localtime if omitted.
●
The method parameter was also introduced in PHP 4.3.0 and allows to
calculate easter dates based on the Gregorian calendar during the
years 1582 - 1752 when set to CAL_EASTER_ROMAN. See the
calendar constants for more valid constants.
●
This function can be used instead of easter_date() to calculate Easter
for years which fall outside the range of Unix timestamps (i.e. before
1970 or after 2037).
www.intellibitz.com [email protected]
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
?>
www.intellibitz.com [email protected]
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.
www.intellibitz.com [email protected]
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.
www.intellibitz.com [email protected]
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 (EnglishGregorian)
2 Returns a string containing the abbreviated day of week (EnglishGregorian)
www.intellibitz.com [email protected]
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.
www.intellibitz.com [email protected]
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
www.intellibitz.com [email protected]
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.
www.intellibitz.com [email protected]
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".
www.intellibitz.com [email protected]
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_GER
ESHAYIM.
www.intellibitz.com [email protected]
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".
www.intellibitz.com [email protected]
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).
www.intellibitz.com [email protected]
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.
www.intellibitz.com [email protected]
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.
www.intellibitz.com [email protected]
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.
www.intellibitz.com [email protected]
CHAPTER 15
www.intellibitz.com [email protected]
Classes and Objects
●
Object basics.
●
Defining classes
●
Creating new objects.
●
Creating constructors.
●
Accessing properties and methods.
www.intellibitz.com [email protected]
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.
www.intellibitz.com [email protected]
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.
www.intellibitz.com [email protected]
Defining Classes
●
The special form class,followed by the name of the class.
●
An optional extensional clause, extends and then the name
of the class that should be inherited from.
●
A set of braces containing the variable declaration and
function definitions.
www.intellibitz.com [email protected]
Defining Classes
●
The variable declaration starts with special form var which
is followed by conventional $variable name.
●
The variable declarations in a class can also have an initial
assignments to a constant value.
●
The functions defined in a class are local to the class.
www.intellibitz.com [email protected]
Creating new objects
●
An Object is an instance of a class and the act of creating
object from a class is called instantiation.
●
The objects can be created with new keyword.
●
$objectname = new classname();
●
$objectname is the instance of the class classname.
www.intellibitz.com [email protected]
Creating new object
●
We can invokeor acces the member variables and functions
in the class using -> operator
●
$objectname ->functionname();
www.intellibitz.com [email protected]
__autoload()
●
It is common OOP practice to place each of your class
definition into separate files.
●
It is good practice to group various class definition into
multiple files based on their usage.
●
By doing this you don't need to include one large library file
in every page.
●
You only need to include the files containing the specific
classes that page needs.
www.intellibitz.com [email protected]
__autoload()
●
You can define __ autoload
function that
automatically be called
any time a new object
attempts to be
instantiated.
www.intellibitz.com [email protected]
Constructors
●
Constructor function sets up the initial state of a new object
before it is used.
●
Constructors are used to initialize the member variables in
the class.
●
Classes which have a constructor method call this method
on each newly-created object
www.intellibitz.com [email protected]
Constructors
●
PHP5 allows you to declare a constructor method by
including the member function __construct() .
●
You can also define a constructor by method by including a
function with same name as the class.
www.intellibitz.com [email protected]
Magic functions
● PHP reserves for itself any function with double
underscores prefix(__)as magic functions.
● This provides various automatic features.
● Do not make any of your own functions have a double
underscore,unless you specially wnt to invoke one of this
magic functions.
www.intellibitz.com [email protected]
Destructors
www.intellibitz.com [email protected]
Private members
– The variables and functions in the class can
be declared as private.
– The private variables and functions can be
accessed only by the code within the class.
– An attempt to access the private variables
and functions outside the class gives an
error.
www.intellibitz.com [email protected]
Protected members
– Protected is used for members which are
internal to the object's logic ,but where it
might make sense for inheriting classes to
override them.
www.intellibitz.com [email protected]
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 ( ).
www.intellibitz.com [email protected]
Chapter summary
●
Making an epoch timestamp with strtotime().
●
Displaying form elements to allow for date or time input.
www.intellibitz.com [email protected]
CHAPTER 16
www.intellibitz.com [email protected]
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).
www.intellibitz.com [email protected]
Classes objects
<?php
function is_edible()
// base class with member properties and methods
{
class Vegetable {
return $this>edible;
var $edible;
}
var $color;
function what_color()
function Vegetable($edible, $color="green")
{
{
return $this>color;
$this>edible = $edible;
}
$this>color = $color;
} // end of class Vegetable
}
www.intellibitz.com [email protected]
Classes objects
function is_cooked()
// extends the base class
{
class Spinach extends Vegetable {
return $this>cooked;
var $cooked = false;
}
function Spinach()
} // end of class Spinach
{
?>
$this>Vegetable(true, "green");
}
function cook_it()
{
$this>cooked = true;
}
www.intellibitz.com [email protected]
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.
www.intellibitz.com [email protected]
call_user_method
●
call_user_method — Call a user method on an specific
object [deprecated]
●
Description
●
mixed call_user_method ( string $method_name, object
&$obj [, mixed $parameter [, mixed $...]] )
www.intellibitz.com [email protected]
call_user_method_array
●
call_user_method_array — Call a user method given with
an array of parameters [deprecated]
●
Description
●
mixed call_user_method_array ( string $method_name,
object &$obj, array $paramarr )
www.intellibitz.com [email protected]
class_exists
●
class_exists — Checks if the class has been defined
●
bool class_exists ( string $class_name [, bool $autoload] )
●
This function checks if the given class have been defined.
●
Parameters
– class_name
●
The class name
– autoload
●
Whether to call __autoload or not by default
●
Return Values
– Returns TRUE if class_name is a defined class,
FALSE otherwise.
www.intellibitz.com [email protected]
class_exists
<?php //autoload parameter example
<?php
function __autoload($class)
// Check the class exists before trying to
{ include($class . '.php'); use it
// Check to see if the include declared the class if (class_exists('MyClass')) {
if (!class_exists($class, false)) { $myclass = new MyClass(); } ?>
trigger_error("Unable to load class: $class", E_USER_WARNING);
}
if (class_exists('MyClass')) {
$myclass = new MyClass();
?>
www.intellibitz.com [email protected]
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.
www.intellibitz.com [email protected]
get_class_methods
<?php
class myclass {
// method 2
$class_methods = get_class_methods('myclass');
// constructor
function myfunc2()
// or
function myclass()
{
$class_methods = get_class_methods(new
{
return(true); myclass());
return(true);
} foreach ($class_methods as $method_name) {
}
echo "$method_name\n";
// method 1
}
function myfunc1()
?>
{
The above example will output:
return(true); myclass
myfunc1
} } myfunc2
www.intellibitz.com [email protected]
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.
www.intellibitz.com [email protected]
<?php
get_class_var
$my_class = new myclass();
class myclass {
$class_vars = get_class_vars(get_class($my_class));
var $var1; // this has no default value...
foreach ($class_vars as $name => $value) {
var $var2 = "xyz";
echo "$name : $value\n";
var $var3 = 100;
}
private $var4; // PHP 5
// constructor
?>
function myclass() {
The above example will output:
// change some properties
// Before PHP 4.2.0
var2 : xyz
$this>var1 = "foo"; var3 : 100
// As of PHP 4.2.0
$this>var2 = "bar"; var1 :
var2 : xyz
return true; var3 : 100
} }
www.intellibitz.com [email protected]
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.
www.intellibitz.com [email protected]
get_class
<?php // create an object
class foo { $bar = new foo();
function foo() // external call
{ echo "Its name is " , get_class($bar) , "\n";
// implements some logic // internal call
} $bar>name();
function name() ?>
{ The above example will output:
www.intellibitz.com [email protected]
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.
●
www.intellibitz.com [email protected]
get_declared_classes
●
Note: In PHP 4.0.1, three extra classes are <?php
returned at the beginning of the array: print_r(get_declared_classes());
stdClass (defined in Zend/zend.c),
OverloadedTestClass (defined in ?>
ext/standard/basic_functions.c) and The above example will output
Directory (defined in ext/standard/dir.c). something similar to:
●
Also note that depending on what libraries
Array
you have compiled into PHP, additional (
classes could be present. This means [0] => stdClass
[1] =>
that you will not be able to define your __PHP_Incomplete_Class
own classes using these names. There [2] => Directory
)
is a list of predefined classes in the
Predefined Classes section of the
appendices.
www.intellibitz.com [email protected]
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.
www.intellibitz.com [email protected]
get_declared_interfaces
<?php
print_r(get_declared_interfaces());
?>
The above example will output something similar to:
Array
(
[0] => Traversable
[1] => IteratorAggregate
[2] => Iterator
[3] => ArrayAccess
[4] => reflector
[5] => RecursiveIterator
[6] => SeekableIterator
)
www.intellibitz.com [email protected]
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.
www.intellibitz.com [email protected]
get_object_vars
<?php print_r(get_object_vars($p1));
function getPoint()
class Point2D { $p1>setLabel("point #1");
{
var $x, $y; print_r(get_object_vars($p1));
return array("x" => $this>x,
var $label; ?>
"y" => $this>y,
function Point2D($x, $y) The above example will output:
"label" => $this>label); Array
{ (
} [x] => 1.233
$this>x = $x; [y] => 3.445
[label] =>
} // "$label" is declared but not )
$this>y = $y; Array
defined (
} [x] => 1.233
function setLabel($label) $p1 = new Point2D(1.233, [y] => 3.445
[label] => point #1
3.445); )
{
$this>label = $label;
}
www.intellibitz.com [email protected]
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.
www.intellibitz.com [email protected]
get_parent_class
<?php
class dad {
class child2 extends dad {
function dad()
function child2()
{
{
// implements some logic
echo "I'm " ,
} get_parent_class('child2') , "'s son
too\n";
}
}
class child extends dad {
} The above example will
function child() output:
$foo = new child(); I'm dad's son
{ I'm dad's son too
$bar = new child2();
echo "I'm " , get_parent_class($this) ,
"'s son\n";
} ?>
www.intellibitz.com [email protected]
}
[email protected]
interface_exists
●
interface_exists — Checks if the interface has been defined
●
bool interface_exists ( string $interface_name [, bool
$autoload] )
●
Checks if the given interface has been defined.
●
Parameters
– interface_name
●
The interface name
– autoload
●
Wether to call __autoload or not by default
– Return Values
●
Returns TRUE if the interface given by
interface_name has been defined, FALSE
otherwise.
www.intellibitz.com [email protected]
interface_exists
<?php
// Check the interface exists before trying to
use it
if (interface_exists('MyInterface')) {
class MyClass implements MyInterface
{
// Methods
}
?>
www.intellibitz.com [email protected]
is_a
●
is_a — Checks if the object is of this class or has this class
as one of its parents
●
bool is_a ( object $object, string $class_name )
●
Checks if the given object is of this class or has this class
as one of its parents.
●
Note: The is_a() function is deprecated as of PHP 5 in
favor of the instanceof type operator.
●
Parameters
– object
●
The tested object
– class_name
●
The class name
www.intellibitz.com [email protected]
is_a
<?php
Return Values <?php
●
// create a new object
$WF = new WidgetFactory();
if (is_a($WF,
'WidgetFactory')) {
echo "yes, \$WF is still a
WidgetFactory\n";
}
www.intellibitz.com [email protected]
?>
is_subclass_of
●
is_subclass_of — Checks if the object has this class as one of its
parents
●
bool is_subclass_of ( mixed $object, string $class_name )
●
Checks if the given object has the class class_name as one of its
parents.
●
Parameters
– Object
●
A class name or an object instance
– class_name
●
The class name
– Return Values
●
This function returns TRUE if the object object,
belongs to a class which is a subclass of
class_name, FALSE otherwise.
www.intellibitz.com [email protected]
is_subclass_of
// create a new object
<?php
$WF = new WidgetFactory();
// define a class
$WFC = new WidgetFactory_Child();
class WidgetFactory
if (is_subclass_of($WFC, 'WidgetFactory')) {
{
echo "yes, \$WFC is a subclass of WidgetFactory\n";
var $oink = 'moo';
} else {
}
echo "no, \$WFC is not a subclass of WidgetFactory\n";
// define a child class
class WidgetFactory_Child }
extends WidgetFactory if (is_subclass_of($WF, 'WidgetFactory')) {
{
echo "yes, \$WF is a subclass of WidgetFactory\n";
var $oink = 'oink';
} else {
}
echo "no, \$WF is not a subclass of WidgetFactory\n";
www.intellibitz.com [email protected]
}
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\n";
} else {
echo "no, WidgetFactory_Child is not a subclass of WidgetFactory\n";
?>
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
www.intellibitz.com [email protected]
method_exists
●
method_exists — Checks if the class method exists
●
bool method_exists ( object $object, string
$method_name )
●
Checks if the class method exists in the given object.
www.intellibitz.com [email protected]
method_exists
<?php
$directory = new Directory('.');
●
Parameters
– object var_dump(method_exists($directory,'read'
));
An object instance
●
– method_name ?>
●
The method nameThe above example will output:
– Return Values bool(true)
●
Returns TRUE if the method given by
method_name has been defined for the
given object, FALSE otherwise.
www.intellibitz.com [email protected]
property_exists
●
property_exists — Checks if the object or class has a property
●
Description
●
bool property_exists ( mixed $class, string $property )
●
This function checks if the given property exists in the specified class
(and if it is accessible from the current scope).
●
Note: As opposed with isset(), property_exists() returns TRUE even if
the property has the value NULL.
●
Parameters
– Class - - The class name or an object of the class to test
for
– Property - - The name of the property
●
Return Values
– Returns TRUE if the property exists, FALSE if it doesn't exist or
NULL in case of an error.
www.intellibitz.com [email protected]
property_exists
<?php
class myClass {
public $mine;
private $xpto;
static function test() {
var_dump(property_exists('myClass', 'xpto')); // true, it can be accessed from here
}
var_dump(property_exists('myClass', 'mine')); //true
var_dump(property_exists(new myClass, 'mine')); //true
var_dump(property_exists('myClass', 'xpto')); //false, isn't public
myClass::test();
?>
www.intellibitz.com [email protected]
CHAPTER 17
www.intellibitz.com [email protected]
Working with Files
●
Understanding File Permissions
●
Reading and Writing Entire Files
●
Reading and Writing Parts of Files
●
Working with CSV Files
●
Inspecting File Permissions
●
Sanitizing Externally Supplied Filenames
www.intellibitz.com [email protected]
Understanding File Permissions
●
PHP can open a remote file as easy as you can open a
local file
●
PHP interpreter running inside a webserver, has the
privileges of the webserver account
●
The web server (and the PHP interpreter) need to be able
to read all PHP program files that make your website, but
they shouldn't be able to change them
www.intellibitz.com [email protected]
Reading and Writing Entire Files
●
Use file_get_contents() to read the contents of a file into a
string
●
A local and remote file look the same to file_get_contents()
●
Use file_put_contents() to write a string to a file
●
The kinds of URL that are acceptable to file_put_contents()
are more limited
www.intellibitz.com [email protected]
Reading and Writing part of
Files
●
Use fopen(), fgets(), feof(), and fclose()
●
$fh = fopen ('/home/user/test.txt', 'rb');
●
Use fwrite() to write to a file.. fwrite() doesn't automatically
add a newline on to the end of the string you write
●
Use fgetcsv() to read a line of CSV file
●
Comma separated value file is a type of file that stores
tabular data.
www.intellibitz.com [email protected]
Inspecting File Permissions
●
Use file_exists() to check if file exists
●
Use is_readable() or is_writeable() before retrieving its
contents with file_get_contents()
●
Use $php_errormsg global variable to track error messages
(track_errors must be on)
●
Use identical operator === to compare for same value and
same type
www.intellibitz.com [email protected]
Sanitizing Filenames
●
Special characters must be escaped
●
In filenames the special characters are / (separates
filenames) and .. (go up one directory)
●
Use realpath() to translate obfuscated filename into the real
names
www.intellibitz.com [email protected]
Chapter Summary
●
Understanding where the PHP interpreter's file access
permissions come from
●
Reading and writing entire local and remote files with
file_get_contents()
●
Opening and closing files with fopen() and fclose()
●
Reading a line of a file with fgets()
www.intellibitz.com [email protected]
Chapter Summary
●
Using feof() and a for() loop to read each line in a file
●
Using forward slashes in filenames with all operating
systems
●
Providing different file modes to fopen()
●
Writing data to a file with fwrite ()
●
Reading a line of a CSV file with fgetcsv ()
www.intellibitz.com [email protected]
Chapter Summary
●
Determining a file exists with file_exists()
●
Inspecting file permissions with is_readable() and
is_writeable()
●
Checking for errors returned from file access functions
●
Understanding when to check a return value with the
identical operator (===)
●
Sanitizing externally supplied filenames
www.intellibitz.com [email protected]
CHAPTER 18
GETTEXT FUNCTIONS
www.intellibitz.com [email protected]
GETTEXT FUNCTIONS
●
The gettext functions implement an NLS (Native Language
Support) API which can be used to internationalize your
PHP applications.
www.intellibitz.com [email protected]
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
Return Values
●
The category A string on
success.
www.intellibitz.com [email protected]
dcngettext
●
dcngettext — Plural version of dcgettext
●
string dcngettext ( string $domain, string $msgid1, string
$msgid2, int $n, int $category )
●
This function allows you to override the current domain for
a single plural message lookup.
●
Parameters
– domain
●
The domain
– msgid1
Return Values
– msgid2
– n A string on
– Category success.
www.intellibitz.com [email protected]
dgettext
●
dgettext — Override the current domain
●
Description
●
string dgettext ( string $domain, string $message )
●
●
The dgettext() function allows you to override the current
domain for a single message lookup.
●
Parameters
●
Domain
– The domain
●
message Return Values
– The message
A string on success.
www.intellibitz.com [email protected]
dngettext
●
dngettext — Plural version of dgettext
●
string dngettext ( string $domain, string $msgid1, string
$msgid2, int $n )
●
The dngettext() function allows you to override the current
domain for a single plural message lookup.
●
Parameters
– Domain
●
The domain
– msgid1 Return Values
– msgid2 A string on success.
– n
www.intellibitz.com [email protected]
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.
www.intellibitz.com [email protected]
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.
www.intellibitz.com [email protected]
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.
www.intellibitz.com [email protected]
CHAPTER 19
REGULAR EXPRESSION
www.intellibitz.com [email protected]
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.
www.intellibitz.com [email protected]
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).
www.intellibitz.com [email protected]
Regex can be used for
●
Finding doubled words
●
Checking inputs from web forms
●
Changing date formats
●
Finding incorrect case.
www.intellibitz.com [email protected]
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.
www.intellibitz.com [email protected]
Metacharacters
●
Some characters do not match themselves and are called
metacharacters.
●
.^*+?{[]}\|() is the complete list of metacharacters.
www.intellibitz.com [email protected]
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”
www.intellibitz.com [email protected]
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.
www.intellibitz.com [email protected]
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[ \t\n\r\f\v]
www.intellibitz.com [email protected]
Metacharacters
●
\S matches any non white space characters [^ \t\n\r\f\v]
●
\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 “.”
www.intellibitz.com [email protected]
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.
www.intellibitz.com [email protected]
Quantifier
●
A quantifier after a character or group specifies how often
that preceding expression is allowed to occur.
●
The most common quantifiers are ?,* and +
www.intellibitz.com [email protected]
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.
www.intellibitz.com [email protected]
Quantifier
●
+ The plus sign indicates that there is at least 1 of the
previous expression
– For example “go+gle “ matches
gogle,google,gooogle etc
www.intellibitz.com [email protected]
Metacharacter
●
{m,n} specifies occurrence of the character minimum of m
times and maximum of n times.
– “ab{2,3}” matches abb or abbb
www.intellibitz.com [email protected]
CHAPTER 20
DEBUGGING
www.intellibitz.com [email protected]
Debugging
●
Controlling where errors appear
●
Fixing parse errors
●
Inspecting program data
●
Fixing database errors
www.intellibitz.com [email protected]
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
www.intellibitz.com [email protected]
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
www.intellibitz.com [email protected]
Inspecting Program Data
●
A program can be syntactically correct but logically flawed..
adding checkpoint to display values of variables
●
Use diagnostic print statements
●
Use var_dump() to include array in output
●
Make sure to edit the right file.. use __FILE__ special
constant to check filename
●
ob_start(), ob_get_contents(), ob_end_clean
www.intellibitz.com [email protected]
Fixing Database Errors
●
Use setErrorHandling() with PEAR_ERROR_CALLBACK
●
$db->setErrorHandling (PEAR_ERROR_CALLBACK,
'my_func');
●
The callback function must accept one argument, which is
the error object
●
Invoke getDebugInfo () to get more error info
www.intellibitz.com [email protected]
Chapter Summary
●
Configuring error display for a web browser, a web server
error log, or both
●
Configuring the PHP interpreter's error-reporting level
●
Getting the benefits of a PHP-aware text editor
●
Deciphering parse error messages
●
Finding and fixing parse errors
www.intellibitz.com [email protected]
Chapter Summary
●
Printing debugging information with print, var_dump() and
error_log()
●
Sending var_dump() output to the error log with output
buffering functions
●
Writing a custom database error-handling function
www.intellibitz.com [email protected]
CHAPTER 21
www.intellibitz.com [email protected]
What Else with PHP?
●
Graphics and PDF
●
Shockwave/Flash
●
Sending and Receiving Mail
●
Uploading Files in Forms
●
HTML_QuickForm Form-Handling framework
●
Classes and Objects
●
SQLite
●
Advanced XML Processing
www.intellibitz.com [email protected]
What Else with PHP?
●
Running Shell Commands
●
Encryption
●
Talking to Other Languages
●
IMAP, POP3, and NNTP
●
Command-Line PHP
●
PHP-GTK
www.intellibitz.com [email protected]
Even More with PHP!
●
More extensions, add-ons, library and built-in functions are
available
●
The PHP Manual http://www.php.net/manual
●
The PEAR Package List http://pear.php.net/packages.php
●
The PECL Package List http://pecl.php.net/packages.php
www.intellibitz.com [email protected]
Chapter Summary
●
Printing debugging information with print, var_dump() and
error_log()
●
Sending var_dump() output to the error log with output
buffering functions
●
Writing a custom database error-handling function
www.intellibitz.com [email protected]
IntelliBitz Technologies
Training Division
168, Medavakkam Main Road
Madipakkam, Chennai 91.
PH: +91 044 2247 5106
www.intellibitz.com
[email protected]
www.intellibitz.com [email protected]