Physics & Computer Science > CP363 : Home > Implementation Information
Version: 2020-02-06 11:02

CP363 : PHP Notes


Variables and Attributes

Variables are not typed. They are preceded by a $. Variables are case sensitive. Class attributes are identified with ->. Examples:

// These two variables are not the same.
$var = 'world';
$VAR = 42;

// The following initializes a new dcris object. 
// (Assumes a dcris constructor exists.)
$d = new dcris();

// Assigns a value to the public dcris attribute name.
$d->name = 'David';

Arrays

PHP supports simple numeric index arrays (initial index at 0) and associative arrays, which are particularly useful when dealing with database result sets. Both types of arrays can be intitialized with the array function. Examples:

// Initializes a numeric array.
$a = array();
// Adds an element to the array.
$a[] = 5;
// Uses a variable to access an array element.
$i = 0;
print( $a[$i] );

// Initializes an associative array.
$b = array();
// Adds an element to the array.
$b['name'] = "David";
// Uses a variable to access an array element.
$j = 'name';
print( $b[$j] );

Including External Files

There are a number of ways of including external files within a PHP server page. We suggest using the require_once function. File inclusions may be nested (i.e. a file may include another file that includes a third file), and require_once includes an external file only once even if the file is requested multiple times. require_once also causes a fatal error if the file does not exist in the file system. Files must be named according to their position within the file system, not within the web server hierarchy. An example:

<?php
require_once( './dcrisPublicClass.php' );
$d = new dcrisPublic();
$d->nameForm();
?>

The file dcrisPublicClass.php is read into this server page from within the same folder as the server page.


Quoting

PHP treats single and double quotes differently: strings in single quotes are used exactly as they appear; strings in double quotes are parsed by PHP and any variables in them are replaced with their values. Examples:

$name = 'David';
$str = 'My name is $name.';

$str is not parsed and has the value My name is $name. The $name in the string is not treated as a variable, but just as a literal string.

$name = 'David';
$str = "My name is $name.";

$str is parsed and has the value My name is David. The $name in the string is treated as a variable, and replaced with its value.

There is no harm in parsing strings that do not contain variables, but it is slightly less efficient.


Complex Variables in Strings

As shown in the previous examples simple variables can be made part of parsed strings. Complex variables, such as array elements, must be surrounded by brace brackets {} in order to be properly parsed. Examples:

$str = "My name is $_POST['name'].";

causes an error: syntax error, unexpected T_ENCAPSED_AND_WHITESPACE, expecting T_STRING or T_VARIABLE or T_NUM_STRING, because the syntax of the variable is ambiguous.

$str = "My name is {$_POST['name']}.";

works fine. The brace brackets tell PHP that everything contained within them is part of the same variable name.


print_r

The print_r function is particularly useful as a debugging tool. When printing arrays it prints the contents of the arrays in a formatted way. The following example shows the result of printing the associative array returned by preparing and executing the SQL statement SELECT * FROM keyword ORDER BY k_desc:

Array
(
    [0] => Array
        (
            [keyword_id] => 7
            [k_desc] => Arms Control and Non-Proliferation Studies
        )

    [1] => Array
        (
            [keyword_id] => 13
            [k_desc] => Civil-Military Relations
        )

...

    [18] => Array
        (
            [keyword_id] => 16
            [k_desc] => Weapons Systems
        )
}

The formatted print identifies the type of value being printed (in this case a numbered Array containing 19 associative Arrays), their indices and values. (In this case the named indices are the names of the fields in the keyword table.)

When using print_r in a web page it is important to surround the function call with <pre>...</pre> tags in order to preserve the print formatting, as in this example:

print( '<pre>' );
print_r( $data );
print( '</pre>' );

print_r is not normally useful for user output in a production environment.


String Concatenation

Strings can be concatenated using the . and .= operators, as in the following example:

    $greetings = 'Hello ' . $name;

Note that this could be replaced by $greetings = "Hello $name";.

The next example shows concatenating across multiple lines:

    $sql = 'SELECT * FROM member ';
    $sql .= 'WHERE last_name LIKE ? AND first_name LIKE ? AND institution LIKE ? ';
    $sql .= 'ORDER BY last_name, first_name';

The first line defines the original string variable $sql and the subsequent two lines add themselves to the end of $sql. Note the use of the space at the end of the first two lines to make sure that the lines do not run together and that there are spaces between the different clauses.


Generic End of Line

Rather than using the escaped characters \n (line feed), \r (carriage return), or some combination thereof, PHP provides the constant PHP_EOL. PHP_EOL provides an end of line for whatever operating system PHP is running under. It is used as in the following example:

  $str = 'This string has an end of line character.' . PHP_EOL;

The first line defines the original string variable $sql and the subsequent two lines add themselves to the end of $sql.


Passing by Reference

PHP allows passing by reference to functions and methods. It is normally used to pass references to arrays or objects so that the passed array or object can be used directly by the function it is passed to rather than having a copy of it made for the function. The syntax is very simple - use an ampersand & as a prefix to the argument only, as in this example:

  public function printArrayData( &$data ) {
    n = count( $data );
    
    for( $i = 0 ; $i < n ; $i++ ) {
      print( $data[$i] . PHP_EOL );
    }
  }

System Variables

There is a wide number of system variables available in PHP. These are global variables and can be accessed from anywhere in a page. The ones the are particularly useful when working with web pages and databases are the following:

$_SERVER

This is an associate array that keeps track of information about the server and the currectly executing page:

$_POST

This is assigned the values of a form using the POST method. The key names are the names of the form fields:

$_GET

This is assigned the values of a query string attached to a URL. Example:

URL with query string: phpinfo.php?first=David&last=Brown


Working With PHP Errors

Errors are normally not displayed on web pages which can make for a difficult debugging experience. There are a couple of things that can be done to make debugging easier. The first is to tell PHP to display errors through the following commands:

// Comment out of production system.
error_reporting( E_ALL & E_STRICT );
ini_set( 'display_errors', '1' );

These commands need appear only once - they can be put directly into server pages or into any classes referenced by the server pages. Note that these commands will not display fatal errors such as syntax errors, only logic errors. Further, these lines should be removed from production versions of your pages.

Some errors are displayed in the web server's error log. This error log is public so you can view the errors that occur. The following web page shows the most recent PHP errors that have occurred on 'hopper':

http://hopper.wlu.ca/tail.php

You may view this page any time you have an error that is not displayed by error reporting functions above.


Working With MySQL Errors

The PDO and PDOStatement classes both provide error methods you can use to examine errors at the database level. The most immediately useful method is the errorInfo method. This method returns a array containing:

Here is some simple sample code for displaying the output of errorInfo:

$sql = 'SELECT * FROM badTableName';
$stmt = $this->conn->prepare( $sql );
$result = $stmt->execute();

if( !$result ) {
  print( '<pre>' . PHP_EOL );
  // Print the connection errors, if any.
  print( 'Connection errors:' . PHP_EOL );
  print_r( $this->conn->errorInfo() );
  // Print the statement errors, if any.
  print( 'Statement errors:' .PHP_EOL );
  print_r( $stmt->errorInfo() );
  print( '</pre>' . PHP_EOL );
}

The error messages may look something like this:

Array
(
    [0] => 42S02
    [1] => -204
    [2] => [MySQL] SQL0204N  "BADTABLENAME" is an undefined name.  SQLSTATE=42704
)