Most of us will have heard of a cookie before, those pesky privacy thieving things which really don’t taste that great, or not. The truth is cookies are vital to the operation of a website and while being reasonably safe and secure do not divulge that much personal information, at least not the personal information that really means anything. In fact about the most personal you can get is asking PHP for the users IP Address, but even that isn’t totally unique to the user.

Anyway back to cookies, cookies are used to store information about a user in the long run (up to 30 days) and sessions are used to store information about user in the short run (until the browser is closed), a session is technically just a temporary cookie, so we’ll start there.

Sessions are most commonly used to store login information so that the website knows who a user is. Most commonly when a user logs in PHP will check that the login information entered by a user matches up with that held in the database, if all the information (username & password) is correct a session can be created to store the login user ID, this way the site will now know that you have logged in and can view certain content.

Storing something as a session is easy.

<?php

//Start the session
session_start();

//Record my name
$_SESSION['my_name'] = 'James';

?>

Let’s split this example into two parts, starting with session_start(). session_start() is a function to tell PHP you are about to use the PHP session functionality, whenever you want to add, edit, view or delete a session you must have already used the session_start() function, further this function has to appear before anything gets outputted to the browser (eg. text, even spaces or new lines).

The second part of this sets the session, the name of the session variable is placed between quotes inside the square brackets. The value of the session is then set after the equals operator (=).

To view the content of this session you would do the following…

<?php

//Start the session
session_start();

//Display my name
echo $_SESSION['my_name'];

?>

Which would output…

James

Any sort of variable (including a session variable) can be cleared by using the unset() function.

<?php

session_start();

unset($_SESSION['my_name']);

?>

There’s also a quick and easy way to delete all session content, session_destroy().

<?php

session_start();

session_destroy();

?>

All session data has now been deleted.

Next up is the cookie, for whatever reason you might want to record information for the user over a fixed amount of time (seconds to a month). To do this we use the setcookie() function in PHP.

<?php

setcookie('my_name', 'James', time() + 3600, '/');

?>

Let’s talk about the parameters, first we have the cookie name ‘my_name’, second we have the cookie value ‘James’, third we have the timestamp for when the cookie should expire. The time() function grabs the amount of seconds that have passed since Unix time (1st Jan 1970), we then add 3600 seconds onto that (3600 seconds = 1 hour) to make the cookie expire one hour from now, finally we set the cookie to be available on all folders on the domain by using ‘/’.

To display the contents of this cookie we would do…

<?php

//Display my name
echo $_COOKIE['my_name'];

?>

To delete the contents of this cookie we have to set the cookie to expire in the past…
<?php

setcookie('my_name', 'James', time() - 1, '/');

?>

As the cookie will have expired one second ago the contents of it are now lost.

During the tutorial Basics of PHP – MySql Query (Select) We used the ‘while’ loop, but we didn’t really talk about what it does that much. Essentially ’while’ and ‘for’ allow us to do something over and over again, quickly and easily. First let’s look at this ‘while’ example.

<?php

$counter = 1;

while($counter <= 10) {

echo 'Number ' . $counter . '<br />';

$counter ++;

}

?> 

In a way ‘while’ and ‘for’ are similar to ‘if’, they are all looking for a condition to be true. In this example we have first set the $counter variable to 1, then we run our ‘while’ loop. ‘While’ continues to execute the code in between the curly brackets provided the $counter variable is less than or equal to 10. Still following? Provided $counter is less than or equal to 10 PHP will display the text “Number ” and then the $counter variable (which will be a number between 1 and 10), and then starts a new line. The $counter variable is then incremented by one, so if the counter was 1 it will not be 2, if it was 2 it will now be 3 ect. Then the ‘while’ loop runs again, checking if $counter is still less than or equal to 10, eventually (after 10 times to be exact) the $counter variable will reach 10 and the ‘while’ loop will not be able to run again. PHP will output this to the browser…

Number 1
Number 2
Number 3
Number 4
Number 5
Number 6
Number 7
Number 8
Number 9
Number 10

The ‘for’ loop is exactly like the ‘while’ loop except it simplifies the process of assigning and incrementing a counter, here is an example of a ‘for’ loop which will output the same as the previous ‘while’ loop.
<?php

for($counter = 1; $counter <= 10; $counter ++) {

echo 'Number ' . $counter . '<br />';

}

?> 

You will notice that all the counter settings are set as parameters inside ‘for’, parameters in ‘for’ are separated by a semicolon. The first parameter sets the variable name to be used as a counter as well as it’s starting value, the second parameter sets the condition that ‘for’ should continue to run under and the third tells ‘for’ what to do after the loop has ran, in this case (and in most) it increments the counter. You will also notice that as the increment is set as a parameter you don’t need to set the counter to be incremented inside the curly brackets.

While this isn’t strictly exclusive to PHP understanding the insides of a MySql query are vital to any developer, whatever their programming language. In the last couple of tutorials we covered MySql Select and MySql Insert but we didn’t talk a lot about the query itself, that is what actually appears as a parameter in the mysql_query() function (eg. “select * from people”). So first let’s talk about the MySql Select query.

select * from people

In this example we are asking MySql to select all the columns from the table people, if you look at the previous tutorial the table people has three columns called contact_id, name & phone_number. By using an asterisks (*) we are asking PHP to select all three of these columns for use.

But what if we don’t want to read all of the columns. Say we only want to look at ‘name’ and ‘phone_number’ and don’t care about ‘contact_id’ we can ask MySql only to return certain columns.

select `name`, `phone_number` from people

The columns we want MySql to return are specified inside a (`) and separated by commas (,).

We can actually ask MySql to return the results in a certain order, say alphabetically or in numerical order (or the opposite to both these).

select `name`, `phone_number` from people order by name asc

‘Order By’ tells MySql we would like the results returned to us in a specific way, ‘name’ specifies we would like to order by the ‘name’ column and ‘asc’ means ascending (starting with ‘a’, then ‘b, c, d’ ect or ’1, 2, 3′ ect). We could ask MySql to return the results descending by using ‘desc’.

Let’s say now we only want MySql to return the phone number for ‘John Doe’.

select `name`, `phone_number` from people where name='John Doe' limit 0, 1

Two new things have been introduced here ‘where’ and ‘limit’. ‘Where’ searches for results which match a parameter, here we are asking MySql to only return results where the column ‘name’ is set to ‘John Doe’. ‘Limit 0, 1′ means MySql will only return the first result. If we set this to ‘limit 0, 2′ MySql will return the first two results. However as there is only one ‘John Doe’ MySql can only return one result so even if you set it to ‘limit 0, 2′ or you don’t set a limit at all you will only get the one result back. This is used to tell MySql to stop looking for other ‘John Doe’s, this can cut down on MySql execution time significantly (especially if you have a large table) and make your program run faster.

Now that we have covered ‘select’ let’s talk about ‘insert’. Here we have the example used in the previous tutorial.

insert into people (`name`, `phone_number`) values ('John Doe', '555-6725')

Here MySql is being told that we want to insert into the table ‘people’ and the columns ‘name’ and ‘phone_number’ (you should always tell MySql the columns you want to insert into and don’t use (*) like in mysql select). ‘Values’ then tells MySql what the values of ‘name’ and ‘phone_number’ are, and they are then given in the next set of brackets.

In the last tutorial we queried our MySql database to select data from it, now we are going to insert data. MySql Insert queries are very easy to use, first of all whenever we want to do something with a database we have to connect to it and select the correct database (refer to previous tutorial for more info).

<pre><?php

$mysql_connection = mysql_connect('localhost', 'username', 'password');

//Check for errors
if(!$mysql_connection) {

die('Could not connect to db: ' . mysql_error());

}
//Select database
mysql_select_db('contacts', $mysql_connection);

?>

Like in the last tutorial we are going to be using the contacts table. Now that we have connected and selected we can run our insert query.


<pre><?php

$mysql_connection = mysql_connect('localhost', 'username', 'password');

//Check for errors
if(!$mysql_connection) {

die('Could not connect to db: ' . mysql_error());

}

//Select database
mysql_select_db('contacts', $mysql_connection);

//Insert into database
mysql_query("insert into people (`name`, `phone_number`) values ('John Doe', '555-6725')");

?>

Just like when we ran the select query in the last tutorial we use the function mysql_query(). Here we are telling PHP that we want to insert into the table ‘people’ and the columns ’name’ and ‘phone_number’, and then we give the values for ‘name’ and ‘phone_number’ as ‘John Doe’ and ’555-6725′. Every time this script runs PHP will insert this data into the MySql database. Try this by refreshing the page multiple times.

Querying a database is where PHP can get fun. If you’re developing a site chances are you will need a database. Database’s are often used to hold user information (like login information) or to record visits to the site. Some of the most complex sites have hundreds of tables each recording vital information.

In this tutorial we will start by learning how to connect to the database and then how to retrieve some information from it (we’ll be creating a contacts database to record people’s phone numbers). To join in you will need to have access to a MySql database & phpMyAdmin, if you have installed WAMP then you will already have this on your computer.

The first thing we are going to do is create a new database and call it contacts, inside the contacts database create a table called people. Inside the table you will need to create three columns called contact_id, name & phone_number. contact_id should be set to INT and Auto Increment, name should be set to VARCHAR (200) and phone_number to VARCHAR (20).

Now that your database is set up it’s time to put some info in there, insert a few rows (leave the contact_id blank – auto increment will automatically assign an ID) of data into the name and phone number, just so that we have something to display in PHP.

Next we start with the PHP file, first we need to connect to the database. Database connection through MySql uses the mysql_connect() function.

<?php

$mysql_connection = mysql_connect('localhost', 'username', 'password');

?>

This should be reasonably straightforward, replace localhost with the IP address of your MySql database (or leave it as localhost if that is what you are using, remember to keep the quotes in place) and then replace username and password with your MySql login information, remember to keep the quotes in place. You may also  be wondering why we have assigned the connection to the variable $mysql_connection, we have done this so that we can use the connection multiple times in the future in different functions like mysql_select_db() and mysql_error(), these two functions require the mysql_connect() details in order to work so we have made it easy on ourselves by storing mysql_connect() in a variable.

Now would be a good time to check have PHP check that those login details actually work, one way of doing this is by using mysql_error(). The mysql_error() function displays any MySql errors to the user.

<?php

$mysql_connection = mysql_connect('localhost', 'username', 'password');

//Check for errors
if(!$mysql_connection) {

die('Could not connect to db: ' . mysql_error());

}

?>

A lot of the above is brand new so let me introduce it. Firstly you may have seen the (!) operator on the previous tutorial, when this operator is used it is asking PHP if the function has returned false instead of true. If the database details did not work then mysql_connect() will have returned false, as we have stored mysql_connect() inside the variable $mysql_connection, $mysql_connection will currently be set to either true or false. In the case that the MySql connection has failed then the code inside the curly brackets is executed. The die() function is used to display a message and then stop the execution of the rest of the page, when you use this PHP will only display what is shown between the brackets (in this case “Could not connect to db”… ect.) and then will not show or do anything else. mysql_error() displays the MySql error and the period (.) in between mysql_error and “Could not connect to db” is called a concatenation operator and is used to join things together, more on this later though (don’t worry about understanding it right now).
So, if no MySql errors appear then the script will move on to the next part, which is to select the database. Previously we have just connected to the MySql server, now we need to tell PHP what database we want to use.

<?php

$mysql_connection = mysql_connect('localhost', 'username', 'password');

//Check for errors
if(!$mysql_connection) {

die('Could not connect to db: ' . mysql_error());

}
//Select database
mysql_select_db('contacts', $mysql_connection);

?>

Again pretty straightforward, replace ‘contacts’ with the name of your database and keep the quotes. We can also use mysql_error() here too if we want to check for errors.
Now that we have connected to the database it’s time to select some data from our ‘people’ table.

<?php

$mysql_connection = mysql_connect('localhost', 'username', 'password');

//Check for errors
if(!$mysql_connection) {

die('Could not connect to db: ' . mysql_error());

}
//Select database
mysql_select_db('contacts', $mysql_connection);

//Query database
$res = mysql_query("select `name`, `phone_number` from people");
while($row = mysql_fetch_array($res)) {

echo 'Name: ';
echo $row['name'];

echo ' Phone Number: ';
echo $row['phone_number'];
echo '<br />';

}

?>

After running that you should hopefully see your database data being displayed on the website, if so congratulations but hold on, there’s more.
Just like with mysql_connect() we have stored mysql_query() as $res and mysql_fetch_array() as $row, mysql_fetch_array() loads all the rows into $row to be displayed. While() is a loop that keeps running until everything has been displayed (this will be covered in another tutorial).
Now there’s one piece of house keeping we can do to keep everything nice and easy, and save us some time. Remember the concatenation operator? Here is the operator in use to make everything much simpler.

<?php

$mysql_connection = mysql_connect('localhost', 'username', 'password');

//Check for errors
if(!$mysql_connection) {

die('Could not connect to db: ' . mysql_error());

}
//Select database
mysql_select_db('contacts', $mysql_connection);

//Query database
$res = mysql_query("select `name`, `phone_number` from people");
while($row = mysql_fetch_array($res)) {

echo 'Name: ' . $row['name'] . ' Phone Number: ' . $row['phone_number'] . ' <br />';

}

?>

The operator allows us to join a string together with a variable (as many times as we like) inside one echo function, this can be used pretty much everywhere to join string with integers, variables and functions.

Operators are pretty key to PHP and are used pretty much everywhere in a PHP program. Operators are symbols which do things to your PHP program, in fact we covered an operator in the second tutorial “Variables” (Remember the equals sign (=)) and in the last tutorial with the ‘&&’ and ‘==’ signs. In fact operators can be used for anything from manipulating and setting variables to performing maths. Here’s a list of operators and what they do, you don’t need to know these by memory – just remember where you can go to find them.

Operator Name Example Explanation
= Equals $variable = ‘content’; Set’s a variable
+ Addition echo 1 + 1; Adds numbers
- Subtraction echo 1 – 1; Subtracts numbers
* Multiplication echo 1 * 2; Multiplies numbers
/ Division echo 4 / 2; Divides numbers
== Equals To if($number == 5) Checking if a variable equals five
!= Not Equal To if($number != 5) Checking if a variable is not equal to five
> Greater Than if($number > 5) Checking if a variable is greater than five
< Less Than if($number < 5) Checking if a variable is less than five
>= Greater Than Or Equal if($number >= 5) Checking if a variable is greater than or equal to five
<= Less Than Or Equal if($number <= 5) Checking if a variable is less than or equal to five
&& And if($number == 5 && $name == ‘Bob’) Checking if a variable (number) is equal to five and a variable (name) is equal to ‘Bob’
|| Or if($number == 5 || $number == 2) Checking if a variable is either 5 or 2
! Not (See Not Equal)
++ Increment $number ++; Adds 1 to the previous number, if $number was 5 it is now 6
Decrement $number –; Subtracts 1 from the previous number, if $number was 5 it is now 4

The whole point behind creating a site using PHP is to make it dynamic and display different content for different situations which is why PHP’s If, ElseIf and Else statements are so valuable. For a moment though we’re just going to focus on If and Else.

Simply put when you write an ‘If’ statement PHP is checking to see if something is true and ‘Else’ is looking to see if the previous ‘If’ statement was false. Still following? Let’s use a greetings example. Say we have created a site and we want it to say either “Good morning” if the time is from midnight to 11:59 AM and “Good afternoon” from 12 PM up, we would use the ‘If’ statement to check if the time was between 00:00 AM and 11:59 AM and if it was display the correct greeting, then we would use the ‘Else’ statement if the ‘If’ statement did not identify the time as being within it’s parameters.

But before we get into the ‘If’ and ‘Else’ statements there is a function which needs to be introduced. ‘date’ is a function which can determine the current date and/or time, you don’t need to know too much about this at the moment other than the code below is storing the current hour (from 00 – 23) into the variable called $hour.

<?php

//Store the current hour
$hour = date('H');

?>

So to give an example, the time here in London is currently 21:14 so the $hour variable would currently be set to ’21′.

Now that we have the current hour stored we can more onto the ‘If’ statement.

<?php

//Store the current hour
$hour = date('H');

//Check if the hour is equal or greater than 00 and equal or less than 11
if($hour >= 00 && $hour <= 11) {

//Display the morning greeting
echo 'Good morning';

}

?>

I know, I know there’s a lot to take in here so let’s tackle this from the top. Once ‘If’ is declared the parameters are then placed inside the brackets, take a look at the first part of the parameter…

if($hour >= 00

‘>=’ is an operator and it means greater than or equal, so PHP is looking for the hour (which in my case is ’21′, currently) to be greater than or equal to ’00′, which it is. Next we have (&&) this operator means ‘and’, here PHP is looking for the time to be greater than or equal to ’00′ and less than or equal to ’11′, less than or equal to is (<=) if you haven’t already worked that out.

Now using the (&&) sign isn’t mandatory, we could  have quite as easily just done

if($hour <= 11)

Which would have produced the same results, but then you wouldn’t know how valuable ‘And’ was, would you!

Next we have the curly brackets ({) and (}), whatever is placed between these brackets is what PHP will execute if the ‘If’, ‘ElseIf’ or ‘Else’ statement runs.

Finally we have the echo function which displays “Good morning”.

Now, what if the time is later than 11:59, introducing ‘Else’.

<?php

//Store the current hour
$hour = date('H');

//Check if the hour is equal or greater than 00 and equal or less than 11
if($hour >= 00 && $hour <= 11) {

//Display the morning greeting
 echo 'Good morning';

}

//Check if the hour is greater than 11
else {

//Display the afternoon greeting
echo 'Good afternoon';

}

?>

‘Else’ is pretty straight forward and doesn’t require any parameters as it’s just checking to see if the previous ‘If’ statement worked, and if not it runs ‘Else’.

Now there’s only one small problem, 9PM isn’t really the afternoon any more, so it’s time to introduce ‘ElseIf’, ‘ElseIf’ is just like ‘If’ except it runs after the ‘If’ statement (like ‘Else’ does, more on this later though).

<?php

//Store the current hour
$hour = date('H');

//Check if the hour is equal or greater than 00 and equal or less than 11
if($hour >= 00 && $hour <= 11) {

//Display the morning greeting
echo 'Good morning';

}

//Check if the hour is greater than 11 and less than 18
elseif($hour >= 12 && $hour <= 18) {

//Display the afternoon greeting
echo 'Good afternoon';

}

//Check if the hour is greater than or equal to 19
else {

//Display the evening greeting
echo 'Good evening';

}

?>

Hopefully you understand what ‘ElseIf’ is doing, if not just got back and take a look at ‘If’. If you’re going to use ‘If’ then there’s no requirement to have an ‘ElseIf’ or an ‘Else’, you can just let PHP display nothing if ‘If’ does not return true, you can also use as many ‘ElseIf’ statements as you like but you can only use a maximum of one ‘Else’ statement.

View this tutorial on YouTube @ http://www.youtube.com/watch?v=mp1-r3KEStQ

PHP Applications can get very complicated, very fast. Part of being a good developer is keeping a clean shop. So bring on comments, comments are areas of text inside a PHP file that you can use to explain what an area of the code is doing, comments are ignored by the server so PHP won’t do anything with them, they are there purely to explain to the developer what they are looking at.

There are a few type of comments you can use, the first is called the Single Line Comment.

<?php

//Set my name
$my_name = 'Joe Smith';

//Display my name
echo $my_name;

?>

Single Line Comments start with two forward slashes (//), this tells PHP to ignore what comes after it. This comment can only exist on one line, if you want to write a comment over multiple lines you need to use a multiple line comment.

<?php

/* This is a multi-line comment.
It keeps working on the next line,
And the next. */

?>

Multiple Line Comments start with a (/*) and end with a (*/), anything that is placed in between will be automatically commented out by PHP.

View this tutorial on YouTube @ http://www.youtube.com/watch?v=DOGXQUz5bEw

Variables are a common sight inside a PHP file, they are used to store pieces of information for multiple use. For example if I am writing a program that displays my house address multiple times I probably wont want to write it out, in full, over and over again. So instead I can write it out in full once and then call on it easily in the future. Welcome to variables.

<?php

$my_address = '13 Lambeth Close, Bexley, London, UK';

?>

Here is an example of a variable, a variables is made up of three parts. Firstly there is the dollar sign ($), this is used at the beginning of a variable to let PHP know what you are doing. Next is the variable name, this appears directly after the dollar sign (no spaces in between), each variable needs it’s own unique name so I’ve named mine “my_address”. Finally we need to add the contents of the variable (in other words what the variable is supposed to remember), this appears after the equals sign (=) in quotes.

Now that I have stored my variable it’s time to use it.

<?php

$my_address = '13 Lambeth Close, Bexley, London, UK';

echo $my_address;

?>

Here I’m using the ‘echo’ function that we discussed earlier (notice how I don’t put the variable in quotes, only strings need to be placed in these) to display the contents of the variable, and that’s it – now you know how to work with variables.

View this tutorial on YouTube @ http://www.youtube.com/watch?v=TLdu4Ho4NKI

Functions are what PHP is all about and so they are a great starting point for a new PHP developer. PHP has around 700 pre-made, ready-to-use functions from the simplest which output text to the browser (what we’ll be starting with) to the more complex that manage the server. All of PHP’s functions can be found at http://www.php.net/ (although personally I just Google the function to find it, even something as simple as “number of letters in a string, php” will turn up the correct function and saves a lot of time!).

The function used to output something to the browser is called “echo” (http://php.net/manual/en/function.echo.php) and is the most frequently used function by PHP developers, it’s also really easy to use. The first thing we need to do is create the PHP tags shown below.

<?php

?>

PHP tags are used to tell the server that whatever is shown in between the tags needs to be read as PHP (otherwise it will get read as HTML). Now that the tags are in place we can write the function.

<?php

echo 'Hello World!';

?>

Functions are usually split up into two parts, first we have to tell PHP which function we want to use (in this case ‘echo’) and then we have to set the function’s parameters. In this case we have set the parameters inside the quotes (‘) however you will find that most of PHP’s functions require brackets, but we’ll get to that later.

Parameters make the function do specific things and they are unique to each function, in the case of ‘echo’ the function only has one parameter, this parameter just needs to be set to whatever you want to output to the browser. In this case we want the browser to display the text “Hello World!” so we have placed that inside the quotes.

Finally at the end of the function we have a semicolon ‘;’ this let’s PHP know that the statement (in this case function) has ended, don’t forget this or you will get an error.

Once you have finished writing your first PHP application you need to save the file (I chose hello_world.php) and then upload it to your server, open the file and you should see the text “Hello World!”. If you do then congrats, you’re on your way to becoming a PHP guru! If not then take another look at everything and if you’re still having trouble put a comment here and I’ll try to help out.

View this tutorial on YouTube @ http://www.youtube.com/watch?v=m9BcPtEvuD8

Follow

Get every new post delivered to your Inbox.