PHP - The Least You Need to Know

Construction This article is moving along, but still needs work. Anyone is welcome to pitch in. :-)

--Robin Richmond 10:28, 29 November 2015 (EST)

Construction


You don't really need to know PHP to administer a TNG site. I'll bet that most TNG site administrators don't. You can certainly install mods that change TNG's PHP files without knowing PHP. But still, it can be useful to know something about PHP when dealing with mod installation issues that come up from time to time. And many people get into the spirit of mods, and think of small changes that they'd like to make, or perhaps want to just tweak a mod that they install.

And it's often nice to be able to have a sense of what's going on in a program, even if you don't know the language well enough to write programs.

So we present PHP - The Least You Need to Know, to help people who do know HTML and CSS understand what's going on in a PHP program.

Prerequisites

You really needs to know HTML and CSS. You don't have to be an experts, but, I mean, the whole purpose of PHP is to create HTML files (which, of course, often contain, and certainly use CSS). So there's not much point in learning PHP unless you understand what it is producing.

JavaScript? Not so much. It would be a very handy knowledge, since parts of PHP look and act a lot like JavaScript. But if you know HTML and CSS, you've probably at least been introduced to JavaScript.

And you definitely need to know about variables, assignment statements, expressions, conditional expressions, functions, and operators. If you don't, well, you'd better look up "fundamental programming concepts" on the Web, and do a little reading.

PHP

Actually, the first 11 pages (I think that each section is just one page long) in the w3schools.com PHP tutorial at [1] are pretty easy reading, and cover substantially what I cover with my first few sections below. So consider reading that before you read this article, or alongside this article.

Variables, Strings, Statements

  • As in a lot of similar languages, statements end with a semicolon. ;
  • As in a lot of similar languages a block of statements, like in a function, if-else structure, a loop, etc. is wrapped in braces. {..statements..}
  • Letter case in variable and function names IS significant.
  • All variable references in PHP start with a dollar sign $. It seems kind of pointless until you see what PHP does inside strings. Then it'll make a lot of sense.
  • PHP doesn't provide any way at all for you to declare variables. You just have to assign a value to them (or not). That is, undefined variables can almost always be used in expressions, and almost always evaluate to the empty string. (This is a HORRIBLE feature for people used to formal structured programming, and it means that PHP does not notice typos in variable names. But it's convenient.)
  • Strings can be enclosed by double quotes or by single quotes.
...
 $area = $height*$width/2; // Area of a triangle
 // And you've probably already figured out that // starts a comment that
 // runs to the end of the line.
 $myname = 'Robin';
 $doctype = "<!Doctype html>";  /* Actually, TNG used XHTML, but
  that's not important here */
 //Note that /* and */ bracket multi-line comments.
  • This is important: You can put a double quote inside a string enclosed in double quotes by adding a backslash in front of it. (And you can put a backslash in there by adding a backslash in front of it) But you cannot do the same in strings enclosed by single quotes.
 $html = "<input type='text' name='age'>";  // Works just fin.
 $html = "<input type=\"text\" name=\"age\">";  //But this is the way TNG usually does it.

 // The following is bad syntax.  The string ends with the second single-quote, and 
 // then PHP will encounter the t in text, and blow up.
 $html = '<input type=\'text\' name='\age\'>';
  • Finally, PHP statements and strings can wrap onto one or more new lines
 $netenergylost = ($R[$mu] - $R*$g - $lamda) / 
                     (8*$pi*$G*$c^^4);
 /* I did make that formula up, and no, $pi is not a built-in value */

 //Now, I'll put an entire form into a string.
 //The string will contain end-of-line characters, and tabs and/or spaces.
 $html = "<form action=\"actionscript.php\" method="\get\">
             <input type="\hidden\" name="\newsearch\" value=\"1\">
             Search key: <input type=\"text\" ...
           ...
          </form>";

HTML in PHP files

A PHP file is essentially an HTML document with embedded PHP code. Output from the PHP code becomes part of the HTML document. As the server is processing a PHP file, it goes in to "PHP mode" when it sees "<?php". It then expects to see PHP code instead of HTML. And when it sees "?>", it goes back to HTML mode, roughly, like this:

...start with HTML...
<?php
  /* Now it's expecting PHP code, which can output HTML code */
?>
...back to HTML...
<?php
  /* Back to PHP */
?>

echo

This is the PHP command that sends output to the HTML document being created. Thus this PHP file:

<!Doctype html>
<html>
<head>
<title>
<?php
    /* Read the page title from a database */
    /* Store it in the variable $title */
    echo $title;
?>
</title>
</head>
...

would produce this HTML document, assuming that the $title value was "John's Genealogy Site"

<!Doctype html>
<html>
<head>
<title>
John's Genealogy Site
</title>
</head>
...

String Concatenation

Now, this is kind of techy, but it real import for understanding PHP statements. First - "concatenation" is just the technical term for "putting two text string together".

PHP does two things with string concatenation that are atypical. The first is real trivial, but the other involves a kind of string manipulation that I don't think I've seen in a programming language since I used "SNOBAL" in college back in - yes - in the 1970's.

Using a period

In many other languages, the "period" operator separates components of an object or other data structure, and an operator such as + or & is used to concatenate strings. Here are a couple of JavaScript examples. (I'm using JavaScript just because a lot of people who know HTML know at least a little JavaScript. But you don't need to know JavaScript either.)

myval = myobject.myattribute;         //Get an attribute of an object.
pointer = mystring.indexOf("c");      //Use a string method to find where "C" occurs in string.
mynewstring = "prefix" + myoldstring + "suffix"; //Concatenate three strings
htmlcode += "</br>";                  // Add a string to the end of an existing string.

But in PHP, the period is used for concatenation, so it cannot be used for other purposes. I won't go into the syntax for getting object attributes, but here are how the other three lines of code would appear in PHP:

$pointer = strpos("c",$mystring);   //Use a built-in function to find where "c" occurs in string.
$mynewstring = "prefix" . $myoldstring . "suffix"; //Concatenate three strings
$htmlcode .= "</br>";               // Add a string to the end of an existing string.

Evaluation within strings

In PHP, you can simply place the name of a variable inside a string, and the value of the variable will be placed in the string (as long as the character that follow the string are not valid in a variable name). If your variable is an array reference, or the character that follows your variable is valid in a variable name, you must place the variable within braces.

$mynewstring = "($myoldstrings)";            // Enclose a string value within parentheses
$htmlcode = "<title>$pagetitle</title>";
$mynewstring = "$variable1$variable2";       //Concatenate within a string
$mynewstring = "The winner is {$people[1]}"; //An array reference within a string
// Braces are necessary to distingush a trailing alphanumeric character from the variable
$mynewstring = "prefix{$myoldstring}suffix";

Note that for strings to be processed in this way, they must be in double-quotes. Strings in single quotes are not processed, so '$var1$var2' is just an 10-character string with two dollar signs in it, like you're used to seeing in other languages.

If-Then-Else

You don't necessarily need to write if-then-else structures; you just need to understand the structure so that you can be sure to put HTML code where it is needed. The If-Then-Else structure in PHP is essentially identical to that structure in JavaScript and Java. There's no Then keyword, but you have to put your conditional expression in parentheses. See W3 Schools for the basics. Here are some more specific examples, including situations where you have just one statement in a Then or Else clause, and don't need the braces.

// You can see if a variable is undefined or empty or zero by just 
// looking at the variable without comparing to anything
if ($contents) echo "<p>$contents</p>";
// Or perhaps
if ($contents) echo "<p>$contents</p>";
else echo "<p>No results!</p>";
// The "not" operator is the exclamation point.
if (!$title) $title="Home Page";

Conditional Expressions

This statement

echo $content ? $content : "No results";

Is equivalent to this:

if ($contents) echo "<p>$contents</p>";
else echo "<p>No results!</p>";

In the conditional expression, ? and : are operators. The question mark indicates that the following expression will be used if the previous expression is true, and the colon indicates that the following expression will be used if the expression before the question mark is false.

You'll often see conditional expressions in code that displays radio button or selection box options, like this:

// The variable $color contains the current color
$checked = color=="red" ? "checked='checked' : "";
echo "<input type='radio' name='colors' value='red'$checked>Red&nbsp;&nbsp;";
$checked = $color=="blue" ? "checked='checked' : "";
echo "<input type='radio' name='colors' value='blue'$checked>Blue&nbsp;&nbsp;";

And yes, there are ways of doing this in a loop, but I'm not going to try to cover that in this article.

Associative arrays

As in JavaScript and some other languages, arrays can take on text subscripts, in which case they become "associative arrays".

One use of associative arrays is in database records. When you read a database record (as described later in this article), you get an associative array in which the subscripts are field names, and the values are the field values.

Let's say you chose the variable $row to hold the values of a People record. So then, you could display values like this:

<table>
<tr><th>Name:</th><td><?php echo "$row['lastname']}, {$row['firstname']}"; ?></td></tr>
<tr><th>Birthplace:</th><td><?php echo $row['birthplace']; ?></td></tr>
...
</table>

(Notice that we went into and out of PHP mode within one line.)

TNG also uses an associative array for "internationalization"; that is, its ability to handle multiple languages. TNG programs very, very rarely use text string constants for messages or text in a page. They'll use constants for HTML and JavaScript commands, but not for text that needs to be in the user's preferred human language.

TNG does this by filling the $text[] array with text strings whose values are in whatever language has been selected, and whose indexes represent a given string. (How those arrays get populated is a separate question. They point here is that they map generic strings to specific language strings.)

So, for instance, after $text[] is set up with language strings, like this:

English German Dutch
$text['age'] = "Age";

$text['birthplace'] = "Birthplace";

$text['age'] = "Alter";

$text['birthplace'] = "Geburtsort";

$text['age'] = "Leeftijd";

$text['birthplace'] = "Geboorteplaats";

The PHP code can use $text like this:

<form ...>
<?php echo $text['age']; ?>:<input type="input" name="age" size="4"/>
<?php echo $text['birthplace']; ?>:<input type="input" name="birthplace" size="35"/>
...
</form>

Or, in combination with a data record, perhaps like this:

<table>
<?php
echo "<tr><th>{$text['name']}</th><td>{$row['lastname']}, {$row['firstname']}</td></tr>";
echo "<tr><th>{$text['birthplace']}</th><td>{$row['birthplace']}</td></tr>";
...
?>
</table>

(And no, $text is not in any way a special name. It's just what TNG uses.)

Executing a SELECT query

(Obviously, this section needs a LOT more work)

  • $query = "The SELECT statement"} - Define your SQL query
  • $result = tng_query($query);} - Execute it, defining a result set in $result. You can't do much with the result set other than figure out how many records it has, and step through the records.
  • $numberOfResults = tng_num_rows($result); - I'll bet that this function name is self-explanatory
  • $row = tng_fetch_assoc($result);} - Load the first row of the result set into a record set, which you can treat like an associative array.
  • while ( $row = tng_fetch_assoc($result)) { - start a loop through the records-
  • refer to individual fields as $row['fieldname'], or inside strings, "{$row['fieldname']}"}
  • } - close the while loop
  • tng_free_result($result); - clean up memory space by clearing the result set.

Includes

The PHP file that the web browser retrieves from the requested web address is often not the complete program. PHP programs make frequent use of the Include command, which loads (i.e. "includes") another PHP file into the program. This technique makes it easy for multiple PHP programs to share code.

<?php
include("begin.php");    //Grab code that opens the database and initializes several variables
include("adminlib.php"); //Grab some functions used by administrative programs
...
?>

An include file might contains some standard HTML code, such as the code for a navigation bar or footer, or it might contain PHP functions that get called elsewhere in the PHP code.