Tag Archives: PHP

Notes on the lesson Using the Query String of the the Tuts+ Course PHP Fundamentals by Jeffery Way.

These are my reference notes on the lesson Using the Query String of the the Tuts+ Course PHP Fundamentals by Jeffery Way.

Links

Notes

The query string is everything that comes after the question mark in the URL eg. http://benpearson.com.au/index.php?name=jeffery&job=developer

The query string contains key value pairs eg. name=jeffery and job=developer. They are seperated with and ampersand.

$_GET is a super global.

The following PHP will display the associative array of the $_GET super global.

var_dump($_GET);

 

The $_GET request (also known as a HTTP verb) is only used when you are fetching and displaying data.  It is not used to send data to update a database. You would use $_POST for that.

You need to test that an item exists in the super global before echoing it otherwise PHP will display an error on the page. Here’s an example of how this is done:

if ( isset( $_GET['job'] ) ) {
    echo $_GET['job'];
}

 

Assume all data received from the query string is dangerous as the URL can be edited by the user.

Run everything you echo from the query string through htmlspecialchars() first. This will convert all your special characters into their html entitys eg. < is converted to &lt;

PHP array_merge

Merges the elements of one or more arrays together so that the values of one are appended to the end of the previous one, and returns the resulting array eg.

<?php
$array1 = array("color" => "red", 2, 4);
$array2 = array("a", "b", "color" => "green", "shape" => "trapezoid", 4);
$result = array_merge($array1, $array2);
print_r($result);
?>

The above example will output:

Array
(
    [color] => green
    [0] => 2
    [1] => 4
    [2] => a
    [3] => b
    [shape] => trapezoid
    [4] => 4
)

Note "color" => "red" is overwritten by "color" => "green".

Reference

PHP continue

continue is used within looping structures to skip the rest of the current loop iteration and continue execution at the condition evaluation and then the beginning of the next iteration.

A basic example that prints “13”, skipping over 2.

$arr = array( 1, 2, 3 );
foreach( $arr as $number ) {
    if( $number == 2 ) {
        continue;
    }
    echo $number;
}

continue accepts an optional numeric argument which tells it how many levels of enclosing loops it should skip to the end of. The default value is 1, thus skipping to the end of the current loop.

This code prints “outer, middle, inner. outer, middle, inner. outer, middle, inner. ”

$i = 0;
while ($i++ < 3) {
    echo "outer, ";
    while (1) {
        echo "middle, ";
        while (1) {
            echo "inner. ";
            continue 3;
        }
        echo "This never gets output.";
    }
    echo "Neither does this.";
}

Reference