PHP Tutorial for Beginner (It is very easy)

Hello, and welcome to my ultimate guide to PHP! I’m going to start from the beginning, and hopefully towards the end you’ll be able to know a lot of the basics of PHP, which will help you along the way to programming in the PHP language.

Chapters
Chapter 1 – The Basics
Chapter 2 – Variables
Chapter 3 – Operators
Chapter 4 – If, Else, Switch
Chapter 5 – Functions
Chapter 6 – Arrays
Chapter 7 – Forms & Inputs
Chapter 8 – While, For, Foreach
Chapter 9 – Advanced Operators
Chapter 10 – Files
Chapter 11 – MySQL
Chapter 12 – External Files
Chapter 13 – E-Mail
Chapter 14 – Sessions
Chapter 15 – Date
Conclusion


Chapter 1 – The Basics
The first thing to note is that all PHP code must go inside these PHP tags:

<?php
//PHP code goes here
?>

This means your code will be executed in PHP, instead of simply being displayed as HTML. You should never forget about this.

Of course these tags are useless if you don’t know any PHP to put into them. Let’s make a simple program which displays “Hello World!” on the screen.

<?php
echo “Hello World!”;
?>

Let’s introduce the echo command. Basically, it prints something onto the screen, to be shown back to the user. In this case, it is printing “Hello World!”. You can use this on various other things too, such as variables, which we will cover later.

Also to note is that the statement ends with a semi-colon. This is required at the end of every statement (Except from statements where parenthesise are used, also to be covered later). If you forget, PHP will give you errors.

Another basic piece of knowledge in PHP is how to use comments. If you make a PHP program and want to go back to it 6 months later, you might not remember what each part of your code does. Because of this, a lot of programmers use comments in their code to help remind them what each part is for. We can do this via:

<?php
//This is a one line comment.

/*This is
a multi-line
comment.*/
?>

Chapter 2 – Variables
If you already know various other programming languages, then you’ll have already heard about variables. These store different pieces of data, for you to alter later on in the programming. For example, you might save the data 82 into the variable age. You can use this later on. This is how we do it in PHP:

<?php
$variablename=”Hello”;
echo $variablename;
?>

From this code, you can see that we are saving the data “Hello” to the variable $variablename. Then, we are using the echo command to display the contents of $variablename. Therefore, this code will simply display Hello on the screen, and you can simply edit the variable to make it display something else.

Note that all variable names in PHP must begin with a $.

This only shows you examples of a string variable, though. If you want to put a number in a variable, it’s as simple as this:

<?php
$variablename=4;
echo $variablename;
?>

Now that we can display the variable, maybe we want to put the data in the middle of a sentence. For example, “Hello Jake, you have 6 watermelons”. Let’s work out how to do this:

<?php
$watermelons=6;
echo “Hello Jake, you have ” . $watermelons . ” watermelons.”;
?>

This might look slightly complex at first glance. The . in between the parts basically puts 2 strings together. In this case, we want to put the number of watermelons in the middle of the string, so have to separate it from the normal text and then join it with the . operator. Everything will become more clearer as we go along.

Chapter 3 – Operators
When you’re working with variables, you might need to use various different operators, to work with the different values.

Let’s take a look at several examples:

<?php
$watermelons=6+4;
echo $watermelons;
?>

This is a simple example of adding 2 numbers together, with the + operator. I’m sure you all know that anyway. It’s also the same with subtracting numbers:

<?php
$watermelons=6-4;
echo $watermelons;
?>

And multiplying numbers:

<?php
$watermelons=6*4;
echo $watermelons;
?>

And dividing numbers:

<?php
$watermelons=8/4;
echo $watermelons;
?>

There are some extra ones you can use in PHP, however, that you may not know about. To increment a value (+ 1), you would use:

<?php
$watermelons=6;
$watermelons++;
echo $watermelons;
?>

This would return 7. The opposite of this is decrementing a value, which you can do with the same concept:

<?php
$watermelons=6;
$watermelons–;
echo $watermelons;
?>

This would return the number 5.

These are only touching the surface of them though. We will learn about all of the rest in future chapters.

Chapter 4 – If, Else, Switch
Occassionally in our scripts, we may need to execute different pieces of code depending on the situation we’re in. For example, if a person’s age is less than 18, we may want to display the text “You are below 18 years old!”. However, if a person’s age is above 18, we may want to display “You are above 18 years old!”. The first way we will look at is the if statement.

An if statement checks if a certain variable matches a certain value. Let’s look at a basic example below:

<?php
$number=3;

if ($number==”3″) {
echo “The number is 3″;
}
?>

From this code, we set the variable $number to 3. Then, we do an if statement to check if the value is equal to 3. If it is, it displays “The number is 3″. There are a few things you should note from this example:

  • Double equals signs – When you’re checking if a condition is a certain value, you must ALWAYS use == instead of just =. When you’re setting a variable to a value, you use =. When you’re checking the value of a variable against something else, we use ==. This can be confusing at first.
  • Brackets – You should always try to put brackets around your if statement.
  • Parenthesise – The code you want to execute from this if statement must go inside of these – { }. If you forget to do this, your code will not be executed during this if statement.

So if we try to execute this code, we will see “The number is 3″ on the screen. What about if we change this code slightly, to this:

<?php
$number=4;

if ($number==”3″) {
echo “The number is 3″;
}
?>

If you test this now, you’ll probably find that nothing is displayed on the screen. This can be quite a problem, because sometimes we want to use more than one value. If we wanted to check whether $number was equal to 3 or not, we could use an else statement. You can see an example below:

<?php
$number=4;

if ($number==”3″) {
echo “The number is 3″;
} else {
echo “The number isn’t 3″;
}
?>

This code now checks if the value is equal to 3. If it is, it displays “The number is 3″. Else, if the number equal to 3, it displays “The number isn’t 3″. Once again, the contents of the code to be executed from the else statement must go inside parenthesise.

Another thing, to add to it, is using an else if statement. This way we can use several if statements together:

<?php
$number=4;

if ($number==”3″) {
echo “The number is 3″;
} else if ($number==”4″) {
echo “The number is 4″;
} else {
echo “The number isn’t 3 or 4″;
}
?>

So this code will check if it’s equal to 3, and if it isn’t, it will check if it’s 4, and if it’s neither, it will execute the code in the else loop. I hope this doesn’t sound completely confusing yet.

Sometimes, however, you may need to check from a long list of values. This would mean that using loads of if statements wouldn’t really be practical in this situation. Luckily, we have another alternative for this – We call this a switch statement. Let’s look at an example to start:

<?php
$number=4;

switch ($number) {
case 1:
echo “The number is 1″;
break;
case 2:
echo “The number is 2″;
break;
case 3:
echo “The number is 3″;
break;
default:
echo “The number isn’t 1, 2 or 3″;
}
?>

Let’s start to break this code down. The variable inside the switch statement is the variable you will be checking against in this statement. I’ve used the variable $number used previously. Parenthesise are used again. Then, we begin to check the values. Case is used to check the values, so for example, case 3: means that if the variable is equal to 3 and case 4: means that if the variable is equal to 4. Then, the code that will be executed if that value is correct, is written. I’ve just used simple echo commands. You’ll find a break; is then used. Never forget these when using switch statements, they’re important to end the case. Finally, towards the end, default: is used. This is the default code executed when none of the values are correct. No break; tag is required during this default section.

This is the end of the chapter. We will be going back to more advanced alternatives very shortly, but firstly, we’re going to learn some other PHP.

Chapter 5 – Functions
Sometimes when we’re coding in PHP, we might need to execute certain pieces of code quite a lot of times, and if it’s a big amount of code, it can make the file much bigger than it needs to be. This is why we can create our own functions to execute the code multiple times.

<?php
function myname() {
echo “Jake Ruston”;
}

echo “My name is “;
myname();
?>

This simple code creates a function called myname. It echo’s my name. Whenever we want to echo my name from now on, we can simply use the function myname(). Let’s look at a slightly more complicated one.

<?php
function myname($name) {
echo $name;
}

echo “My name is “;
myname(“Jake Ruston”);
?>

In this example, the function requires a parameter – An input. Whenever we use the myname() function, we need to include the name between the brackets. The function will then retrieve the value, store it in the variable $name, and then it will echo it. Let’s take a look at another example.

<?php
function addnum($num1, $num2) {
$num3=$num1+$num2;
echo $num3;
}

echo “1 + 5 = “;
addnum(1,5);
?>

This code uses two parameters – The first number and the second number. The function stores both values in $num1 and $num2, and then it adds the numbers together, stores the result in $num3 and then echo’s it. Very simple. Let’s look at one final example of PHP functions.

<?php
function addnum($num1, $num2) {
$num3=$num1+$num2;
return $num3;
}

echo “1 + 5 = ” . addnum(1,5);
?>

This example is very similar to the previous example, but instead of echo’ing the value, it returns it. There is a difference. When you echo a value, it cannot be used in PHP directly – It is simple printed on the screen. When you return a value, we can use it as part of returning a string, as shown in the example, as well as other ways. We may learn about this later, in more detail.

Chapter 6 – Arrays
Let’s get started on Chapter 6. The problem with variables is that it can only store one value. Sometimes, you need to use multiple values for the same purpose, such as below:

<?php
$name1=”Jake Ruston”;
$name2=”Hello Hello”;
$name3=”Steve Beep”;
$name4=Dave Bap”;
?>

I’m sure you can see the problem here. There are way too many variables being used. To solve this, we have arrays. This is a special type of variable that can store multiple pieces of data. We can use one like this:

<?php
$name[0]=”Jake Ruston”;
$name[1]=”Hello Hello”;
$name[2]=”Steve Beep”;
$name[3]=”Dave Bap”;

echo “The first name is ” . $name[0] . ” and the second name is ” . $name[1];
?>

They can be very useful for lists of items or values. You can see that the array always starts at 0.

To use the value in PHP, you can simply refer to it using the number in the array – Such as $name[3].

There isn’t really much to say about arrays, they are pretty simple. What we haven’t talked about though is multi-dimensional arrays. These are useful occassionally. You can see an example below:

<?php
$family[0][0]=”Jake Ruston”;
$family[0][1]=”Hello Hello”;
$family[0][2]=”Steve Beep”;
$family[0][3]=”Dave Bap”;

echo “In Family 0, there is ” . $family[0][0] . “, ” . $family[0][1] . “, ” . $family[0][2] . ” and ” . $family[0][3] . “.”;
?>

As you can see, you can have multiple sections to the array. $family[0][0] could refer to the 1st family and the 1st person in that family. $family[2][1] could refer to the 3rd family and the 2nd person in that family. It reduces the amount of variables when using a list, too.

Chapter 7 – Forms & Inputs
One thing we haven’t covered yet is inputting data in PHP. This can be a problem – The same code is executed for each person. What we need to work out how to do is to allow users to input data into the PHP script – So they can get the desired output. We normally do this through a normal HTML form. I’m showing this on the basis that you have basic HTML knowledge and know how to create a form in HTML.

<html>
<body>

<form action=”testing.php” method=”post”>
Name: <input type=”text” name=”my_name” />
Age: <input type=”text” name=”my_age” />
<input type=”submit” />
</form>

</body>
</html>

From this code, we can see that the my_name field is a text field, for users to enter their name. The my_age field is also a text field, for users to enter their name. The action in the form tag is the URL to which the data is being sent to. If you’re having a separate file to process the PHP, you would use this. If you’re putting the HTML form and the PHP code in the same file, just insert the file name. What we need to look at most importantly in this form is the name parameters in the tags and the method parameter in the form tag.

When we’re creating a HTML form, we can either have a method of post or a method of get. Both have their uses. When using the get method, the variables and the data are included in the URL. For example, if you have a form which uses my_age and my_name as text inputs and you use the get method, the URL would look like webpage.php?my_age=31&my_name=Jake_Ruston. The problem with this is that if you’re dealing with sensitive informaton such as credit card details and passwords, you really don’t want to display this in the URL. This is why we use post variables.

Let’s work on processing PHP from the form example we already used. In that form, we used the post method with text field names of my_age and my_name. This is how we could process it:

<?php
$my_name=$_POST[‘my_name’];
$my_age=$_POST[‘my_age’];

echo “The age entered was ” . $my_age . ” and the name entered was ” . $my_name;
?>

The main thing to look at is the way we retrieve the data. When we’re using the post method in our form, we use $_POST[‘TEXT_FIELD_NAME’], or for the get method, we use $_GET[‘TEXT_FIELD_NAME’], where TEXT_FIELD_NAME is the name parameter of the text field in the form.

This is all you need to know about forms.

Chapter 8 – While, For, Foreach
This is going back to the if, else and switch statements we were doing earlier. This time, we’re learning about 3 other more advanced ones – While loops, for loops and foreach loops. Let’s start with the most popular one, while loops.

A while loop executes a block of code when a specific condition is true – And then continues to execute it while the condition is still true. A simple example should help to explain this a bit better:

<?php
while ($i<5) {
echo “Code executed!
“;
$i++;
}
?>

Can you work out what this code does? While the variable $i is less than 5, it displays “Code executed!” and then a line break. It then increments $i, so that the loop ends after 4 attempts. If we didn’t increment it, then $i would always be less than 5 and it would never end.

Let’s move onto the for loop.

This can be a little more complex to remember, but still fairly easy. Let’s take a look at an example before we discuss it:

<?php
for ($i=0; $i<5; $i++)
echo “Code executed!
“;
$i++;
}
?>

As you can see, this for loop does exactly the same as the while loop above. There are 3 different parts to the for loop – Initialising the variable, the condition and the incrementation. As you can see from my example, I’ve set the variable $i to 0 (Initialising), and the condition is to check if $i<5. I then increment $i.

Now let’s move onto the final one – The foreach loop. This is only used for arrays, which is why we had to learn about arrays first. Example:

<?php
$name[0]=”Jake”;
$name[1]=”Jake2″;
$name[2]=”Jake3″;

foreach ($name as $value) {
echo “Name: ” . $value . ”
“;
}
?>

From this PHP code, we have set 3 different values inside the $name array. Then, we use a foreach loop. The first variable is the name of the array, and then the second variable used ($value) stores the current value in the array. The value in this variable changes each time when the loop runs, which is how we can use the variable $value inside the actual loop.

Chapter 9 – Advanced Operators
So far we’ve only used some basic operators in our PHP code – Such as =, +, -, *, /, ==, <, >, ++, –. You should know what all of these mean by now. We have missed out quite a few though. There are some more that you may need to know, such as:

  • != – This means not equal to. This is only used during a condition check, never to set the value of something. Note how we don’t need the double equals sign in this, just the != is fine.
  • += – This is a quick way of adding a variable to a number/another variable. If you write $number += 4, then you are adding 4 to the number stored in $number. It can come in handy at some points.
  • && – This means and. It is usually used in an if statement, where 2 variables need to be checked. For example:if ($name==”Jake” && $age==”408″) {
    echo “Your name is Jake AND your age is 408!”;
    }
  • || – This means or. It is also usually used in an if statement, where 2 or more variables need to be checked. For example:if ($name==”Jake” || $age==”408″) {
    echo “Your are either 408 years old or your name is Jake!”;
    }

These are basically all the operators that you will come across in ordinary PHP coding

Chapter 10 – Files
In PHP, it is not uncommon to have to read/write to files. If you’re keeping track of data, or need to look inside a settings file, then this is probably the best way. Don’t worry though, it’s pretty simple.

When you want to open a file in PHP, you must ALWAYS begin with the fopen function. This opens the file – If it exists, it is opened. If it doesn’t exist, then it is created. There are a few different modes that you can open the file in, however, so let’s take a quick look.

  • r – This opens the file JUST for reading – Nothing else can be done. You cannot write to the file.
  • r+ – This opens the file for reading and for writing – And it starts at the beginning on the file.
  • w – This opens the file JUST for writing – And it clears the contents of the file too to begin fresh.
  • w+ – This opens the file for writing and for reading – It also clears the contents of the file.

Now that we know about the different modes, let’s get learning the PHP behind opening it!

<?php
$file=fopen(“textfilename.txt”, “w”);
?>

The first parameter of the fopen function is the name of the file to open. The second parameter is the mode to write in. As you can see, this command will open the file textfilename.txt and clear the contents of the file, ready to write to. Make sure you always use a variable to store the result of the fopen function, because this is the file identifier which will be used later.

If you’re reading through a text file, one of the most important commands you’ll come across is the feof command. This is a loop which will read every line until the end of a file – Meaning you can process whatever you want with the file. You can see an example of this below:

<?php
$file=fopen(“text.txt”, “r”);
while(!feof($file))
{
echo fgets($file). ”
“;
}
fclose($file);
?>

Let’s break down the code. What it does is open the text file text.txt in the read mode. Then, with the help of a while loop, it reads every line of the text file with the feof command. Notice how it says (!feof($file)), because this means that if it’s not the end of the file. During this loop, it get’s the contents of the current line with the fgets command and then a line break. The file is then closed through the fclose function. Very important.

So what this code basically does is reading the contents of the whole file and displaying it on the screen.

This is about it for reading the file for now, let’s get onto learning how to write to a file.

This is really quite simple too. Look at the example below:

<?php
$file=fopen(“text.txt”, “w”);
$string=”Write me!”;
fwrite($file, $string);
fclose($file);
?>

The only new function introduced here is fwrite, which does exactly as it says. The first parameter is the file identifier which we stored earlier when opening the file, and then the second parameter is what we want to write. I made a variable with the string “Write me!” and then chose to write that to the file

Chapter 11 – MySQL
When we need to store certain data, often we can use files to write to. However, in some cases, this is just not possible. If you need to store data such as user accounts, then we can use an alternative – MySQL. This is very popular, but can be quite difficult to remember.

In a MySQL Database, we normally have fields (or columns) which give a name to each part of data, and then records (or rows) which contain the actual data, in the format below:

USERNAME           PASSWORD                EMAIL                                    ADDRESS

shamim                 something           shamim.link@yahoo.com              RUET            sadamoon            rajshahi                Rajbd@yahoo.com                           Rajshahi

As you can see, the fields in this database structure are Username, Password, E-Mail and Address. The records are the rows of data.

When we want to send data to or from MySQL, we use what is called a query to do so. This is just some of the basic terminology. Let’s get started with the PHP aspects of it.

When we start using MySQL, we first need to connect to MySQL through the mysql_connect command, which has several parameters as seen below:

<?php
$connection=mysql_connect(“localhost”, “mysqlusername”, “mysqlpassword”);
?>

The three parameters to this statement are the host, the MySQL username and the MySQL password. There are no specific databases involved yet. The host is almost always localhost, so if you aren’t sure, it’s probably localhost.

If MySQL fails to connect for some reason, then we need the script and let the user know, so they don’t get loads of MySQL errors. Let’s develop the code slightly:

<?php
$connection=mysql_connect(“localhost”, “mysqlusername”, “mysqlpassword”);

if (!$connection) {
die(“MySQL Database Error!”);
}
?>

The (!$connection) checks if the connection has had a problem, to put it simply. The die command displays the parameter onto the screen and then stops the script. A nice simple way of getting around it. Another thing to remember is that you must ALWAYS close your MySQL connection when it’s finished. You can do that easily by:

<?php
$connection=mysql_connect(“localhost”, “mysqlusername”, “mysqlpassword”);

if (!$connection) {
die(“MySQL Database Error!”);
}

mysql_close($connection);
?>

Nice and simple, huh? You just use the mysql_close function, and the only parameter is the variable we used to open the connection. If you’ve got to this stage in the tutorial, I don’t think you’ll have any problems with this so far. Of course, our code so far is very pointless because it simply opens up a connection and then closes it. Let’s take a look at some things we can do now that we have a MySQL connection.

One thing that might come in handy is creating a database. Personally, I’ve never actually used this because I always create the database and all of the tables in the database first, because it’s much easier to work with through PHPMyAdmin, but this is for those who want to create a database in PHP:

<?php
$connection=mysql_connect(“localhost”, “mysqlusername”, “mysqlpassword”);

if (!$connection) {
die(“MySQL Database Error!”);
}

mysql_query(“CREATE DATABASE my_database_name”,$connection);

mysql_close($connection);
?>

This code will now create a database using the mysql_query function – We will be using this a lot. First we type the SQL query, create database, and then we write the name of the database we want to create. The second parameter is the variable of the connection we opened. It still is a bit pointless to have a database with no tables, so let’s learn how we can create some tables in PHP and add it to our code.

<?php
$connection=mysql_connect(“localhost”, “mysqlusername”, “mysqlpassword”);

if (!$connection) {
die(“MySQL Database Error!”);
}

mysql_query(“CREATE DATABASE my_database_name”,$connection);
mysql_select_db(“my_database_name”, $connection);
mysql_query(“CREATE TABLE People
(
personID int NOT NULL AUTO_INCREMENT,
PRIMARY KEY(personID),
FirstName varchar(15),
LastName varchar(15),
Age int
)”,$connection);

mysql_close($connection);
?>

To start with, if you’re unsure of what this means, then you need to find a good SQL tutorial. This guide is simply for using MySQL in PHP, and isn’t an SQL tutorial.

After we’ve created a database, we need to select the database – To tell the script that we want to execute all other MySQL commands on this specific database. We can do this via mysql_select_db(“my_database_name”, $connection), where the first parameter is the database name and the second is the variable of the connection we opened. The code afterwards simply creates a new table. The table we created was called People with 4 fields – personID, FirstName, LastName and Age. It also has another parameter – Once again, the variable of the connection we opened.

Now we have created a database as well as a table. Shall we move onto inserting rows into our table?

<?php
$connection=mysql_connect(“localhost”, “mysqlusername”, “mysqlpassword”);

if (!$connection) {
die(“MySQL Database Error!”);
}

mysql_query(“CREATE DATABASE my_database_name”,$connection);
mysql_select_db(“my_database_name”, $connection);
mysql_query(“CREATE TABLE People
(
personID int NOT NULL AUTO_INCREMENT,
PRIMARY KEY(personID),
FirstName varchar(15),
LastName varchar(15),
Age int
)”,$connection);

mysql_query(“INSERT INTO People (FirstName, LastName, Age) VALUES (‘Jake’, ‘Ruston’, ‘16′)”, $connection);
mysql_query(“INSERT INTO People (FirstName, LastName, Age) VALUES (‘Bob’, ‘Bob’, ‘72′)”, $connection);
mysql_query(“INSERT INTO People (FirstName, LastName, Age) VALUES (‘Fred’, ‘Fred’, ‘38′)”, $connection);

mysql_close($connection);
?>

Let’s look at the extra line we’ve now used. We’ve used the mysql_query function once again, and we’ve used the SQL INSERT INTO, which does exactly what it says. We’ve then specified the table name. Afterwards, in brackets, we’ve specified 3 field names which we want to insert data into. We want to leave personID since it auto increments anyway, so we’re just inserting values into FirstName, LastName and Age. We then specify the values we want to insert, and then finally with the last parameter, the variable of the connection. I hope I’m not losing you so far.

Okay, so now we’ve developed our own small little script which creates a database, and then creates a table, and then inserts 3 records into it. What about if we want to retrieve data back into the PHP script?

<?php
$connection=mysql_connect(“localhost”, “mysqlusername”, “mysqlpassword”);

if (!$connection) {
die(“MySQL Database Error!”);
}

mysql_query(“CREATE DATABASE my_database_name”,$connection);
mysql_select_db(“my_database_name”, $connection);
mysql_query(“CREATE TABLE People
(
personID int NOT NULL AUTO_INCREMENT,
PRIMARY KEY(personID),
FirstName varchar(15),
LastName varchar(15),
Age int
)”,$connection);

mysql_query(“INSERT INTO People (FirstName, LastName, Age) VALUES (‘Jake’, ‘Ruston’, ‘16′)”, $connection);
mysql_query(“INSERT INTO People (FirstName, LastName, Age) VALUES (‘Bob’, ‘Bob’, ‘72′)”, $connection);
mysql_query(“INSERT INTO People (FirstName, LastName, Age) VALUES (‘Fred’, ‘Fred’, ‘38′)”, $connection);

$current_query=mysql_query(“SELECT * FROM People”, $connection);

while($row = mysql_fetch_array($current_query))
{
echo $row[‘FirstName’] . ” ” . $row[‘LastName’];
echo ”
“;
}

mysql_close($connection);
?>

We’ve had to add a few extra lines of PHP to achieve this. First of all, we’ve used the mysql_query function to SELECT data. The * means we want to retrieve all data from the records (It’s good practice to do this, incase you need other data later on in the script), and then we specify the table name. We need to store this into a variable.

We then have to use a while loop, and a function called mysql_fetch_array. The value stored in $current_query is NOT what we want, so we have to use the mysql_fetch_array function which then retrieves it row by row. The while loop is used so we can execute code everytime it retrieves another row – So for example, in our code, we’re displaying the FirstName and the LastName values of every row.

Sometimes though, we may not want to retrieve ALL rows of data. This is why we can add WHERE to our select statement. Let’s look at our select statement so far:

$current_query=mysql_query(“SELECT * FROM People”, $connection);

And then let’s add the WHERE clause:

$current_query=mysql_query(“SELECT * FROM People WHERE FirstName=’Jake’”, $connection);

This will now only return rows where the FirstName is Jake. In the case of our example, this will only return one row.

There are still two different MySQL examples we need to look at – Updating values and deleting them. Let’s start with updating values.

mysql_query(“UPDATE People SET Age = ‘363′ WHERE FirstName = ‘Jake’ AND LastName = ‘Ruston’”);

Can you work out what this does? We use UPDATE and then the table name to let the script know what table we want to update. Then, we set the new field name to the new value, and use a where clause to make sure we only update one row – And not all rows. It could be a problem if we set all age values to 363.

And then we can finish off this MySQL chapter by learning about how to delete rows. This is also very simple:

mysql_query(“DELETE FROM People WHERE LastName=’Ruston’”);

This statement shows the table name we want to delete from, and then we use a where clause to make sure we only delete specific rows – If we didn’t use a where clause, then this one statement could potentially delete all rows from the database!

Chapter 12 – External Files
When you’re programming in PHP, you might want to use other files – And not store all of the code in one file. If you’re making a full website in PHP, then you may find that you have to use the MySQL connection information multiple times. We can get around this by making separate files for individual PHP codes, to make it more organised.

There are two different ways we can do this – With the include() function and the require() function.

Let’s say that we have two different PHP files – One called included.php and one called main.php.

The contents of included.php is:

<?php
function hellotest() {
echo “Hello – Testing”;
}
?>

The contents of main.php is:

<?php
include(‘included.php’);

hellotest();
?>

included.php holds a function we’ve created – We learnt how to do these previously. main.php uses the include() function to get the contents of the included.php function – The only parameter is the file name. Now that we’ve included the file, we can use a function we created in the included.php file. Very simple and easy.

Now there’s another alternative:

<?php
require(‘included.php’);

hellotest();
?>

This is the same sort of thing – But the file is required. This means that if the file cannot be retrieved for whatever reason, a PHP error will occur and the script will stop.

Chapter 13 – E-Mail
If you’re creating a PHP script that requires some sort of user notification, then learning how to send E-Mails through PHP can be very helpful.

Sending E-Mail is done through one simple function – mail(). There are quite a few parameters to this function, as you can see below:

  • to – This is the E-Mail Address that you wish to send an e-mail to.
  • subject – This is the Subject of the E-Mail you’re going to send.
  • message – This is the Message of the E-Mail you’re going to send.
  • headers – This is extra headers sent from the e-mail, eg. From, Cc, Bcc.

Using this function is very simple. Look at an example below:

<?php
$to = “someone@example.com”;
$subject = “Test mail”;
$message = “Hello! This is a simple email message.”;
$from = “someonelse@example.com”;
$headers = “From: $from”;
mail($to,$subject,$message,$headers);
echo “Mail Sent.”;
?>

All you have to do in this example is modify the variables $to, $subject, $message and $from. Then you can send your desired e-mail. This is the end of this small chapter.

Chapter 14 – Sessions
Sessions are normally used when you want to store temporary information about your visited – For example, for a shopping cart, the items in the cart would be stored as a session, in a cookie. Once the visitor leaves the website, the session will most likely be deleted. Sessions can also be used for membership scripts – Where users have to login, and they stay logged in for as long as the session lasts.

To start a session, you need to include the following line AT THE TOP OF THE FILE:

<?php session_start(); ?>

This has to go at the top of the file, else several PHP errors will be returned. This code creates a session, so you can easily get started. Now let’s learn how to store some data into a session:

<?php
session_start();

$_SESSION[‘testing’]=”3″;

echo “Session variable is ” . $_SESSION[‘testing’];
?>

The first line creates the session. Then, we save the value 3 into the session, with the name testing. This is in the same sort of format as GET and POST variables. Once you’ve set this, it can easily be used in the PHP code, as seen by echo’ing the contents of this session variable. Don’t forget that when you’ve set the session variable, users can still go to other pages on the website and the variable still remains, so you can still use $_SESSION[‘testing’] on other pages.

If you want to destroy a session (For example, a user logging out), then you can use the quick function, as below:

<?php
session_destroy();
?>

This destroys the session. There is one last thing you might need to know about session variables – How to check if one is set.

<?php
if(isset($_SESSION[‘testing’])) {
$_SESSION[‘testing’]=$_SESSION[‘testing’]+1;
} else {
$_SESSION[‘testing’]=1;
}

echo “Value=”. $_SESSION[‘testing’];
?>

We use an if statement in conjunction with an isset function to check if a value is stored inside the session variable. If the session variable is set (Has a value inside of it) then it adds one to the total. If it isn’t set (No value), then it sets the session variable to 1. It then echo’s the contents of the session variable.

Chapter 15 – Date
Some scripts may require the use of the date – Using the current date as well as dates in the future – Maybe a week in the future. This probably won’t be used as much as some other functions we’ve learnt about, but it may be helpful to learn anyway.

First of all, let’s learn about the date() function. This allows us to find the current date, and display it in the way we want to.

<?php
echo date(“Y/m/d”);
?>

This function will return the current date, in the format like so – 2009/11/13. Want to organise it into your own pattern? Still very easy.

<?php
echo date(“d.m.Y”);
?>

This displays the date like 13.11.2009. All you have to do is re-arrange d (For day), m (For month) and Y (For year) in the way you want.

Maybe you want to find dates in the future too. For this, use the mktime() function. It goes in the format:

mktime(hour,minute,second,month,day,year);

We add this function to the date() function too. If we want to find the date tomorrow, we can use this:

<?php
$tomorrow = mktime(0,0,0,date(“m”),date(“d”)+1,date(“Y”));
echo “Tomorrow is ” . date(“d/m/Y”, $tomorrow);
?>

Let’s look into the mktime function. We’ve set the hour to 0, minute to 0, second to 0, the month is the current month, the day is the current day+1 and the year is the current year. This sets it forward 1 day. Then, we echo the date in the usual format, but we add an extra parameter to the date() function – The variable of the mktime we made. This is all we need to do.

Conclusion
This is the end of my long tutorial. I hope you’ve all learnt quite a lot of PHP, which will help you when you’re developing your PHP scripts. I might update it several times in future, let’s just see how it goes.

Advertisements
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: