To complete the PHP MVC trio, we must take a look at Model classes. Model classes provide data access and modification functionality to MVC applications, regardless of what the data source is. In other words, the way that the Model classes are used should not reveal to the Controller classes what type of data storage medium is being used. All we wish to provide to the Controller classes is an interface to create, read, delete, and update information. And, by default, our Model classes will perform these CRUD operations in databases.
A Model Base Class
As was done with the Controller base class to provide core functionality to Controller classes, we wish to provide the base functionality to Model classes through a Model base class. In our case, this base functionality will be to connect to a MySQL-compatible database. So, to /app/core, we add Model.php:
class Model{
protected static $_connection = null;
public function __construct(){
if(self::$_connection == null){
$user = 'root';
$password = '';
$host = 'localhost';
$DBName = 'test';
self::$_connection = new PDO("mysql:host=$host;dbname=$DBName", $user, $password);
}
}
}
In the above, we declare and initialize a static attribute $_connection. Static attributes are attributes of the class; only one instance of this attribute exists for the entire set of all objects in this class, i.e., one $_connection for all objects deriving from class Model. Then, one the first run of the constructor for the class, when $_connection is null, it is set to a PDO object connected to a MySQL database, called test, hosted on localhost (the same computer as the one running the PHP, which is your computer if you are running XAMPP locally). The connection is done through the ‘root’ user which has no password, by default, in the XAMPP MySQL installation. You should definitely change these settings!
Let’s not forget to adjust dependencies… modify your app/init.php file to add the new Model class:
For each table in our database, we will wish to build one Model class. We say that these are Model classes, and this is semantically true. In this specific example, they are effectively subclasses of our Model class. To continue our example, we build a model for Item in the Item.php file in the /app/models folder:
class Item extends Model{
var $name;
public function get(){
$SQL = 'SELECT * FROM ITEM';
$stmt = self::$_connection->prepare($SQL);
$stmt->execute();
$stmt->setFetchMode(PDO::FETCH_CLASS, 'Item');
return $stmt->fetchAll();
}
}
In the Item model, we define a $name attribute, such that all objects of this class have this property. Then, the get() method is declared to run a SELECT * FROM ITEM query in the database. The query is defined, then prepared (this will become more useful further along as you read), to then be executed. Then, since SELECT is a read command, there will be records to fetch, we set the fetch mode to return objects of the Item class (this class). Finally, we return an array of Item objects, each representing the records read from the database.
The Database to Match
To complete this example, we must create an Item table in our test database, and have the records have item_id (for instance) and name fields. To accomplish this, go back to your xampp control panel, if this is what you are using, and on the MySQL line, click Start and, once MySQL is highlighted green, click Admin; this will open an instance of phMyAdmin.
If you have a test database in the left menu, click on it (otherwise, you certainly know how to add one). You should be prompted to add a table, if not, expand the test database in the left structure and click on New table.
At the top left, name the table Item. Let’s add the item_id field first by typing that name in the Name column and selecting the checkbox in the A_I colunm (if anything pops up, just click OK). Now let’s add the name of the item by adding name on the following line’s Name column, in the type column, select VARCHAR, in the Size colunm, enter the value 50. Click Save at the bottom right.
Now let’s add test data to the table. Click the Insert tab in the top tabs row. For example, insert ‘milk’ and ‘cookies’ in the Value column for the name field. Click one of the execute buttons on the right.
Making it Work
If you followed along with the posts and implemented the HomeController class as in Controller Classes and An Introduction to Views, all script elements can be called through your browser at http://localhost/ and display your items from the database Item table.
MVC application output is defined in views. Four our PHP MVC application, these views are defined as .php files which mainly contain HTML/CSS/JavaScript code and some PHP to output model elements as required.
It is important to note here that the output formats depend on the application we are trying to build. For example, some applications, APIs, will output JSON data only and leave it up to a separate front-end to render the UI.
Going back to our example, let’s take a look at a simple view, itemList.php, stored in the /app/views/home/ folder:
<html>
<head><title>Item List</title></head>
<body>
<h1>List of items</h1>
<ul>
<?php
foreach($data['items'] as $item){
echo "<li>$item->name</li>";
}
?>
</ul>
</body>
</html>
Much of the above view is directly output HTML code. However, the code between <?php ... ?> generates one <li>...</li> element per item in the $data[‘items’] collection passed to the view by the controller. The foreach loop is one of the most often used repetition instructions in PHP Views. For more information on all that can be done to produce correct output, refer to Hello PHP! and PHP: Getting Acquainted.
The main concern addressed by the Views is to format the data output as per the requirements for the application. This formatting is not a concern that the Model or Controller classes share. Concerns are task categories that should be handled by different classes when the separation of concerns is done correctly.
Tying this to the previous examples
Consider the following controller calling the above-defined view in its index method:
class HomeController extends Controller{ public function index(){ $items = $this->model('item')->get(); $this->view('home/itemList',['items'=>$items]) } }
The above gets data from the storage and access interface through the call to $this->model('item')->get(). We assume item elements contain a name attribute. Then, this data is passed to the view on the following line. Notice how the view name is the folder and file name (less the .php) from the /app/views/ folder.
In the next post, we will look at building a model base class and model item class to match our example.
In MVC applications, HTTP requests lead to Controller method invocation (a.k.a. actions). It is inside controller methods that we define the application logic of an MVC application. In other words, this is where we define much of the application flow, user experience, features, etc.
The Controller base class
Given the orchestration role given to controllers, it will be their concern to invoke actions on Models (the data-handling part of the app) and call Views (the app output). We write the Controller base class to enable these methods.
Method model
Assume all model classes are contained in the /app/models folder in files with their class name.php. Furthermore, the program entry point is the index.php file in the document root.
In the above, we check that the file exists and then require it to finally return a new object of this type. If the class definition does not exist, we return null. For the calling method, this will result in an object of the proper type to call the data processing methods.
Method view
The view method is invoked whenever the application is to produce output.
Assume all view files are located in the /app/views folder in files with their name.php. The program entry point is the index.php file in the document root.
protected function view($name, $data = []){
if(file_exists('app/views/'.$name.'.php')){
include('app/views/'.$name.'.php');
} else {
echo "ERROR: View $view not found!";
}
}
This method checks the existence of a file and then includes it in order to produce the output defined in this file. If the file does not exist, it simply provides feedback to help the developer fix this error.
The complete Controller class
To complete the class, we simply assemble the two methods and wrap them in a class definition as follows:
class Controller{
protected function model($model){
if(file_exists('app/models/' . $model . '.php')){
require_once 'app/models/' . $model . '.php';
return new $model();
}else
return null;
}
protected function view($name, $data = []){
if(file_exists('app/views/'.$name.'.php')){
include('app/views/'.$name.'.php');
} else {
echo "ERROR: View $view not found!";
}
}
}
We will now require the Controller base class and extend it in all of the application classes in the /app/controllers folder.
Example Controller
We now explore the code for an example controller that will extend the Controller base class and use the Controller methods to produce useful results.
class HomeController extends Controller{
public function index(){
$items = $this->model('item')->get();
$this->view('home/itemList',['items'=>$items])
}
}
Given the correct model and view implementations, the above could get all items from a database table and display them in a list output for the user to see and act upon.
Tying it all together
For the controller class to be invoked, it is necessary to make sure that all dependencies are loaded properly and that the program is properly bootstrapped. To take care of the dependencies, we add a file named init.php in the /app folder:
Here, we assume that a Query String parameter, url, contains the URL request. The method
firstly verifies that this parameter exists,
removes any leading “/” character,
sanitizes the URL, and
separates what remains into components, using the “/” character.
The explode function returns an array which would then contain, for instance, if /Teacher/StudentList were called:
['Teacher','StudentList']
Mapping to the Proper Class and Method
In this example application, all controller classes have Controller as a suffix in their names, are all contained in the /app/controllers folder in files with their class name.php. Furthermore, the program entry point is the index.php file in the document root.
The routing is handled in a class named App, written in the file App.php in /app/core as follows:
Once the URL has been parsed into an array, the two first elements are examined to see if they match a Controller class and a method within this controller class. Then the call is made to this method, with any components of the URL leftover in the array as parameters. The process is invoked then the App class is instantiated into an object.
Handling Dependencies
We will add a file where all core dependencies for the application will be listed. We will call this file init.php and place it in the /app folder:
<?php
require_once 'core/App.php';
?>
Tying it all together
In order for the routing to happen, it is necessary to bootstrap the application with a .htaccess file and an index.php file as follows:
<?php
require_once 'app/init.php';
new App();
?>
For example, the URL /Teacher/StudentList would yield a call to the StudentList method of the TeacherController class, without any parameters.
Moreover, the URL /Student/message/Alice would yield a call to the message method of the StudentController class, with one parameter containing the value Alice.
Options are set mainly to change folder access. We set these options on or off respectively with + and –.
Indexes
When allowed, Indexes allows the listing of all files in a folder by accessing this through a request. Therefore, is is especially important to turn this option off (with -) to not reveal the contents of your folders. This will make it harder to exploit your system for evil intents.
MultiViews
When turned on, MultiViews may cause substitute files to be read when others are required that incompletely match the name of those present on the server. In the case of an MVC application, we wish to completely route the application based on requests not matching the files in the system, and furthermore, we wish to still allow resources to be directly loaded by the browser. We must turn off this option.
URL Rewriting
One useful thing Apache can do to make your MVC Web application work well if to rewrite URLs in such a way that the URL becomes a parameter for a PHP application entry point.
RewriteEngine On
Before any URL rewriting happens, we must turn on the rewriting engine.
RewriteBase
The RewriteBase directive specifies the URL prefix to be used for per-directory (htaccess) RewriteRule directives that substitute a relative path. Here, we wish to call the index.php file in the Web server document root.
RewriteCond directive
The RewriteCond directive defines a rule condition. One or more RewriteCond can precede a RewriteRule directive. The following RewriteRule is then only used if the current state of the URI matches its pattern, and if all these conditions are met.
REQUEST_FILENAME is the full local filesystem path to the file or script matching the request.
-f: Is regular file. (alternatively !-f is NOT regular file.) Treats the TestString as a pathname and tests whether or not it exists, and is a regular file.
-d: Is directory. (alternatively !-d is NOT directory.) Treats the TestString as a pathname and tests whether or not it exists, and is a directory.
So the above sets conditions that the requested file is neither a file or folder that exists. This will allow the browser to fetch stylesheets, libraries, etc. from the resources without having to be routed by the MVC application.
RewriteRule
This sets the rule that will be run once the conditions are met. In the above example
RewriteRule ^(.+)$ index.php?url=$1 [QSA,L]
the rule matches the incoming requested URL, except the server address, and sends this URL to index.php, through the URL query string parameter. Any other query string parameters are added by virtue of the QSA (Query String Append) flag. The L flag ensures that no further rules are applied to this request if this rule is run.
One more .htaccess file is needed in the app folder of your MVC application (or wherever your application stores its code which should not be accesses directly through Http requests). The file is as follows:
Options -Indexes
Deny from all
This will not allow users to list contents of any folder as well as disallow direct access to any file through external requests. Only your internal code will be able to include, require and run this code.
Completing the application
Consider the above .htaccess file is in the Apache server document root with the following index.php file:
<?php
var_dump($_GET);
?>
Then, for any request with characters after the / following the hostname, e.g., https://cstutoring.ca/Hello/Alice, the characters would be displayed in an output of the following nature:
array(1) { ["url"]=> string(11) "Hello/Alice" }
We can now use the ‘url’ value to enable routing within the MVC application.
To learn to use conditional test statements to compare numerical and string data values
To learn to use looping statements to repeat statements
To learn to use Boolean operators to create compound conditional test statements
Using Conditional Test Statements
Conditional statements provide a way for scripts to test for certain data values and then to react differently depending on the value found.
Using the if Statement
Use an if statement to specify a test condition and a set of statements to run when a test condition is true.
if ($average > 69)
$Grade="Pass";
print "Grade=$Grade ";
print "Your average was $average";
If $average was equal to 70 then the above would output:
Grad=PassYouraveragewas70
Boolean Expressions
Boolean expressions use Boolean operators to compare values and output is a Boolean value (true or false).
PHP Boolean Operators
Test
Operator
Effect
==
Equal to
!=
Notequal to
<
Lessthan
>
Greater than
>=
Greater thanor
equal to
<=
Lessthan or
equal to
The === and !=== test for equality and inequality, additionally testing for data type. So'1'==1istruewhereas'1'===1isfalse. and '1'!=1isfalseand'1'!==1istrue.
AFullExample…
Consider the following application which receives two grades as input and determines whether their average is above 89. It uses an HTML form for input grades:
Enter First Score <input type="text" size="4" maxlength="7" name="grade1"> Enter Second Score <input type="text" size="4" maxlength="7" name="grade2">
And the receiving inline PHP:
<html>
<head><title>Decisions</title></head>
<body>
<?php
$grade1= $_POST["grade1"];//get the first grade
$grade2= $_POST["grade2"];//gest the second grade
$average = ($grade1 + $grade2) / 2;
if ( $average > 89 ) {
print "Average score: $average You got an A! <br>";
}
$max=$grade1;
if ($grade1 < $grade2) {
$max = $grade2;
}
print ("Your max score was $max");
?>
</body></html>
ComparingStrings
PHP represents strings using character encodings such as the ASCII code values. These encodings provide a standard, numerical way to represent characters in computer storage. Every letter, number, and symbol is translated into a code number.
For instance:
“A” is ASCII code 65, “B” is 66, “C” is 67, and so on and “a” is ASCII code 97, “b” is 98, “c” is 99, and so on.
ASCII “A” is less than ASCII “a,” “B” is less than “b,” and “c” is less than “d”.
ComparingStrings
You can use == operator to check if one string is equal to another. For example,
$sport1 = "Hockey"; $sport2 = "Soccer";
if ($sport1 == $sport2) {
print ("$sport1 is equal to $sport2." );
} else {
print ("$sport1 is not equal to $sport2.");
}
Outputs: Hockey is not equal to Soccer.
Also use <, >, <=, and >= operators to compare string values using ASCII code values. For Example
$sport1 = "Hockey"; $sport2 = "Soccer";
if ($sport1 < $sport2) {
print ("$sport1 is less than $sport2.");
} else {
print ("$sport1 is not less than $sport2.");
}
Outputs Hockey is less than Soccer.
A Full Example …
Consider the following HTML form element that sets the elements “first” and “second” of $_POST
<form action="" method="POST">
First Name: <input type="text" name="first">
Second Name: <input type="text" name="second">
</form>
Consider the receiving code as follows:
<html>
<head>
<title>String Comparison Results</title>
</head>
<body>
<?php
$first = $_POST["first"];
$second = $_POST["second"];
print ("First=$first Second=$second<br>");
if ($first == $second) {
print ("$first and $second are equal");
}elseif ($first < $second) {
print ("$first is less than $second");
}else{ //if ($first > $second)
print ("$first is greater than $second");
}
?>
</body></html>
This code will compare strings and state that the first is equal, less than, or greater than the second.
Above, since we wanted to code more than 2 branches in our application, we used if and else for the first and last and elseif for all others in between.
In the above, each Boolean expression will only be evaluated if all preceding Boolean expressions evaluate to false. Furthermore, the branch which will run is the first one from the top for which the Boolean expression evaluates to true. If and only if all Boolean expressions evaluate to false, the else branch will be run.
Notice the ordering of the clauses in the following example.
$opening = 9;
$lunchstart=12;
$lunchend=13;
$closing=17;
if ($hour < $opening) {
echo "Sorry, it is $hour and we open at $opening.";
} elseif ($hour < $lunchstart) {
echo "Good morning. It is $hour. ";
echo "We can help you until $closing, except ";
echo "lunch, from $lunchstart to $lunchend.";
} elseif ($hour < $lunchend) {
echo "Sorry, we are out to lunch until $lunchend. ";
echo "We close for the day at $closing";
} elseif ($hour < $closing) {
echo "Good afternoon. The time is $hour. ";
echo "Here to help you until $closing";
} else { //if ($hour <= 23) {
echo 'Sorry, we have gone home already. ';
echo "We will be back tomorrow at $opening";
}
Use an else clause with if and possibly one or more elseif clauses. This is to specify the statements to run when all the previous Boolean expressions evaluate to false.
Switch Statement
Use switch statements to run code depending on a set of discrete values, i.e., specific values as opposed to ranges of values.
switch ($rating) {
case 1:
$rated = "Poor";
print "The rating was $rated";
break;
case 2:
$rated = "Fair";
print "The rating was $rated";
break;
case 3:
$rated = "Good";
print "The rating was $rated";
break;
default:
print "Error: that rating does not exist";
}
In the above code, the value of $rating is accessed. If it is 1, the branch labeled case 1: will be run. In general, if the value is x, if there is a label case x:, then this will be the starting point to run code within the switch block. All case blocks are ended with a break statement, otherwise, the PHP interpreter will continue running code from the following case block.
Repetition
Scripts can use loop statements to repeat sections of code. This allows us to write more flexible scripts.
Using a for loop
Use a for loop to repeat a set of statements a specific number of times.
for ( $i = 0; $i < $max; $i++ ) {//The initialization
//Set of statements to repeat
}
When we try to access elements of a collection, such as an array, the foreach loop is easier to use than the for loop. The syntax is as follows:
foreach($collection as $item){
//perform an action on $item
}
When the collection is a dictionary, a collection of key/value pairs, the syntax is slightly different:
foreach($collection as $key => $value){
//perform actions on $key and $value
//the data should be organized such that
//$collection[$key] == $value
}
Usingthewhileloop…
Use the while loop to repeat a set of statements as long as a Boolean expression remains true.
while ($ctr < $max) {
//Set of statements to repeat
}
A while loop will repeat as long as the Boolean expression is true. If the expression initially evaluates to false, then the statements within the loop body will never run.
In order to avoid infinite looping, the statements in the while loop must lead to modifying the value of the boolean expression. In the example above, the value of $ctr must increase to eventually be greater than or equal to $max.
If the loop conditional test always true, then the loop will never end. This is an infiniteloop. This would consume resources on the Web server and possibly slow down other server activity.
PHP supports a set of Boolean operators you can use to create compound Boolean expressions. These may be used within an if statement or a while statement to specify more than one condition. For example, consider the following
while ($x > $max && $found != 1) {...}
BooleanOperators
PHP supports three logical test operators.
1. &&—theANDoperator. Example:
while ($ctr < $max && $flag == 0) {
Whenever either of these expressions is false, the loop will terminate.
2. ||—theORoperator. Example:
if ($ctr != $max || $flag == 0) {...}
Carries out the statements within the if statement, if either $ctr is not equal to $max or $flag, is equal to 0.
3. !—theNOToperator.Used to test whether an
expression is false. Example,
if (!$flag == 0) {...}
This statement is true when $flag is anything except 0.
The following example asks the user to guess a “secret” two-digit combination and uses Boolean operators. The Input HTML form uses the following to set pick1. A similar group sets a variable pick2.
…<font size=4> Pick a number from 1 to 9<br />
<?php
for($i=1;$i<=9;$i++)
print("<input type="radio" name="pick1" value='$i'>$i");
print("<br />Pick a second number<br />");
for($i=1;$i<=9;$i++)
print("<input type="radio" name="pick2" value='$i'>$i");
?></font>
AFullScriptExample
<html>
<head><title>Number Guess Results </title><head>
<body>
<?php
$pick1 =$_POST["pick1"];
$pick2 =$_POST["pick2"];
$combo1=5;
$combo2=6;
if (($pick1 == $combo1) && ($pick2 == $combo2)) {
print ("Congratulations you got both secret numbers $combo1 $combo2!");
} elseif (($pick1 == $combo1) || ($pick2 == $combo2)){
print ("You got one number right.");
} else {
print ("Sorry, you are totally wrong!");
}
print ("You guessed $pick1 and $pick2.");
?>
</body>
</html>
Theternaryoperator
The ternary operator evaluates one expression if the condition is true and another if the condition is false.
(condition?if true:if false);
It is normally used in assignment and sometimes directly for return/output values, e.g.,
$max=($a>=$b?$a:$b); print('The max is ' . ($a>=$b?$a:$b)); return ($a>=$b?$a:$b);
Summary
Use conditional statements to test for certain conditions and, based on the results of the test, to run specific script statements.
Loops expand the types of programming problems that you can solve and allow you to solve some programming problems much more concisely.
Use Boolean AND (&&), OR (||) and NOT (!) operators to build compound Boolean expressions.
When the user submits the form, any data input is sent without encryption, just like any other HTML form field.
Someone with network access could read the password being transferred. This is why HTTPS is a nice thing to have.
Moreover, using the GET method to send a password would make it visible as part of the URL in the HTTP request. One must use POST as the submission method.
Text Areas
The following creates a text area containing 4 rows and 50 columns prefilled with “Comments…”.
Text areas have closing tags. Any text here will appear as default text in text area.
Radio Buttons
Radio buttons are small circles that can select by clicking them with a mouse. Only one within a group can be selected at once. The value that will be sent to the form-processing program is that of the selected item.
The name argument must be the same for all radio buttons operating together. Since both radio buttons above have the same name, they will operate together.
The value argument sets the variable value that will be available to the form-processing script.
The “Yes” item above will be pre-checked when the form is viewed.
Check Boxes
Check boxes are small boxes on a form that create a check mark when the user clicks them. The following item will be pre-checked when the form is viewed:
<input type=”checkbox” name=”travel” value=”None”> None of the above?
Since each checkbox element has the same name, multiple values can be set for the same variable name. The value received by the form-processing script would be a comma-separated list of all items checked. Use explode(…) to convert the list to an array.
As mentioned in the Hello PHP! post, the first questions regarding a coding language should be about syntax. As we saw, in the Hello World! program (see below), PHP delimits instructions with the semicolon (;), PHP delimiters are required in PHP files, and single quotation marks are accepted delimiters for string literals.
<?php
echo 'Hello World!';
?>
Objectives
To understand what PHP is and how a PHP script functions with a Web Server to handle Web Browser requests.
To learn what software and components you need to get started with PHP.
To create and run a simple PHP script.
To learn how to store and access data in PHP variables.
To understand how to create and manipulate numeric and string data/variables.
To review how to create HTML input forms.
To learn how to receive HTML form data with your PHP scripts.
HTML
HTML is used to provide web browser output.
PHP scripts may output any information format; we will output HTML to produce websites that work with web browsers.
How PHP Scripts are Accessed and Interpreted
Exploring the Basic PHP Development Process
The basic steps you can use to develop and publish PHP are:
if you are publishing online:
Create a PHP script file and save it to a local disk.
Use FTP to copy the file to the server.
Access your file using a browser, through server address yourserver/path/filename.
OR,
if you are testing on your local server (e.g., XAMPP):
Create a PHP script file and save it to the local server path.
Ensure that your server is up and running.
Access your file using a browser, through server address 127.0.0.1/path/filename or localhost/path/filename.
Given a script on a local server at c:\XAMPP\htdocs\app-one\start.php where c:\XAMPP is the installation path for XAMPP, htdocs is the server web root, the correct URL for this script would be
Online, htdocs is one of the usual web server root names… start here.
Creating a PHP Script File and Saving It to a Local Disk
You can use a number of different editors to create your PHP script files, e.g., Notepad, Notepad++, TextPad, Sublime Text.
The PHP script starts with a <?php tag and ends with ?>.
Between these tags is a single PHP print statement.
<?php
print("Hello, World!");
?>
The script must be placed in a folder that is under the server web root folder.
Accessing Your File Using a Browser
Given that your script is in a folder within the server document root, you must access it with the domain name of the server plus the correct path of the script relative to the server document root, e.g., given a script at c:\XAMPP\htdocs\app-one\start.php where htdocs is the server document root, and the server is local, the correct URL for this script would be
The output will always tell you the origin of the error. Running this file, you should see a “Parse error: parse error in /… on line 4”. Since there is no compilation process, all errors, even syntax errors occur when you run the program. This is your debugging output.
Embedding HTML in a PHP Script
One way to use PHP is to embed HTML within PHP files. For example:
<html> <head> <title>HTML With PHP Embedded</title> </head> <body>
<?php print ("<br> Using PHP is not hard<br>"); ?> and you can learn to use it quickly!
</body>
</html>
Note that to work properly, this must be a .php file, so that Apache sends the php script to the php interpreter.
Using Backslash (\) to Escape Characters within Strings
Sometimes you want to output an HTML tag that also requires double quotation marks. Use the backslash (“\”) character to signal that the double quotation marks themselves should be output: print (“<font color=\”blue\”>”);
The above statement would output: <font color=”blue”>
Of course, it would be wiser to use single straight quotation marks to avoid having to escape the double straight quotation marks… print (‘<font color=”blue”>’);
Using Comments with PHP Scripts
Comments enable you to include descriptive text along with the PHP script. Comment lines are ignored when the script runs; they do not slow down the run-time. Comments have two common uses:
Describe the overall script purpose.
Describe particularly tricky script lines.
<?php // This is a comment ?>
Can place on Same line as a statement:
<?php print ("Hello, World!"); //Output a line ?>
Another example:
<html> <head><title> Generating HTML From PHP</title></head> <body> <h1> Generating HTML From PHP</h1> <?php // Example script to output HTML tags print ("Using PHP has <i>some advantages:</i>"); print ("<ul><li>Speed</li>"); print ("<li>Ease of use</li>"); print ("<li>Functionality</li></ul>"); //Output bullet list ?> </body> </html>
PHP allows a couple of additional ways to create comments:
<?php phpinfo(); # This is a built-in function ?>
Multiple line comments.
<?php /* phpinfo() is a php function that is part of the base php language. It displays information on the PHP version being used and all configured extentions. */ phpinfo(); ?>
Using PHP Variables
Variables are used to store and access data in computer memory. A variable name is a label used within a script to refer to the data.
In PHP, for example:
$cost = 4.25; $months = 12;
Assigning New Values to Variables
You can assign new values to variables:
$days = 3; $newdays = 100; $days = $newdays;
At the end of these three lines, $days and $newdays both have values of 100.
The Names of Variables
You can select just about any set of characters for a variable name in PHP, but they must:
Use a dollar sign ($) as the first character
Use a letter or an underscore character (_) as the second character. Other characters should be alphanumeric.
Select variable names that make your code self-explanatory, e.g., $counter is more descriptive than $c or $ctr.
Combining Variables and the print Statement
To output the value of $x, write the following PHP statement:
print ("$x");
The following code will output “I would like to buy 6 apples.”
$num=6; print ("I would like to buy $num apples.");
The following code will output “I would like to buy $num apples.”
$num=6;
print ('I would like to buy $num apples.');
If you accidentally use a variable that has not been initialized (never was assigned a value), then it will have no value (called a null value). When a variable with a null value is used in an expression PHP, PHP may not generate an error and may complete the expression evaluation. For example, the following PHP script will output “x= y=4”:
<?php $y = 3; $y = $y+$x+1; // $x has a null value print ("x=$x y=$y"); ?>
Writing Complex Expressions
Operator precedence rules define the order in which the operators get executed. For example,
$x = 5 + 2 * 6;
The value of $x is either 42 or 17 depending on order of evaluation. Multiplication and division operations get executed before addition and subtraction. Therefore, the expression must be evaluated to 17.
PHP’s operator precedence rules are as follows, in order:
<html> <head><title>Expression Example</title></head> <body> <?php $grade1 = 50; $grade2 = 100; $grade3 = 75; //learning arrays will be very beneficial! $average = ($grade1 + $grade2 + $grade3) / 3; print ("The average is $average."); ?> </body> </html>
Working with PHP String Variables
Strings are used in scripts to hold data such as customer names, addresses, product names, and descriptions. Consider the following example, where $name is assigned “Christopher” and the variable $preference is assigned “Milk Shake”:
$name="Christopher"; $preference="Milk Shake";
WARNING: Be Careful Not to Mix Variable Types
Be careful not to mix string and numeric variable types, unless this is your intent. For example, you might expect the following statements to generate an error message, but they will not. Instead, they will output “y=1”:
You can also use double quotation marks to concatenate directly, e.g.,
$firstname="John"; $lastname="Smith"; $Fullname = "$firstname $lastname"; //AND $Fullname2 = $firstname . " " . $lastname; //Have the same effect
Practical Functions for Strings
Function
Description
strlen()
Return the length of the string, e.g.,
$len = strlen($name);
trim()
Removes blank characters from the beginning and end of a string, e.g., $in_name = ” Joe Jackson “; $name = trim($in_name);
strtolower() and strtoupper()
Return the input string in all uppercase or all lowercase letters, respectively, e.g.,
$inquote = “Now Is The Time”;
$lower = strtolower($inquote);
$upper = strtoupper($inquote);
substr()
Return a part of the string, as specified, e.g.,
$part = substr( $name, 0, 5); //return first 5 chars
$part = substr( $name, 2); //return all chars from 3rd
PHP supports both numeric and string variables. String variables use different methods for value manipulation (for example, concatenation) than numeric variables do.
You can use HTML forms to pass data to PHP scripts. HTML form elements include text boxes, text areas, password boxes, check boxes, radio buttons, and selection lists.
PHP scripts can receive form element input values by using a PHP variable name that matches the one specified in the form element’s name argument.
PHP is a great language to develop server-side scripts for data-centric Web applications. PHP can run on all computers and most if not all commercial Web hosting services offer it as part of their platforms.
When studying any coding language, the first thing to learn is the correct syntax to write correct programs in this language. Are instructions separated by newlines or semicolumns? How do we declare variables? How do we set and get values from them? Let’s get started with PHP.
First things first, the development environment is important. Since PHP is a scripting language, we can use any text editor that has proper syntax highlighting for PHP to develop with this language. I like Sublime Text, but there are many editors that provide a great development environment for PHP.
Also part of the development environment is the runtime environment. To this effect, I suggest downloading and installing XAMPP.
Let’s get started
Now that you’ve installed XAMPP (I will assume a default installation on the C: drive of your Windows-run computer) and your favorite text editor, we will write a simple Hello World! program.
First, navigate to C:\xampp\htdocs. This is the root folder where the Apache server instance we will later run will fetch your Web resources. Select all files preinstalled in this folder and delete them. Now create a new file: index.php. In this file, paste the following code:
<?php
echo'Hello World!';
?>
Save your file and now, we will run this script.
Now, let’s start XAMPP: Go to the C:\xampp folder and run the xampp-control.exe program. On the line labeled Apache, click the “Start” button. The Apache label should turn to light green. If it does not, then you are likely to have a port conflict preventing Apache from starting. To find out which program this is, click on the Netstat button on the right.
Assuming Apache is running correctly, we will now run our Hello World! program by starting our favorite browser ant directing it to http://localhost/. You should see “Hello World!” displayed in the browser window.
To explain what’s going on, we have <?php and ?> tags delimiting the PHP code. The echo instruction will output the strings given to it as a parameter. In this case, we are providing the 'Hello World?' string literal.