Difference between revisions of "PHP Basics"

From AQA Computer Science
Jump to: navigation, search
(Creating a Hello World in PHP)
(PHP Constants)
 
Line 155: Line 155:
 
<?php  
 
<?php  
 
define (Message, "<p> Hello World <br> Hola Mundo </p>", true);  
 
define (Message, "<p> Hello World <br> Hola Mundo </p>", true);  
echo mESSAGE;  
+
echo Message;  
 
?>
 
?>
 
</syntaxhighlight>
 
</syntaxhighlight>

Latest revision as of 13:27, 10 October 2019


PHP is a server side scripting language, which is run on the server before the page is served to the client. Essentially it dynamically creates pages on the fly. It can be written on it's own our within normal standard HTML etc. It must be stored on a running webserver and you can only access it via it's URL in a browser. The page the client will receive will have all of the server side elements replaced with the output of the code. If your viewed source you would only see standard HTML and text.

PHP Tags

PHP code must be contained within PHP tags, these tags can be placed anywhere in the page because they are all run before the page is served to the client.

1 <?php // the opening PHP tag
2 // your PHP code
3 ?> // the closing PHP tag

Within your PHP tags every line must be terminated with a semi colon.

PHP Comments

Like all languages PHP supports comments, these can greatly help the maintenance of a project because the developer / programmer may not be the person who maintains the project when it is live. The comments are exactly the same as in C#:

1 // This will comment a single line or include a comment at the end of that single line

Alternatively:

1 /*
2 This will comment all lines
3 between the start and
4 the end comment marks
5 */

Creating a Hello World in PHP

1 <?php echo "hello world"; ?>

hello world

echo is used to write text to the page, you could also echo html code or variables:

1 <?php echo "<p>Hello World<br>Hola Mundo</p>"; ?>

1 <p>Hello World<br>Hola Mundo</p>

Hello World
Hola Mundo

You could also do this:

 1 <html>
 2 <head> <title> Hello World </title> </head>
 3 <body>
 4 <p>
 5 <?php echo "Hello World"; ?>
 6 <br>
 7 <?php echo "Hola Mundo"; ?>
 8 </p>
 9 </body>
10 </html>

 1 <html>
 2 <head> <title> Hello World </title> </head>
 3 <body>
 4 <p>
 5 Hello World
 6 <br>
 7 Hola Mundo
 8 </p>
 9 </body>
10 </html>

Hello World
Hola Mundo

PHP Variables

In PHP you don't declare variables before they are used, instead you just assign it a value and PHP will automatically convert it to the correct data type in the background. All variables in PHP start with the dollar sign ($) followed by the name of the variable. The name must start with a letter, and can only contain alpha-numeric characters and underscore. Variables are also case sensitive.

1 <?php 
2 $name = "wayne";
3 $age = 21;
4 $alive = true; 
5 ?>

The above example creates 3 different variables, notice that you don't need to declare the data types.

1 <?php 
2 $message = "<p> Hello World <br> Hola Mundo </p>"; 
3 echo $message; 
4 ?>

You can join together text using a period . :

1 <?php 
2 $message = "Hello World"; 
3 echo "<p>".$message."</p>; 
4 ?>

Calculations can be performed as normal but PHP will dynamically alter data types to suit. so this:

1 <?php 
2 $number = 5;
3 $text = "5" 
4 echo $number + $text; 
5 ?>

will produce the output 10.

It is also important to note that variables inside double quotes will be displayed as their value, while variables in single quotes will only produce what you wrote. For example:

1 <?php 
2 $a = "Hello";
3 echo "$a<br>" . '$a';
4 ?>
5 //Output:
6 //Hello
7 //$a

PHP Constants

Constants are like variables however once they are declared they cannot be changes or undefined. The name of a constant must start with either an underscore or letter.

1 <?php 
2 define (Message, "<p> Hello World <br> Hola Mundo </p>"); 
3 echo Message; 
4 ?>

You can also include another parameter (true) to make the constant insensitive to the case:

1 <?php 
2 define (Message, "<p> Hello World <br> Hola Mundo </p>", true); 
3 echo Message; 
4 ?>

PHP Operators

Operation Character used Description Example
Equal Performed using == Returns true if both inputs are the same. value == "test"
Not Equal performed using != returns true if both inputs are not the same value != "test"
Less Than Performed using < Returns true if value 1 is less than or equal to value 2. value < 0
Greater Than performed using > Returns true if value 1 is greater than value 2. value > 1
Less Than or Equal Performed using <= Returns true if value 1 is less than or equal to value 2. value <= 0
Greater Than or Equal performed using >= Returns true if value 1 is greater than or equal to value 2. value >= 1
AND Performed using "&" or "&&" Returns true if both inputs are true. true && false = false
OR performed using "|" or "||" returns true if one or both inputs are true. true || false = true
NOT performed using "!" Returns false if true, or true if false. !true = false

PHP Selection

If

The if statement executes some code if one condition is true:

if (condition) {
    code to be executed if condition is true;
}


The example below will output "Have a good day!" if the current time (HOUR) is less than 20:

<?php
$t = date("H");

if ($t < "20") {
    echo "Have a good day!";
}
?>


Else

The if....else statement executes some code if a condition is true and another code if that condition is false.

if (condition) {
    code to be executed if condition is true;
} else {
    code to be executed if condition is false;
}

The example below will output "Have a good day!" if the current time is less than 20, and "Have a good night!" otherwise:

<?php
$t = date("H");

if ($t < "20") {
    echo "Have a good day!";
} else {
    echo "Have a good night!";
}
?>


ElseIf

The if....elseif...else statement executes different codes for more than two conditions.

if (condition) {
    code to be executed if this condition is true;
} elseif (condition) {
    code to be executed if this condition is true;
} else {
    code to be executed if all conditions are false;
}

The example below will output "Have a good morning!" if the current time is less than 10, and "Have a good day!" if the current time is less than 20. Otherwise it will output "Have a good night!":

<?php
$t = date("H");

if ($t < "10") {
    echo "Have a good morning!";
} elseif ($t < "20") {
    echo "Have a good day!";
} else {
    echo "Have a good night!";
}
?>


Switch Case

Use the switch statement to select one of many blocks of code to be executed.

switch (n) {
    case label1:
        code to be executed if n=label1;
        break;
    case label2:
        code to be executed if n=label2;
        break;
    case label3:
        code to be executed if n=label3;
        break;
    ...
    default:
        code to be executed if n is different from all labels;
}

This is how it works: First we have a single expression n (most often a variable), that is evaluated once. The value of the expression is then compared with the values for each case in the structure. If there is a match, the block of code associated with that case is executed. Use break to prevent the code from running into the next case automatically. The default statement is used if no match is found.

<?php
$favcolor = "red";

switch ($favcolor) {
    case "red":
        echo "Your favorite color is red!";
        break;
    case "blue":
        echo "Your favorite color is blue!";
        break;
    case "green":
        echo "Your favorite color is green!";
        break;
    default:
        echo "Your favorite color is neither red, blue, nor green!";
}
?>

PHP Repetition

while Loop

The while loop executes a block of code as long as the specified condition is true.

while (condition is true) {
    code to be executed;
}


The example below first sets a variable $x to 1 ($x = 1). Then, the while loop will continue to run as long as $x is less than, or equal to 5 ($x <= 5). $x will increase by 1 each time the loop runs ($x++_):

<?php 
$x = 1; 

while($x <= 5) {
    echo "The number is: $x <br>";
    $x++;
} 
?>

do...while Loop

The do...while loop will always execute the block of code once, it will then check the condition, and repeat the loop while the specified condition is true.

do {
    code to be executed;
} while (condition is true);


The example below first sets a variable $x to 1 ($x = 1). Then, the do while loop will write some output, and then increment the variable $x with 1. Then the condition is checked (is $x less than, or equal to 5?), and the loop will continue to run as long as $x is less than, or equal to 5:

<?php 
$x = 1; 

do {
    echo "The number is: $x <br>";
    $x++;
} while ($x <= 5);
?>


for Loop

The for loop is used when you know in advance how many times the script should run.

for (init counter; test counter; increment counter) {
    code to be executed;
}

Parameters:

init counter: Initialize the loop counter value test counter: Evaluated for each loop iteration. If it evaluates to TRUE, the loop continues. If it evaluates to FALSE, the loop ends. increment counter: Increases the loop counter value The example below displays the numbers from 0 to 10:

<?php 
for ($x = 0; $x <= 10; $x++) {
    echo "The number is: $x <br>";
} 
?>

foreach Loop

The foreach loop works only on arrays, and is used to loop through each key/value pair in an array.

foreach ($array as $value) {
    code to be executed;
}


For every loop iteration, the value of the current array element is assigned to $value and the array pointer is moved by one, until it reaches the last array element.

The following example demonstrates a loop that will output the values of the given array ($colors):

<?php 
$colors = array("red", "green", "blue", "yellow"); 

foreach ($colors as $value) {
    echo "$value <br>";
}
?>

PHP Functions

A user defined function declaration starts with the word "function":

function functionName() {
    code to be executed;
}

Note: A function name can start with a letter or underscore (not a number).
Tip: Give the function a name that reflects what the function does!
Function names are NOT case-sensitive.

In the example below, we create a function named "writeMsg()". The opening curly brace ( { ) indicates the beginning of the function code and the closing curly brace ( } ) indicates the end of the function. The function outputs "Hello world!". To call the function, just write its name:

<?php
function writeMsg() {
    echo "Hello world!";
}

writeMsg(); // call the function
?>

PHP & Forms - Action to another page

post

The example below displays a simple HTML form with two input fields and a submit button:

<html>
<body>
<form action="welcome.php" method="post">
Name: <input type="text" name="name"><br>
E-mail: <input type="text" name="email"><br>
<input type="submit">
</form>
</body>
</html>

When the user fills out the form above and clicks the submit button, the form data is sent for processing to a PHP file named "welcome.php". The form data is sent with the HTTP POST method.

To display the submitted data you could simply echo all the variables. The "welcome.php" looks like this:

<html>
<body>
Welcome <?php echo $_POST["name"]; ?><br>
Your email address is: <?php echo $_POST["email"]; ?>
</body>
</html>

The output could be something like this:

Welcome John
Your email address is john.doe@example.com

get

The same result could also be achieved using the HTTP GET method:

<html>
<body>
<form action="welcome_get.php" method="get">
Name: <input type="text" name="name"><br>
E-mail: <input type="text" name="email"><br>
<input type="submit">
</form>
</body>
</html>

and "welcome_get.php" looks like this:

<html>
<body>
Welcome <?php echo $_GET["name"]; ?><br>
Your email address is: <?php echo $_GET["email"]; ?>
</body>
</html>

PHP & Forms - Action in same page

post

The example below displays a simple HTML form with two input fields and a submit button:

<html>
<body>
Welcome <?php echo $_POST["name"]; ?><br>
Your email address is: <?php echo $_POST["email"]; ?>
<form action="" method="post">
Name: <input type="text" name="name"><br>
E-mail: <input type="text" name="email"><br>
<input type="submit">
</form>
</body>
</html>

When the user fills out the form above and clicks the submit button, the form data is sent for processing to a PHP file named "welcome.php". The form data is sent with the HTTP POST method.

The output could be something like this:

Welcome John
Your email address is john.doe@example.com

get

The same result could also be achieved using the HTTP GET method:

<html>
<body>
Welcome <?php echo $_GET["name"]; ?><br>
Your email address is: <?php echo $_GET["email"]; ?>
<form action="" method="get">
Name: <input type="text" name="name"><br>
E-mail: <input type="text" name="email"><br>
<input type="submit">
</form>
</body>
</html>