PHP Summary reference: PHP an MySQL for Dummies by Janet Valade, published by Wiley 2002 |
PHP Advantages:
|
PHP code is enclosed in the HTML tag <?php ... ?>. Sometimes, when short tags are enabled, the briefer <? ... ?> can be used. PHP programs are usually in programs with one of the following extensions: .php (the most common), .phtml, or .php4. PHP code is a sequence of statements. Each statement is terminated with a ';' or '?>' (the PHP closing tag). '{' and '}' can be used to form a block of PHP statements. Error and warning messages are output if there is a syntax problem. The file php.ini determines whether or not warning messages are displayed. PHP is case in-sensitive, except for variable names.Variable names are preceded by a '$', can have any length, and can include letters, numbers (except the 1st character), and underscores. The scope of a variable is the entire program (web page).
variables can be assigned values with the '=' operator. They are dynamically created only on assignments, and the variable $glarf can be dropped via unset($glarf).
Warning messages can be avoided by inserting an '@' at the point where the warning message would be issued.
Constants are set via: define("constant-name", "constant-value"); It is then accessed via constant-name (without quotes).
Mathematical operators +, -, *, /, and % are the same as in C/Java. Parenthesed expressions are the same as well. sprintf is a function returning a formatted string, and works similarly to C's printf. The number_format function formats a number with commas. The 2nd parameter, after the value expression is the number of decimal places.
Strings can be enclosed in either single or double quotes. The backslash escape is the same as in C/Java strings in double quoted strings, but only "\'" is the only non-literal in single quoted strings. Double quoted strings are also different in that variables in them are evaluated first. Strings are concatenated with the "." operator.
Dates and times are also supported the same as in UNIX (number of seconds from 1970.0). The function date converts a timestamp into a specified format. For example, date("yyyy/m/d") might return 2003/05/09. If a 2nd parameter is passed, that timestamp is converted to the format specified in the 1st parameter. The following summarizes the date formatting characters:
M | Abbreviated Month, like Jan | F | unabbreviated Month, like January | m | 2 digit month, like 01 |
n | month number, like 1 | d | 2 digit day of month | j | day of month, like 1 |
l | Day of week, like Friday | D | Day of week, like Fri | w | 1-digit day of week, 0=Sunday |
Y | year, like 2002 | y | 2-digit year, like 02 | g | hour in range 1-12 |
G | hour in range 0-24 | h | hour in range 01-12 | H | hour in range 00-24 |
i | minutes in range 00-59 | s | seconds in rand 00-59 | a | am orpm |
A | AM or PM |
The function time() returns the current timestamp. The function mktime(h,m,s,mo,d,y) manufactures a particular timestamp. The time between Xmas 2020 and today would be mktime(12,0,0,12,25,2020) - time(). The correct format of date for MySQL is "yyyy-m-d", "yyyy.m.d", or "yyyy/m/d". An alternative method for obtaining a formmatted current datetime is enclosing a format in parens: ("yyyy-m-d"). If a 2nd timestamp parameter follows the format inside the parens, that timestamp is formatted. For example, if you set $today=("yyyy-m-d"); you can then do the following SQL query: UPDATE Member SET createDate="$today"Conditionals are also supported in PHP, much the same as in C/Java. The standard comparison operator are supported: ==, >, >=, <, <=, !=, <>. Both numbers and strings can be compared. Strings are compared case-sensitive alphabetically. Strings can be compared to regular expressions with wildcards with the ereg("pattern", value) function. eregi is the same except it ignors case. Also ereg_replace("pattern", "replace-string", value) replaces pattern with replace-string in value, and ergi_replace does the same, but ignors case. The following lists pattern components:
^ | start of line | $ | end of line | . | any char | ? | preceding is optional |
( ) | enclosed must be somewhere in there | [ ] | all must be one of enclosed chars | [!] | all must not be one of enclosed chars | - | unless at start, all chars in a range |
+ | one or more of preceding | * | zero or more of preceding | { , } | start, end number in range of reps of preceding | \ | following char is literal |
( | ... | ) | set of alternate strings |
Examples:^[A-Z].* is string of at least one char that begins with a capital letter.
^[0-9]{5,5}(\-[0-9]{4,4})?$ is any zip code
^.+@.+\.com$ matches most email addressesConditions can be joined with logical compartors: and, or, xor. They can also be grouped with parens. Or can also be represented with "||", and with "&&".
Comments can be added to the program enclosed between /* and */. Or from "#" or "//" to the end of the line.
SYNTAX
echo item, item, ... outputs the items which can be strings or variables commas are output as a space. If a string is enclosed in double quotes, variables inside are evaluated and output at those places.
++ and -- postfix operators are supported, as are =+, =-, =*, and =/ (pretty lame, eh?)
Bailing out of a program is done with either the exit("message"); or die(message") statements.
Arrays can be made by assigning a value to a variable followed by []. For example: $x[1]="glarf"; $x[2]="foo"; An array is a list of key/value pairs. Keys can also be words. When using $x[]="glarf", the "glarf" is assigned to $x[0]. Alternatively, one can do $x = array("glarf", "foo"); or $capitals = array("CA" => "Sacramento", "AZ" => "Tucson", ... ); To remove a value from an array, use unset. For example, unset($capitals["CA"]). Arrays can be sorted with the sort statement for numerically indexed arrays, and asort for arrays indexed with words. For example, asort($captitals); rsort, arsort do reverse sorts. ksort, krsort sort by key. usort($array-name, function-name) sorts by a function.
The list statement can be used to assign array values to variables: list($firstval, $secondval, $thirdval) = $array-name; This is the same as $firstval = $array-name[0], $secondval = $array-name[1], ... To get the keys of an array, use extract($array-name); This generates variables from the words used as indeces, and assigns them the value of the corresponding array value. For example: after extract($capitals);, there is a variable $AZ with the value "Tucson". Array values are referenced either using a foreach (see below), or using pointers: current($array-name) is the value of the array at the "current" index. next($array-name) advances the pointer, prev($array-name) decrements. reset($array-name) moves the pointer to the first value and end($array-name) moves to the last value in the array.
Multidimensional arrays are also supported, and referenced by $array-name[index-1][index-2]...
foreach ($array-name as [$key-name =>] $value-name){ ... statement(s)... } The variable $value-name contains the current array value, and may be used in the following block. If $key-name => is specified, the name of the key is put into the variable $key-name.
if ( condition ) statement [elsif ( condition ) statement] [else statement
switch ($variable-name) { case value1: statement; break; case value2: ... } for (init-loop-statement(,s); end-condition; increment-statement(,s)) statement;
while ( condition ) statement
do statement while ( condition );
break and continue are also supported.
function func-name ( [$var1, $var2, ...] ) { ... return [value]; } functions can be defined anywhere on a page (can be referenced before defined).
INTERFACING WITH DATABASE
$connection-name = mysql_connect($host, $user, $password) or die("message".mysql_error()); where $host = computer-name[:port]. if $host is "", localhost is assumed. If port is not specified, the default 3306 is assumed.
mysql_close($connection-name); closes the connection.
$db = mysql_select_db("database-name", $connection) or die("message".mysql_error());
$result = mysql_query($query) or die("message".mysql_error()); most successful queries return 1, but INSERT and UPDATE don't return data. SELECT and SHOW do, and $result points to that data.
A row of data from a select is obtained via $row = mysql_fetch_array($result, type-of-array); type-of-array can be one of MYSQL_NUM (array has numbers as keys), MYSQL_ASSOC (array with key/value pair for each column in the row using column names as keys, MYSQL_BOTH (array with both types of keys -- this is the default). The array can be split into variables named after each column via $row = mysql_fetch_array($result, MYSQL_ASSOC); extract($row); To process each row, use while($row = mysql_fetch_array($result)){ extract($row); ... process row ... } It is best to combine getting db info into a function:
<?php
function getData($key) {
$db = mysql_select_db( "db-name" ) or die("...");
$query = "SELECT * FROM table-name WHERE col-name = '$key'";
$result = mysql_query($query) or die("couldn't execute query");
return mysql_fetch_array($result, MYSQL_ASSOC);
}//or, if you want a 2-dimensional result:
function get_vals($result){
$j = 1;
while (!$row = mysql_fetch_array($result, MYSQL_ASSOC)){
foreach ($row as $colname => $value){ $array[$j][$colname] = $value; }
$j++;
} return &array;
} ?>BUILT-IN ARRAYS
$GLOBALS: All global variables. Example: $GLOBALS['X'] is the variable $X.
$HTTP_POST_VARS or $_POST: All variables passed via the FORM POST method.
$HTTP_GET_VARS or $_GET: All variables passed via the FORM GET method.
$HTTP_COOKIE_VARS or $_COOKIE: the cookie variables
$HTTP_SESSION_VARS or $_SESSION: all variables registered as session variables
$_REQUEST: all variables in $_GET, $_POST, and $_SESSION
For example, $HTTP_POST_VARS["NAME"] is the name parameter passed by a form. A function call should verify the parameters are valid, for example:
function validate(){
$errmsg="";
if ($HTTP_POST_VARS["NAME"]=="") $errmsg=+"Name must be filled in.";
if ($HTTP_POST_VARS["PWD"]=="") $errmsg+="Password is required.";
...
return $errmsg;
}... $redo = validate();
if ($redo != ""){... rebuild old form, but with all valid values filled in....
... for example, echo "<INPUT type=text name=NAME value='$NAME' size=40>"