PHP – basics

PHP BASICS

PHP is a server side scripting language that is run by the web server before sending the html page to the browser. Any file with a .php extension goes through php and any php scripts on the web page get executed and output as html before being sent to the user. PHP is only activated when a request is made to the server.

START LEARNING PHP

Once you’ve got your WAMP or XAMPP set up, find the localhost folder (\c\xampp\htdocs), create a new text file called whatever: start.php and in it type this:

<?php
   phpinfo();

Open the file in your browser using localhost/start.php.  or http://localhost/start.php. It will show a page of php configuration data showing all the core settings for php. Find ‘Configuration file’ and this is where you will find the php configuration file called php.ini.

Next step is to choose your weapon. Dreamweaver, Sublime text, Komodo edit, Coda (for the Mac) and Notepad++ are the main ones.

One more note before we start – why not call all your php files index.php and put them in their own folder. This way:

A) you don’t need to point directly at the .php file, just the folder name.

B) you avoid advertising your technology choice.

OK let’s write some <?php ?>

PHP – THE ECHO COMMAND

<?php echo "Hello World"; ?>

<?php. This is the opening tag which tells your server to expect php code and that the server should use the php engine to interpret the code.

echo “Hello World”; Echo tells php to ‘echo’ the string written in quote marks as html. As always, group strings in single or double quotation marks. And always use a semi colon at the end of a statement to delimit the code.

?>. This is the php closing tag which doesn’t need to be used – but please do as problems may occur.

Here’s an example of a simple page that uses html and php together:

<!DOCTYPE html>
<head>
  <title>A HTML page with PHP code</title>
</head>
<body>
<h1><?php echo 'This is a H1 tag with PHP data'; ?></h1>
<p><?php echo 'This is a paragraph tag with PHP data'; ?></p>
</body></html>

PHP – VARIABLES

 $myPhpVar = 'Yo this is my PHP variable';
echo $myPhpVar;

With variables, we can store data in memory and use it in our scripts. PHP variables are always prefixed with the dollar sign $, and as with JavaScript, cannot contain spaces and only be upper and lower case letters, numbers and underscores. It’s good practice to give variables meaningful names to make coding easier. Oh, and use camelCase if there is more than one word as it’s easier to read.

In the code above, a variable is declared and a value of a string is assigned to it. The variable can be changed thus:

<?php   //Starts PHP script
$myPhpVar;   //Declare variable name
$myPhpVar = 'This is using a variable';  //Give variable a string value
echo $myPhpVar; //Echo the value of the variable as html
$myPhpVar = 'This variable has now changed';  //Change variable value
echo $myPhpVar;  //Echo the new variable value
?>  //End php script

It’s important to note php renders scripts line by line. There will be two lines appear as html because php renders the first line, then the second line. Remember not to overwrite a variable’s value before you want to use it.

PHP – VARIABLE INTERPOLATION

One trick is that you can include the variable inside of a text string if you use “double quotes”. Thus:

$var = 'variable';
echo "$var interpolation";
// outputs variable interpolation

PHP – VARIABLE DATA TYPES

 <?php
$var = 0;  // Integer
$var = 3.14; // Floating point number
$var = "String";  // String
$var = true;  // Boolean
$var = array(100, 200, 300, 400);  // Array

Integers can be either positive or negative whole numbers. Floating point numbers have decimal places and either positive or negative. Strings, surrounded by quotes can be letters, numbers and symbols. Booleans are either true or false but do not enclose in quotes as they turn into a string. An array is a multi-level storage type. We’ll go into more detail here:


 

PHP  – ARRAYS

Arrays store tabular data with a ‘key: value’ syntax. The code below states: create a variable as an array with a string ‘key’ which has the value of  ‘This value’. The => symbol means that php can use the value by accessing the array’s key string.

<?php
$varArray = array('item1' => 'This value');

 

PHP – MULTIPLE ARRAYS

can be constructed in 2 ways:

<?php
$varArray = array(
   'item1' => 'item1 value',
   'item2' => 'item2 value'
   );

or declare the array first, then add key, value pairs later:

<?php
$varArray = array();
$varArray['item1'] = 'item1 value';
$vararray['item2'] = 'item2 value';

Since PHP 5.4 we can now declare arrays with a comma separator thus:

<?php
$varArray = [
         'item1' => 'item1 value', 
         'item2' => 'item2 value'
          ];

PHP – ASSOCIATIVE ARRAYS

An associative array is an array where instead of numbers as indices you use strings.

$birthday['Dan'] = "09-09-1984";
//also can be types this way...
$bday = array('Dan' => '09-09-1984';
// therefore if we want to know my birthday we can look it up using the name as the index...
echo 'my birthday is' . $bday['Dan'];

 


 

PHP COMMENTS

Comments are the same as in JavaScript and C with a subtle difference:

<?php
// Single line comment
# The hash mark is another shell like single line comment.
/* Multiple line comment
   good for hiding code until you want to use it
*/


// Though ALL comments MUST be INSIDE the ?> PHP end tag - otherwise it will be parsed as regular ole HTML
?>
// Woops, all the text on this line will be shown

PHP OPERATORS – STRING CONCATENATOR

The dot ‘.’ is PHP’s string concatenator

<!php
$firstName = "Dan";
$secondName = "Johnson";
$fullName = $firstName . " " . $secondName;
echo $fullName;

PHP OPERATORS – COMPARISON OPERATORS

==  - Checks if two values are the same
<   - Checks if one value is less than another
>   - Checks if one value is greater than another
<=  - Checks if one value is less than or equal to another
>=  - checks if one value is greater than or equal to
!=  - Not equal to
and - Checks if two comparisons are true (also &&)
or  - Checks if one or the other condition is true (also ||)
++  - Add one to the current value ($var = $var + 1)

PHP – CONDITIONAL STATEMENTS

Conditional statements are statements that may or may not execute depending on the result of  comparison. They are called control structures.

PHP – IF STATEMENT

If PHP evaluates a condition to be true, it runs the following block of statements. If false, PHP will skip the block and move on.

<?php
if ($variableA == $variableB) {   // If this is true
   echo 'A is the same as B'      // Do this
}

 

PHP – ELSE STATEMENT

The ELSE statement follows an IF statement.

eg:
if ($this == $isTrue) {
echo 'do this';
} else {
       echo 'do this instead';
}

Here is an example of an IF ELSE statement:

This is a form which sends the users name to the server:

<form action="http:/localhost/name.php" method="post">
 <div><label for="name">Name:
 <input type="text" name="name" id="name"></label></div>
 <div><input type="submit" value="go!" /></div>
</form>

This is the script in the name.php file:

<?php
$name = $_REQUEST['name'];
 if ($name == 'dan')
 { echo 'Welcome to your website Dan!';}
 else
 { echo 'Welcome to Dan\'s website ' . 
 htmlspecialchars($name, ENT_QUOTES, 'UTF-8') . '!'; } ?>

 

PHP – ELSEIF STATEMENT

If there is multiple conditions to check use the elseif statement.

<?php
if ($a == $b) {
   echo 'A is the same as B';
} elseif ($a == $c) {
   echo 'A is the same as C';
} elseif ($a == $d) {
   echo 'A is the same as D';
} else {
   echo 'A is not the same as anything';
}

 

PHP – THE SWITCH STATEMENT

Similar to the elseif statement – the switch statement checks each time if a second value is the same as an initial value.

<?php
switch ($a) {
     case $b:
          echo 'b is the same as a';
          break;
     case $c:
          echo 'c is the same as a';
          break;
     case $d:
          echo 'd is the same as a';
          break;
     default:
          echo 'nothing is the same as a';
          break;
}

Once PHP finds a matching clause, it executes the following statements until it reaches the keyword ‘break’. It then skips the rest of the switch statement and continues on. If it can’t find a match, it executes the code in the default case.

You can also group the cases together, thus:

<?php
switch ($a) {
     case $b:
     case $c:
     case $d:
          echo 'a is the same as b, c or d';
          break;
     default:
          echo 'a is not the same as anything';
}

 


PHP – LOOPS
Loops let us write one statement and execute code multiple times

 

PHP – for LOOP
The for loop is a standard looping mechanism which is best suited if you have a finite number of iterations. You have the following 4 components:

  • The counter (set to a known value).
  • The condition (which executes for as long as the statement is true).
  •  An increment / decrement (to adjust the counter).
  • A statement block (to be executed throughout the loop).
for (declare counter; condition; increment counter)
{ statement/s to execute repeatedly as 
  long as the condition is true }
for (
   $i = 1;                // Counter
   $i < 101;              // Condition
   $i = $i + 1) {         // Increment
      echo $1 . '<br>';   // Statement
}

What happens is, once the condition is true, PHP executes the statement, then goes back and executes the increment, then loops back to the condition and starts again. By this time the variable has changed from ‘1’ to ‘2’ and the process continues until the condition is false.

PHP -while LOOP
While loops only require the condition at the start. It is best suited where there is an unspecified number of iterations. The while loop allows us to determine how many times we can execute a set of statements repeatedly.

while (condition)
{ 
 ⋮statement(s) to execute repeatedly as long as the condition is true
}

But we’ll need a counter to start with:

<?php
$i = 1;                    // counter
while ($i < 101) {         // while this condition is true...
     echo $i . '<br>';     // ...do this
     $i = $i + 1;          // then increment counter & start again 
}

Note: Don’t forget to adjust the counter! When you write a loop, always have some way of stopping it at some point.

Here’s another while loop:

$count = 1;
while ($count <= 10){ // open brace marks the body of the loop
   echo "$count ";   // variable interpolation
   ++$count;}       // ++ is another way to increment the counter

 

PHP – foreach LOOP
The foreach loop takes an array and executes a set of statements for each element

<?php
$anArray = array('Hi', 'World');     // array with 2 elements
foreach ($anArray as $value) {       // assign variable for each
     echo $value . '<br>';           // do this for each element
}

Outputs thus:

Hi
World

 


 

PHP –  TEMPLATES AND INCLUDES

It’s a good idea to separate php code from regular ole html as much as possible. In php you can create a script that will call a separate html file and include the contents of that file at the point of the statement. This makes it easier to work with the different languages.

Here we create a php file with a conditional statement, then include a html file, where we will output the result:

<?php
$output = '';
for ($count = 1; $count <= 10; ++$count)
{
     $output .="$count ";
}

include 'count.html.php';
  • Instead of echoing the numbers, we will add them to a variable ($output). So to start we declare the variable and assign it an empty string.
  • The for loop sets a counter of 1, checks if this is less than or equal to 10, then assigns that result to the end of the variable. The .= operator is a short hand way to add a value to the end of an existing string variable. the long version is thus:
$output = $output . "$count ";
  • The include statement instructs php to execute the contents of the html file at this location.
  • Note that you don’t have to put the php closing tag at the end of a php file. The end of the file itself instructs php that it is the end.

this is what the html file looks like:

<!DOCTYPE html>
<html lang="en">
   <head>
      <meta charset="utf-8">
      <title>Lets count to ten</title>
   </head>
   <body>
       <p>
         <?php echo $output; ?>
       </p>
   </body></html>
   
  

This is the PHP TEMPLATE : a html page with only one snippet of code that inserts dynamically generated values into an otherwise static html page. So you can see that both files are easier to read.

Hey, you can have as many php include statements as you like. With this in mind you can now call the php file a controller.

PHP – THE CONTROLLER

A controller is a php script that responds to a browser request by selecting one of several templates to fill in and send back. A controller contains the logic that controls which template is sent to the browser.

Lets create the files for the single form using this template technique:

<?php
if (!isset($_REQUEST['firstname']))
{
   include 'form.html.php';
}
else 
{
   $firstName = $_REQUEST['firstname'];
   $lastName = $_REQUEST['lastname'];
   if ($firstName == 'dan' and $lastName == 'johnson')
{
   $output = 'Welcome, to you website dude!';
}

This is the contents of the form template:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Form example</title>
</head>
<body>
<form action="" method="post">
<div>
<label for="firstname">First Name:
<input type="text" name="firstname" id="firstname"></label></div>
<div><label for="lastname">Last Name:
<input type="text" name="lastname" id="lastname"></label></div>
<div><input type="submit" value="Go!"></div>
</form>

As you can see, here we leave the action attribute blank. This is so that the browser will submit the two variables to the same url it received it from: the controller that included this template!

 

 


What are PHP Objects?

Object Oriented Programming ‘OOP’ is an advanced style of programming suited to complex programs with lots of moving parts. Most modern programs support this style and some even require it.

A simpler style is called ‘procedural programming’, though some complex programs are written this way (WordPress to name one).

To write in OOP you create an object. So instead of calling a function and calling other functions that use that connection you can create an instance of an object and use the features of the object.

$pdo = new PDO();

The new keyword tells PHP that you want to create a new object. Leave a space then type the class name, which tells PHP what type of object it is. PHP comes with a library of classes that you can create objects from. this tells PHP to create a new object of the PDO class.

In PHP an object is a value (like a string, array etc). You can store an object in a variable or pass it to a function as an argument. Objects have more features than a standard function though. Objects act like arrays in that they hold other values. When we access values of an object, we say that we access the property of the object. And to do that we use arrow notation:

$varObject = new thisClass();         // Create a new object 
$varObject ->thisProperty = 336699;   // Set the property value
echo $varObject ->thisProperty;       // get a propertie's value

Arrays list similar values but objects store a list of related values (such as the properties of a database connection). Object can not only store properties and values, it can also store methods. Methods are essentially a group of functions:

$thisObject = new aClass();   // create an object
$thisOject->aMethod();        // call a method of the object

Just like normal functions, methods can take arguments and return values.

Put simply, properties (a collection of variables), and a selection of functions (methods) that can be accessed using one object makes it a lot easier to work with complicated jobs.

You can even create your custom classes that you can use to create your own objects, but.

 

 

 

 

 

 

 

This is NOT the end of php basics. Though it really does appear to be doesn’t it?

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.