+ All Categories
Home > Documents > PHP Tutorial

PHP Tutorial

Date post: 28-Oct-2014
Category:
Upload: ebooktutorials
View: 621 times
Download: 0 times
Share this document with a friend
Description:
For more eBooks please visit www.ebooktutorials.blogspot.in
Popular Tags:
77
PHP Tutorial
Transcript
Page 1: PHP Tutorial

PHP Tutorial

Page 2: PHP Tutorial

PHP Tutorial - Table of contentsIntroductionA brief introduction to the tutorial and what you can expect to learn.Lesson 1: What is PHPA little on how PHP works, what it means that PHP is a server-side technology, andwhat you will learn in the next lessons.Lesson 2: ServersWe look at different options to run PHP on your own computer or on a web host.Lesson 3: Your first PHP pageIn this lesson, you create your first very simple PHP page. Here, you can also testwhether your server is set up properly to run PHP.Lesson 4: Working with time and datesIntroduction to functions that can be used in work with time and dates.Lesson 5: LoopsLoops can repeat parts of a script. In this lesson, we look at loops such as whileand for.Lesson 6: ConditionsConditions can be used to control the execution of a PHP script. We look at if ...elseif ... else... and switch ... case.Lesson 7: Comment your scriptsComments make your PHP scripts more clear and easier to understand. Commentscan be a great help if you or someone else needs to make changes in your codesat later stage.Lesson 8: ArraysIn this lesson, you will learn what an array is, how it is used, and what it can do.Lesson 9: FunctionsIn previous lessons, you have learned to use different, built-in functions. Now youwill learn how to create your own functions.Lesson 10: Passing variables in a URLLearn how to pass variables and values from one page to another using the HTTPquery string.Lesson 11: Passing form variablesInteractive websites require input from users. One of the most common ways toget input is using forms.Lesson 12: SessionsSessions can be used to store and retrieve information during a user's visit on yoursite.Lesson 13: CookiesCookies can be used to store and retrieve information about a user from visit tovisit.Lesson 14: FilesystemWith the filesystem, you can access the server's filesystem. This allows you tomanipulate files, folders and drives with PHP scripts.

Created By www.ebooktutorials.blogspot.in

Content Downloaded from www.html.net 1

Page 3: PHP Tutorial

Lesson 15: Reading from a text fileIn this lesson, we will use the filesystem to read from a text file. Text files can bevery useful to store data of various kinds.Lesson 16: Writing to a text fileThis lesson is about how to write to a text file using the filesystem. Text files canbe very useful to store various kinds of data.Lesson 17: DatabasesIn this tutorial, we use the MySQL database. MySQL is the natural place to startwhen you want to use databases in PHP.Lesson 18: Create databases and tablesIn this lesson, we look at two ways to create databases and tables. First, how it isdone in PHP, and then how it's made with the more user-friendly tool:PhpMyAdmin.Lesson 19: Insert data into a databaseLearn how to use SQL statements to insert data into a database. We also look atdata types and the most common beginner mistakes.Lesson 20: Retrieve data from a databaseLearn how to use an SQL query to retrieve data from a database.Lesson 21: Delete data from a databaseLearn how to delete records from a database using SQL.Lesson 22: Update data in a databaseIn this last lesson, you will learn how to update data using an SQL statement

Created By www.ebooktutorials.blogspot.in

Content Downloaded from www.html.net 2

Page 4: PHP Tutorial

IntroductionPHP gives you the freedom to add advanced features to your website.

The aim of this tutorial is to give you an easy, yet thorough and accurate introductionto PHP. It starts from scratch but requires that you already have a good knowledge ofHTML. If you are new to HTML, you should start with our HTML tutorial.

PHP can be used in many contexts - discussion forums, polls, shops, SMS gateways,mailing lists, etc. The only limitation with what you choose to do with PHP is yourimagination. PHP is not hard to learn, but be aware that PHP is more sophisticated anddemanding to learn than HTML. Therefore, patience in the process is a virtue.

This tutorial cannot show you everything. Therefore, some engagement and a will toexperiment are required. If you need help along the way, we recommend that you usethe forums for such support. This is where you meet the real experts who are willingand ready to offer tips, suggestions and advice.

What is needed?

It is assumed that you already have a text editor and know how it is used.

Next, you need access to a computer or a server that can run PHP. In contrast to HTMLand CSS, PHP is not affected by which browser your visitors use, but by the type ofserver that's hosting your pages. This is because PHP is a server-side technology.

In the next few lessons, you will learn all about how PHP works, and how to set upyour computer to run PHP. After that, you'll learn about specific functions and methods.

When you finish this tutorial, you will be able to code PHP and thus have access tounlimited possibilities for adding interactivity to your webpages.

Created By www.ebooktutorials.blogspot.in

Content Downloaded from www.html.net 3

Page 5: PHP Tutorial

Lesson 1: What is PHPWhenever anyone is learning PHP, the most common questions that first come up are:What is PHP? And how does it work?

It is precisely these questions we will look at in this lesson. It's a big help to understandsuch basics related to PHP before you start developing you own PHP pages. Such basicunderstanding will increase the speed of learning significantly.

So, let's get started!

What is PHP?

PHP was originally an acronym for Personal Home Pages, but is now a recursiveacronym for PHP: Hypertext Preprocessor.

PHP was originally developed by the Danish Greenlander Rasmus Lerdorf, and wassubsequently developed as open source. PHP is not a proper web standard - but anopen-source technology. PHP is neither real programming language - but PHP lets youuse so-called scripting in your documents.

To describe what a PHP page is, you could say that it is a file with the extension .phpthat contains a combination of HTML tags and scripts that run on a web server.

How does PHP work?

The best way to explain how PHP works is by comparing it with standard HTML.Imagine you type the address of an HTML document (e.g.http://www.mysite.com/page.htm) in the address line of the browser. This wayyou request an HTML page. It could be illustrated like this:

Created By www.ebooktutorials.blogspot.in

Content Downloaded from www.html.net 4

Page 6: PHP Tutorial

As you can see, the server simply sends an HTML file to the client. But if you insteadtype http://www.mysite.com/page.php - and thus request an PHP page - theserver is put to work:

The server first reads the PHP file carefully to see if there are any tasks that need to beexecuted. Only when the server has done what it is supposed to do, the result is thensent to the client. It is important to understand that the client only sees the result ofthe server's work, not the actual instructions.

This means that if you click "view source" on a PHP page, you do not see the PHPcodes - only basic HTML tags. Therefore, you cannot see how a PHP page is made byusing "view source". You have to learn PHP in other ways, for example, by reading this

Created By www.ebooktutorials.blogspot.in

Content Downloaded from www.html.net 5

Page 7: PHP Tutorial

tutorial.

What you learn in this tutorial is to write commands to a server!

So, the first thing you need to get ahold of is... a server! But don't worry - you don'tneed to buy a new computer. You just need to install some software on your computerthat makes it function as a server. Another option is to have a website on a hostedserver that supports PHP. Then you just need to be online while coding.

The next lesson is about how to get your computer to act as a server.

Created By www.ebooktutorials.blogspot.in

Content Downloaded from www.html.net 6

Page 8: PHP Tutorial

Lesson 2: ServersPHP is a server-side technology. Therefore, you need to have a server to run PHP. Butit doesn't need to cost you anything to make this upgrade and there are several optionsfor doing so.

Since you ultimately only need to choose one option, this lesson is divided into threeparts. First comes a little introduction on the different options (just choose the one thatsuits you best). When your server is up and running, we'll pick up with Lesson 3 tomake your first PHP page.

Option 1: Website on a hosted server

You can choose to have a website on a host that supports PHP.

Test whether your host supports PHPIf you don't already have a website on hosted server you can create a free accounton 000webhost.com which supports PHP.

Option 2: Install PHP on your computer

It's no walk in the park to install PHP on your computer. This option is only recommendfor experienced computer users, but it can obviously be done. Here are links todownloads and installtion guides:

Windows Installation GuideMac Installation GuideLinux Installation Guide

Option 3: XAMPP

XAMPP is a program that makes it easy and possible for us ordinary folks to run the PHPdirectly on our computer without having to install PHP on our own.

Learn how to install XAMPP

Created By www.ebooktutorials.blogspot.in

Content Downloaded from www.html.net 7

Page 9: PHP Tutorial

Lesson 3: Your first PHP pageFrom lesson 1 and 2, you now know a little about what PHP is, and you've installed (orhave access to) a server. Now we are ready to begin making our first PHP page. Wekeep it simple and easy, but after you have gone through this lesson, you willunderstand much more about what PHP is and what you can do with it.

Basically, a PHP file is a text file with the extension .php which consists of:

TextHTML tagsPHP Scripts

You already know what text and HTML tags are. So let's look a little more at PHPscripts.

PHP Scripts

PHP Documentation Group has issued detailed documentation for PHP. Throughoutthe tutorial, there will be many links to the documentation. The goal is that you becomeaccustomed to looking up and finding answers to your questions. PHP is so extensivethat you can't to learn all facets in this tutorial. But PHP is not difficult! On the contrary,PHP is often very similar to plain English.

Let's get started with your first PHP page.

Example: Hello World!

Start by making an ordinary HTML document, but name the file page.php and save it inthe root of the site:

If you use XAMPP (see lesson 2), the path for the root is"c:\xampp\htdocs\page.php" on your computer (which is now a server). Read moreabot saving PHP files in XAMPP.If you have a website on a host that supports PHP, you simply upload/ftp the fileto your web host.

The HTML code should look like this:

<html> <head> <title>My first PHP page</title>

</head> <body>

</body> </html>

Created By www.ebooktutorials.blogspot.in

Content Downloaded from www.html.net 8

Page 10: PHP Tutorial

As you probably remember from lesson 1, PHP is all about writing commands to aserver. So let's write a command to the server.

First, we need to tell the server when the PHP will start and end. In PHP you use thetags <?php and ?> to mark the start and end for the PHP codes that the server mustexecute (on most servers it will be suficient to use just <? as start tag, but <?php isthe most correct to use the first time PHP is used.)

Now try to add the following simple code snippet to your HTML code:

<html> <head> <title>My first PHP page</title> </head> <body>

<?php

echo "<h1>Hello World!</h1>";

?>

</body> </html>

When we look at the PHP document in a browser, it should look like this:

But it gets interesting when you look at the HTML code in the browser (by selecting"view source"):

Created By www.ebooktutorials.blogspot.in

Content Downloaded from www.html.net 9

Page 11: PHP Tutorial

The PHP codes are gone! As you may remember from lesson 1, it is only the server thatcan see the PHP codes - the client (the browser) only sees the result!

Let's look at what happened. We asked the server to write <h1> Hello World!</h1>. Ina more technical language, one would say that we used the string function echo towrite a specified string to the client where the semicolon ends the command. But do notworry! In this tutorial, we try to keep the technical language at a minimum.

Our first example is obviously not particularly exciting. But just wait! From now on, it'sonly going to be more and more interesting. Let's look at another example.

Example: Now!

Let's make the server write something else. We could, for example, ask it to write thecurrent date and time:

<html> <head> <title>My first PHP page</title>

</head> <body>

<?php

echo date("r");

?>

</body> </html>

That will look like this in the browser:

Created By www.ebooktutorials.blogspot.in

Content Downloaded from www.html.net 10

Page 12: PHP Tutorial

And the corresponding HTML code:

Now things are getting interesting, right?

We make the server write the date and time when the PHP page is displayed. Note thatif you refresh the page in the browser, a new time is written. The server writes thecurrent date and time each time the page is sent to a client.

It is also important to note that the HTML code contains only the date - not the PHPcodes. Therefore, the example is not affected by which browser is used. Actually, allfunctionalities that are made with server-side technologies always work in allbrowsers!

And again, notice the semicolon after the code line. It is a separator and very importantto include - otherwise the script won't work.

In the example, we used date, which is a function that returns the current date and

Created By www.ebooktutorials.blogspot.in

Content Downloaded from www.html.net 11

Page 13: PHP Tutorial

time on the server.

Let's try to extend the example by writing both a string and a function - separated by"." (a period) - it's done like this:

<html> <head> <title>My first PHP document</title> </head> <body>

<?php echo "<p>Current date and time: " . date("r") . "</p>";

?>

</body> </html>

It will look like this in the browser:

And the corresponding HTML code:

Created By www.ebooktutorials.blogspot.in

Content Downloaded from www.html.net 12

Page 14: PHP Tutorial

In the next lesson, we will take a closer look at the date function and the differentformats for date and time.

Created By www.ebooktutorials.blogspot.in

Content Downloaded from www.html.net 13

Page 15: PHP Tutorial

Lesson 4: Working with time and datesIn this lesson, we will try to look at the many different options for working with timeand dates in PHP. We went through some very simple examples in the previous lessonmostly to show you what PHP is. In this lesson, we will take a closer look at the datefunction.

Time and date functions

PHP provides a wide range of funtions in relation to time and date. In this lesson, wewill look at the most important of these functions: date.

With different parameters, the date function can return the current date / time inmany different formats. Some of the most useful parameters are:

date("y")Returns the current year from a date - with today's date, it returns: 12

date("m")Returns the current month from a date - with today's date, it returns: 09

date("n")Returns the current month from a date without leading zeroes ( eg. "1" instead of"01") - with today's date, it returns: 9

date("F")Returns the current month name from a date - with today's date, it returns:September

date("d")Returns the current day of the month from a date - with today's date, it returns:19

date("l")Returns the name of the current weekday from a date - with today's date, itreturns: Wednesday

date("w")Returns the current day of the week from a date - with today's date, it returns: 3

date("H")Returns the current hour from a time - with the current time, it returns: 04

date("i")Returns the current minute from a time - with the current time, it returns: 09

date("s")Returns the current second from a time - with the current time, it returns: 30

This example illustrates the use of the date function:

<html> <head> <title>Time and date</title>

Created By www.ebooktutorials.blogspot.in

Content Downloaded from www.html.net 14

Page 16: PHP Tutorial

</head> <body>

<?php echo "<p>Today it's " . date("l") . "</p>";

?> </body> </html>

Show example

The time is 1348020570

And now hold on... because now it becomes a little nerdy! The function time() returnsthe current time as the number of seconds since January 1, 1970, 12:00 PM, GMT.

<html> <head> <title>time and date</title> </head> <body>

<?php

echo "<p>It's been exactly " . time() . " seconds since January 1, 1970, 12:00 PM, GMT </ p> ";

?>

</body> </html>

Show example

Time expressed in the number of seconds since January 1, 1970, 12:00 PM GMT is aso-called "timestamp" (UNIX timestamp) and is quite useful when you work withdates/times in the future or the past.

By default, the date function uses the current timestamp (i.e. the current value of time()). But with an extra parameter you can specify a different time stamp and thuswork with the future or the past. In the example below, we set the timestamp to 0seconds from January 1, 1970 12:00 PM, GMT. Thereby we can check what day ofweek January 1, 1970 was.

<html> <head> <title>time and date</title> </head> <body>

<?php echo "<p>January 1, 1970 was a " . date("l",0) . "</p>";

?>

Created By www.ebooktutorials.blogspot.in

Content Downloaded from www.html.net 15

Page 17: PHP Tutorial

</body> </html>

Show example

Unless you are a mathematical genius, it quickly becomes complicated to count thenumber of seconds since January 1, 1970 to a specific time in the future or past. Buthere you can get help from another nifty function: mktime, which does thecalculations for you.

The syntax for mktime is (hour, minute, second, month, day, year). The examplebelow converts the time of the first step on the Moon (July 21, 1969, 02:56):

<html> <head> <title>time and date</title> </head> <body>

<?php echo mktime (2,56,0,7,21,1969);

?>

</body> </html>

Show example

Notice that it's returning a negative number as the date is earlier than January 1, 1970.

We can now put this together with the date function and find out which weekday thishistoric day took place.

<html> <head> <title>time and date</title> </head> <body>

<?php echo date("l", mktime(2,56,0,7,21,1969)); ?> </body> </html>

Show example

What can you use it for?

Created By www.ebooktutorials.blogspot.in

Content Downloaded from www.html.net 16

Page 18: PHP Tutorial

All this may seem a bit theoretical at this stage. After all, what on earth can you use afunction like time() for? More importantly, when will you learn something you canactually use on your pages?

The answer is that what you learn here are building blocks - the only limitations to whatyou can build are your creativity and imagination! I would venture to say that you havealready learned more than you think. For example, do you think you can make awebsite with different background images each day of the week and that works in allbrowsers?

Sure you can! Look at this example:

<html> <head> <title>time and date</title> </head>

<body background="background_<?php echo date("w"); ?>.png">

</body> </html>

Show example

The example above, with a dynamic background image, simply requires that you makeseven images and name them background_1.png, background_2.png,background_3.png, etc.

If a user then enters your site on a Tuesday, the site will have background_2.png asbackground, and the next day, background_3.png. Easy and simple!

In the next lesson, you will be introduced to new building blocks that can be used tomake loops and repetitions in your codes.

PHP is fun, don't you think?

Created By www.ebooktutorials.blogspot.in

Content Downloaded from www.html.net 17

Page 19: PHP Tutorial

Lesson 5: LoopsIn PHP, it is possible to manage the execution of scripts with different controlstructures. In this lesson, we will look at loops. Loops can be used to repeat parts of ascript a specified number of times or until a certain condition is met.

"while" loops

The syntax for a while loop is:

while (condition) { Statement }

The syntax can almost be directly translated into English: do something while acondition is met.

Let's look at a simple example:

<html> <head> <title>Loops</title>

</head> <body>

<?php

$x = 1; while ($x <= 50) { echo "<p>This text is repeated 50 times</p>"; $x = $x + 1; } ?>

</body>

</html>

Show example

In the example, a variable named "$x" is used. As you can see, variables in PHP alwaysstart with a "$" character. It's easy to forget this at first, but it's absolutely necessary toremember or else the script doesn't work.

Apart from that, the example is almost self-explanatory. First the variable $x is set to beequal to 1. Then the loop asks the server to repeat the text while $x is less or equal to50. In each loop, the variable $x will be increased by 1.

"for" loops

Created By www.ebooktutorials.blogspot.in

Content Downloaded from www.html.net 18

Page 20: PHP Tutorial

Another way to make a loop is with for on the form:

for (Initialization; Condition; Step) { Statement }

The statement is repeated as long as 'Initialization' + 'Step' meets the 'Condition'. Ifthat doesn't make sense, look at this example:

<html> <head>

<title>Loops</title> </head> <body>

<?php

for ($x=0; $x<=50; $x=$x+5) { echo '<p>variable $x is now = ' . $x . '</p>'; } ?>

</body> </html>

Show example

In the example above, $x is growing with the value 5 in each loop. The loop willcontinue as long as $x is below or equals 50. Also note how the value $x is used as partof the sentence.

Here is another example:

<html> <head>

<title>Loops</title> </head> <body>

<?php

for ($x=1; $x<=6; $x=$x+1) { echo "<h" . $x . ">Heading level " . $x . "</h" . $x . ">"; } ?>

</body> </html>

Show example

Do you get it? First we set the value of $x to 1. Then in each loop, we write a headingat level $x (h1, h2, h3, etc.) until $x is equal to six.

Created By www.ebooktutorials.blogspot.in

Content Downloaded from www.html.net 19

Page 21: PHP Tutorial

Loops within loops

In principle, there are no limitations on how loops can be used. For instance, you caneasily put loops inside loops and thereby create many repeats.

But be careful! PHP becomes slower the more complicated and extensive the scripts.For instance, look at the next example where, with three loops, we can write over 16million colors!

In order not to make the page slow, we have drastically reduced the number by puttingthe step to 30 and thereby limited the number of colors to 512.

<html>

<head> <title>Loops </title> </head> <body>

<?php for ($intRed=0; $intRed<=255; $intRed=$intRed+30) {

for ($intGreen=0; $intGreen<=255; $intGreen=$intGreen+30) {

for ($intBlue=0; $intBlue<=255; $intBlue=$intBlue+30) { $StrColor = "rgb(" . $intRed . "," . $intGreen . "," . $intBlue . ")"; echo "<span style='color:" . $StrColor . "'>" . $StrColor . "</span>"; } } } ?>

</body> </html>

Show example

In this example, each of three primary colors (red, green and blue) can have a valuebetween 0 and 255. Any combination of the three colors creates a color on the formrgb(255,255,255). The color code is used as color in a <span>.

Loops becomes more useful when you've learned a little more. When you understandthe principle in a loop, you can proceed to the next lesson, where we look at conditions.

Created By www.ebooktutorials.blogspot.in

Content Downloaded from www.html.net 20

Page 22: PHP Tutorial

Lesson 6: ConditionsConditions are used to execute part of a script only if some predefined requirements(conditions) are fulfilled. For example, a condition could be that a date must be afterJanuary 1, 2012 or that a variable is greater than 7.

If...

The first type of condition we will look at is if, which has the following syntax:

if (condition) { statement }

Again, the syntax is very close to ordinary English: If a condition is met, then executesomething. Let's look at a simple example:

<html>

<head> <title>Loops </title> </head> <body>

<?php

$x = 2;

if ($x > 1) { echo "<p>variable $x is greater than 1 </p>"; } ?>

</body> </html>

if ... else ...

The next type of condition will want to look at is else , which may be presented in thefollowing form:

if (condition) { statement } else { statement }

Again, the syntax is very close to ordinary English: if a condition is met executesomething or else execute something else.

Created By www.ebooktutorials.blogspot.in

Content Downloaded from www.html.net 21

Page 23: PHP Tutorial

In lesson 4, you learned how to find the number of a month. In the following example,we will use the month number in an if else condition to find out what season it is:

<html> <head> <title>Conditions</title> </head> <body>

<?php

if (date ("m") == 3) { echo "<p>Now it's spring!</p> "; } else { echo "<p>I do not know what season it is!</p> "; }

?>

</body> </html>

Show example

As you can see, this condition is not a particularly smart condition - it only works whenit's March!

However, there are plenty of ways to improve the condition and make it more precise.Below are listed comparison operators that can be used in the condition:

== Equals< Less than> Greater than<= Less than or equal to>= Greater than or equal to!= Not equal to

In addition, there are some logical operators:

&& And|| Or! Not

The operators can be used to develop more precise conditions, so now we can expandthe above example to include all the spring months:

<html> <head> <title>Conditions</title>

</head> <body>

<?php

Created By www.ebooktutorials.blogspot.in

Content Downloaded from www.html.net 22

Page 24: PHP Tutorial

if (date("m") >= 3 && date("m") <= 5) { echo "<p> Now it's spring!</p> "; } else { echo "<p> Now it's either winter, summer or autumn!</p> "; } ?>

</body> </html>

Let's take a closer look at the extended condition:

date("m") >= 3 && date("m") <= 5

The condition can be translated into:

If the month is greater than or equal to 3, and the month is less than or equal to 5

Smart, eh? Operators play a significant role in many different parts of PHP.

But it still only works with March, April and May. All other months are not yet coveredby the condition. So let's try to develop the condition a little more.

if ... elseif ... else...

Using elseif, we can expand the condition and make it work for all months:

<html> <head> <title>Conditions</title>

</head> <body>

<?php if (date("m") >= 3 && date("m") <= 5) { echo "<p>Now it's spring!</p>"; }

elseif (date("m") >= 6 && date("m") <= 8) { echo "<p>Now it's summer!</p>"; }

elseif (date("m") >= 9 && date("m") <= 11) { echo "<p>Now it's autumn!</p>"; }

else { echo "<p>Now is winter!</p>"; } ?>

</body> </html>

Created By www.ebooktutorials.blogspot.in

Content Downloaded from www.html.net 23

Page 25: PHP Tutorial

Show example

To write conditions is all about thinking logically and being methodical. The exampleabove is pretty straightforward, but conditions can get very complex.

switch ... case

Another way of writing conditions is to use the switch method:

switch (expression) { case 1: statement break; case 2: statement break; default: statement break; }

This method is based on an expression and then lists different "answers" or "values"with related statements. The easiest way to explain the method is to show anexample.

As you may remember from lesson 4, the function date("w") returns the currentweekday. This can be used in an example where we write the name of the day (insteadof a number):

<html> <head> <title>Conditions</title> </head> <body>

<?php switch(date("w")) { case 1: echo "Now it's Monday"; break; case 2: echo "Now it's Tuesday"; break; case 3: echo "Now it's Wednesday"; break; case 4: echo "Now it's Thursday"; break; case 5: echo "Now it's Friday"; break; case 6: echo "Now it's Saturday";

Created By www.ebooktutorials.blogspot.in

Content Downloaded from www.html.net 24

Page 26: PHP Tutorial

break; default: echo "Now it's Sunday"; break; } ?>

</body> </html>

Show example

Often switch can be a good alternative to if else conditions. What you should usein a given situation depends on which method you find easiest and most logical. Makingyour scripts logical and clear can be a great challenge.

In the next lesson, we will look at how you can add comments to your scripts to explainhow they work. Good comments can be crucial if you or somebody else has to makechanges in your codes at a later stage.

Created By www.ebooktutorials.blogspot.in

Content Downloaded from www.html.net 25

Page 27: PHP Tutorial

Lesson 7: Comment your scriptsAs you may have noticed, PHP scripts can easily look confusing. In this lesson, we coverwhy comments are important and how to insert them into your scripts.

Why is it important to comment your scripts?

When you are coding, you are writing commands to a server/computer and need to usea highly formal language that may not clearly reflect your thoughts when making thescript.

Therefore, it can be difficult for others (or yourself) to understand how the script isstructured, and thus hard to identify and correct errors in the script.

Comments can be used to write short explanatory text in the script. The servercompletely ignores the comments, and the comments do not affect the actualfunctionality of the script.

In the business world, it is often a requirement that scripts and programming arecommented, otherwise it would be too risky for a company to take over a system inwhich it would be too difficult to find and correct errors.

How do you insert comments?

It is quite easy to insert a comment. You simply start the comment with a double slash:"//".

Take a look at this example from lesson 5, now with comments:

<html> <head> <title>Loops</title> </head> <body>

<?php

// Here we write color codes using three loops

// Red can be between 0 and 255 for ($intRed=0; $intRed<=255; $intRed=$intRed+30) {

// Green can be between 0 and 255 for ($intGreen=0; $ intGreen<=255; $intGreen=$intGreen+30) {

// Blue can be between 0 and 255 for ($ intBlue=0; $intBlue<=255; $intBlue=$intBlue+30) {

// The color code is made on the form rgb(red,green,blue) $strColor = "rgb(" . $intRed . "," . $intGreen . "," . $intBlue . ")"

// Now we write the color code to the client echo "<span style='color:" . $strColor . "'> " . $strColor . "

Created By www.ebooktutorials.blogspot.in

Content Downloaded from www.html.net 26

Page 28: PHP Tutorial

</span>";

// Closes the loops } } }

?>

For the sake of the example, we have included many extra comments, so it should beclear that you are far better off debugging a script with comments than without.

Therefore, remember to comment your scripts!

Created By www.ebooktutorials.blogspot.in

Content Downloaded from www.html.net 27

Page 29: PHP Tutorial

Lesson 8: ArraysIn this lesson, we will look at what an array is, how it is used, and what it can do.

Understanding arrays can be a little difficult in the beginning. But give it a try anyway...we've tried to make it as easy as possible.

What is an array?

An array is a set of indexed elements where each has its own, unique identificationnumber.

Sound confusing? It's actually not that complicated.

Imagine a list of words separated by commas. It is called a comma-separated list, and itcould, for example, look like this:

apples, pears, bananas, oranges, lemons

Then try to imagine dividing the list at each comma. Next, give each section a uniqueidentification number like this:

What you see is an array. We can, for example, name the array "fruits". The idea is thatwe can access the array with a number and get a value back, like this:

fruits(0) = applesfruits(1) = pears fruits(2) = bananas fruits(3) = oranges fruits(4) = lemons

This is the idea behind arrays. Let us try to use it in practice.

How do you use an array?

We will continue with the fruit example. Step by step, we will make it work as a realarray. First, we set a variable equal to the list of fruits:

<?php

$fruitlist = "apples, pears, bananas, oranges, lemons";

Created By www.ebooktutorials.blogspot.in

Content Downloaded from www.html.net 28

Page 30: PHP Tutorial

?>

Next, we use the function explode to split the list at each comma:

<?php $fruitlist = "apples, pears, bananas, oranges, lemons"; $arrFruits = explode(",", $fruitlist);

?>

Voila! "$arrFruits" is now an array!

Notice that we called the function explode with two arguments:

1. the list that should be split2. and the delimiter - i.e., the character used to split (in this case a comma) - in

quotation marks: ",".

Here we use a comma as a delimiter, but you can use any character or word as adelimiter.

Let us try to comment the script and put it into a PHP page:

<html> <head> <title>Array</title> </head> <body>

<?php // Comma separated list $fruitlist = "apples, pears, bananas, oranges, lemons"; // Create an array by splitting the list (with comma as delimiter) $arrFruits = explode(",", $fruitlist); // Write the values from our array echo "<p>The list of fruits:</p>"; echo "<ul>"; echo "<li>" . $arrFruits[0] . "</li>"; echo "<li>" . $arrFruits[1] . "</li>"; echo "<li>" . $arrFruits[2] . "</li>"; echo "<li>" . $arrFruits[3] . "</li>"; echo "<li>" . $arrFruits[4] . "</li>"; echo "</ul>";

?>

</body> </html>

Show example

This example is very simple, and it might be a bit difficult to see the advantage of using

Created By www.ebooktutorials.blogspot.in

Content Downloaded from www.html.net 29

Page 31: PHP Tutorial

an array for this particular task. But just wait... arrays can be used for many very usefulthings.

Loop through an array

Back in lesson 5 you learned about loops. Now we will look at how you can loopthrough an array.

When you know how many elements an array contains, it is not a problem defining theloop. You simply start with 0 and let the loop continue to the number of items available.In the example with the fruits, you would loop through the array like this:

<html> <head> <title>Array</title>

</head> <body>

<?php // Comma separated list $fruitlist = "apples, pears, bananas, oranges, lemons"; // Create an array by splitting the list (with a comma as delimiter) $arrFruits = explode (",", $fruitlist); echo "<p>The list of fruits:</p>"; echo "<ul>"; // Loop through the array $arrFruits for ($x=0; $x<=4; $x++) { echo "<li>" . $arrFruits[$x] . "</li>"; } echo "</ul>";

?> </body> </html>

Show example

As you can see, the variable $x (which increases from 0 to 4 in the loop) was used tocall the array.

How to find the size of an array

But what if we add another fruit to the list? Then our array will contain one elementmore - which will get the identification number 5. Do you see the problem? Then weneed to change the loop, so it runs from 0 to 5, or else not all of the elements will beincluded.

Wouldn't it be nice if we automatically could find out how many elements an array

Created By www.ebooktutorials.blogspot.in

Content Downloaded from www.html.net 30

Page 32: PHP Tutorial

contains?

That's exactly what we can do with the function foreach. Now we can make a loopthat works regardless of the number of elements:

<?php foreach ($arrFruits as $x) { echo $x; } ?>

This loop will work regardless of how many or few elements the array contains.

Another example

Below is another example of how you can use an array to write the name of the month:

<html> <head> <title>Array</title>

</head> <body> <?php // Creates array with each month. // Creates array with the months. Note the comma before January - because there is no month with the number 0 $arrMonths = array("","January","February","March","April","May","June","July","August","September

// Call the array with the number of the month - write to the client echo $arrMonths[date("n")]; ?>

</body> </html>

Show example

Notice that we use the function array instead of the function explode to create anarray.

Ok. Enough about arrays! In the next lesson, you'll learn how to write your ownfunctions.

Created By www.ebooktutorials.blogspot.in

Content Downloaded from www.html.net 31

Page 33: PHP Tutorial

Lesson 9: FunctionsIn previous lessons you have learned to use functions like date() and array(). Inthis lesson, you will learn to create your own functions using function.

What is a function?

A function process inputs and returns an output. It can be useful if, for example, youhave a wide range of data you have processed or if you have calculations or routinesthat must be performed many times.

A function has the following syntax:

Function Name(list of parameters) { Statement }

This way, we can make a very simple function that can add the value 1 to a number. Itcould look like this:

function AddOne($x) { $x = $x + 1; echo $x; }

Our function is named AddOne and must be called with a number - e.g. 34....

echo AddOne(34);

... which (surprise!) will return 35.

The example above processes a number, but functions can work with text, dates oranything else. You can also create functions that are called by many differentparameters. In this lesson you will see different examples of functions.

Example 1: Function with more parameters

As mentioned above, you can easily create a function that can be called with moreparameters. In the next example, we'll create a function that is called with threenumbers and then returns the value of the three numbers added together:

<html> <head> <title>Functions</title>

Created By www.ebooktutorials.blogspot.in

Content Downloaded from www.html.net 32

Page 34: PHP Tutorial

</head> <body>

<?php

function AddAll($number1,$number2,$number3) { $plus = $number1 + $number2 + $number3; return $plus; } echo "123 + 654 + 9 equals " . AddAll(123,654,9);

?>

</body> </html>

Show example

Ok. Now that was almost too simple! But the point was just to show you that a functioncan be called with more parameters.

Example 2: English date and time

Let us try to make a slightly more complex function. A function that's called with a dateand time returns it in the format: Wednesday, 15 February, 2012, 10:00:00 AM

<html> <head> <title>Functions</title> </head> <body>

<?php

function EnglishDateTime($date) { // Array with the English names of the days of the week $arrDay = array("Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"); // Array with the English names of the months $arrMonth = array("","January","February","March","April","May","June","July","August","September

// The date is constructed $EnglishDateTime = $arrDay[(date("w",$date))] . ", " . date("d",$date); $EnglishDateTime = $EnglishDateTime . " " . $arrMonth[date("n",$date)] . " " . date("Y",$date); $EnglishDateTime = $EnglishDateTime . ", " . date("H",$date) . ":" . date("i",$date); return $EnglishDateTime;

} // Test function echo EnglishDateTime(time());

?>

</body> </html>

Created By www.ebooktutorials.blogspot.in

Content Downloaded from www.html.net 33

Page 35: PHP Tutorial

Show example

Please note how '$arrMonth' and '$EnglishDateTime' are constructed over several lines.This is done so that users with a low screen resolution can better see the example. Themethod has no effect on the code itself.

The function above works on all web servers regardless of language. This means thatyou can use such a function if your website, for example, is hosted on a French server,but you want English dates.

At this stage, we will not go into more depth with functions, but now you know a littleabout how functions work.

Created By www.ebooktutorials.blogspot.in

Content Downloaded from www.html.net 34

Page 36: PHP Tutorial

Lesson 10: Passing variables in a URLWhen you work with PHP, you often need to pass variables from one page to another.This lesson is about passing variables in a URL.

How does it work?

Maybe you have wondered why some URLs look something like this:

http://html.net/page.php?id=1254

Why is there a question mark after the page name?

The answer is that the characters after the question mark are an HTTP query string.An HTTP query string can contain both variables and their values. In the exampleabove, the HTTP query string contains a variable named "id", with the value "1254".

Here is another example:

http://html.net/page.php?name=Joe

Again, you have a variable ("name") with a value ("Joe").

How to get the variable with PHP?

Let's say you have a PHP page named people.php. Now you can call this page usingthe following URL:

people.php?name=Joe

With PHP, you will be able to get the value of the variable 'name' like this:

$_GET["name"]

So, you use $_GET to find the value of a named variable. Let's try it in an example:

<html> <head> <title>Query string</title> </head> <body>

<?php

// The value of the variable name is found echo "<h1>Hello " . $ _GET["name"] . "</h1>";

Created By www.ebooktutorials.blogspot.in

Content Downloaded from www.html.net 35

Page 37: PHP Tutorial

?>

</body> </html>

Show example (keep an eye on the URL)

When you look at the example above, try to replace the name "Joe" with your ownname in the URL and then call the document again! Quite nice, eh?

Several variables in the same URL

You are not limited to pass only one variable in a URL. By separating the variables with&, multiple variables can be passed:

people.php?name=Joe&age=24

This URL contains two variables: name and age. In the same way as above, you canget the variables like this:

$_GET["name"] $_GET["age"]

Let's add the extra variable to the example:

<html> <head> <title>Query string </title> </head> <body>

<?php

// The value of the variable name is found echo "<h1>Hello " . $_GET["name"] . "</h1>"; // The value of the variable age is found echo "<h1>You are " . $_GET["age"] . " years old </h1>";

?>

</body> </html>

Show example (keep an eye on the URL)

Now you have learned one way to pass values between pages by using the URL. In thenext lesson, we'll look at another method: forms.

Created By www.ebooktutorials.blogspot.in

Content Downloaded from www.html.net 36

Page 38: PHP Tutorial

Lesson 11: Passing variables with formsInteractive websites require input from users. One of the most common ways to getinput is with forms.

In this lesson, we will look at how to build forms and process inputs on the server.

<form>

When you code a form, there are two particular important attributes: action andmethod.

actionIs used to enter the URL where the form is submitted. It would be the PHP file thatyou want to handle the input.

methodCan either have the value "post" or "get", which are two different methods to passdata. At this point, you don't need to know much about the difference, but with"get", the data is sent through the URL, and with "post", the data is sent as a blockof data through standard input service (STDIN). In the last lesson, we looked athow data is retrieved through the URL using $_GET. In this lesson, we look athow data submitted through a form using the method "post" is retrieved.

An HTML page with a form

The page that contains the form doesn't need to be a PHP file (but it can be). It neednot even be on the same site as the file that will receive the data.

In our first example, we will look at a very simple form with one text field:

<html> <head> <title>Form</title> </head> <body>

<h1>Enter your name</h1>

<form method="post" action="handler.php"> <input type="text" name="username"> <input type="submit"> </form>

</body> </html>

The result in the browser is a form:

Created By www.ebooktutorials.blogspot.in

Content Downloaded from www.html.net 37

Page 39: PHP Tutorial

Now we come to the fun part: receiving and handling the data with PHP.

Requesting form data with PHP

When you need to request data submitted through a form (post method), you use $_POST:

$_POST["fieldname"];

Which returns the value of a field in the form. Let us try to use it in an example.

First create a page with a form as above. Then make a PHP page named "handler.php"(notice that this is the name of the page we wrote in the action attribute in our<form>).

The file "handler.php" shall have the following content:

<html> <head> <title>Form</title> </head>

<body>

<?php

echo "<h1>Hello " . $_POST["username"] . "</h1>";

?>

</body> </html>

Show example

User input and conditions

Created By www.ebooktutorials.blogspot.in

Content Downloaded from www.html.net 38

Page 40: PHP Tutorial

In the next example, we will try to use user input to create conditions. First, we need aform:

<html> <head> <title>Form</title> </head> <body>

<form method="post" action="handler.php">

<p>What is your name:</p> <input type="text" name="username"></p>

<p>What is your favorite color: <input type="radio" name="favoritecolor" value="r" /> Red <input type="radio" name="favoritecolor" value="g" /> Green <input type="radio" name="favoritecolor" value="b" /> Blue </p>

<input type="submit" value="Submit" />

</form>

</body> </html>

Which will look like this in the browser:

Now we will use these inputs to create a page that automatically changes backgroundcolor according to what the user's favorite color is. We can do this by creating acondition (see lesson 6) that uses the data the user has filled out in the form.

<?php

$strHeading = "<h1>Hello " . $_POST["username"] . "</h1>";

switch ($_POST["favoritecolor"]) { case "r": $strBackgroundColor = "rgb(255,0,0)"; break; case "g"; $strBackgroundColor = "rgb(0,255,0)"; break; case "b": $strBackgroundColor = "rgb(0,0,255)"; break; default:

Created By www.ebooktutorials.blogspot.in

Content Downloaded from www.html.net 39

Page 41: PHP Tutorial

$strBackgroundColor = "rgb(255,255,255)"; break; }

?>

<html> <head> <title>Form</title>

</head> <body style="background: <? echo $strBackgroundColor; ?>;">

<? echo $strHeading; ?>

</body> </html>

The background color will be white if the user has not chosen any favorite color in theform. This is done by using default to specify what should happen if none of the aboveconditions are met.

But what if the user does not fill out his name? Then it only says "Hello" in the title. Wewill use an extra condition to change that.

<?php

$strUsername = $_POST["username"]; if ($strUsername != "") { $strHeading = "<h1>Hello " . $_POST["username"] . "</h1>"; } else { $strHeading = "<h1>Hello stranger!</h1> "; }

switch ($_POST["favoritecolor"]) { case "r": $strBackgroundColor = "rgb(255,0,0)"; break; case "g"; $strBackgroundColor = "rgb(0,255,0)"; break; case "b": $strBackgroundColor = "rgb(0,0,255)"; break; default: $strBackgroundColor = "rgb(255,255,255)"; break; }

?>

<html>

<head>

<title>Form</title> </head> <body style="background: <? echo $strBackgroundColor; ?>;">

<? echo $strHeading; ?>

</body> </html>

Created By www.ebooktutorials.blogspot.in

Content Downloaded from www.html.net 40

Page 42: PHP Tutorial

Show example.

In the example above, we use a condition to validate the information from the user. Inthis case, it might not be so important if the user did not write his name. But as youcode more and more advanced stuff, it's vital that you take into account that the usermay not always fill out forms the way you had imagined.

Example: contact form

With your new knowledge of PHP and forms, you are able to create a contact formusing the function mail, which has the following syntax:

mail(to, subject, message);

First, we need a simple HTML form:

<html> <head> <title>Contact form</title> </head> <body>

<h1>Contact form</h1>

<form method="post" action="handler.php"> <p>Subject:<br /><input type="text" name="subject" /></p> <p>Message:<br /><textarea name="message"></textarea></p> <input type="submit"> </form>

</body> </html>

Next we need a PHP script to send the users input:

<html> <head> <title>Functions</title> </head> <body>

<?php

// Recipient (change to your e-mail address) $strEmail = "[email protected]";

// Get user inputs $strSubject = $_POST["subject"]; $strMessage = $_POST["message"];

mail($strEmail,$strSubject,$strMessage); echo "Mail Sent."; ?>

</body> </html>

Created By www.ebooktutorials.blogspot.in

Content Downloaded from www.html.net 41

Page 43: PHP Tutorial

Please note that the example will only work if you have access to a mail server. Bydefault, this is not the case in XAMPP and most free hosts. Also, some hosts mayrequire that you include a from header, which is done with an extra parameter:

mail("[email protected]", "Test", "This is a test mail", "From: [email protected]");

Created By www.ebooktutorials.blogspot.in

Content Downloaded from www.html.net 42

Page 44: PHP Tutorial

Lesson 12: SessionsWhen you visit a website, you do a number of different things. You click from one pageto another. Perhaps you also fill out a form or purchase a product.

As a web developer, such information is of great importance to developing successfulweb solutions.

Suppose, for example, that you want to make a site where some pages are protectedwith login and password. To make this protection effective, the password-protectedpages should have access to information on whether the user has logged in at an earliertime. You must, in other words, be able to "remember" what the user did earlier.

This is exactly what this lesson is about - how you can use sessions in PHP to store andretrieve information during a user's visit to your site.

Session

PHP session allows you to manage information about a user's session. Youcan write smart applications that can identify and gather information about users.

A session can begin in different ways. We will not go into technical details here butfocus on the case where a session starts by a value being stored. A session ends/dies ifthe user hasn't requested any pages within in a certain timeframe (by the standard 20minutes). Of course, you can also always end/kill a session in your script.

Let us say that 50 people are clicking around on the same site, e.g. a web shop, at thesame time. Information on what each of them have in their shopping cart would best bestored in a session. In order to identify the individual users, the server uses a uniqueuser ID that is stored in a cookie. A cookie is a small text file stored on the user'scomputer (more about cookies in lesson 13). Therefore, sessions often require supportof cookies in the user's browser.

An example of using sessions

When you requested this page, I stored the current time in a session. I did this so thatI can now show you an example of how a session works.

I named the item "StartTime" and stored it by adding the following line in my PHPscript:

<?php

session_start(); $_SESSION["StartTime"] = date("r");

Created By www.ebooktutorials.blogspot.in

Content Downloaded from www.html.net 43

Page 45: PHP Tutorial

?>

Thereby, a session was started. As described above, each session is given an ID by theserver.

Your session has the following ID: 743083bbfa3cdb81361df473fd050425

At any time, I can call the "StartTime" from the session by writing:

<?php

session_start(); echo $_SESSION["StartTime"];

?>

Which would reveal that the page was requested at Wed, 19 Sep 2012 04:22:00 +0200(according to the clock on this web server).

But what is interesting is that the information remains in the session, even after youhave left this page. The information will follow you until your session ends.

By default, a session lasts till the user closes the browser, then it dies automatically. Butif you want to stop a session, it can always be killed in this way:

<?php

session_destroy();

?>

Let us try to look at another example where sessions are used: a password solution.

Login system with sessions

In the following example, we will make a very simple login system. We will use many ofthe things we have learned in previous lessons.

The first thing we need is a form where people can enter their username and password.It could look like this:

<html> <head> <title>Login</title>

</head> <body> <form method="post" action="login.php">

<p>Username: <input type="text" name="username" /></p> <p>Password: <input type="text" name="password" /></p>

Created By www.ebooktutorials.blogspot.in

Content Downloaded from www.html.net 44

Page 46: PHP Tutorial

<p><input type="submit" value="Let me in" /></p>

</form> </body> </html>

Then we create the file: login.php.

In this file, we check whether it is the correct username and password that has beenentered. If that is the case, we set a session that says that this user is logged in withthe correct username and password.

<html>

<head> <title>Login</title>

</head> <body> <?php

// Check if username and password are correct if ($_POST["username"] == "php" && $_POST["password"] == "php") { // If correct, we set the session to YES session_start(); $_SESSION["Login"] = "YES"; echo "<h1>You are now logged correctly in</h1>"; echo "<p><a href='document.php'>Link to protected file</a><p/>"; } else { // If not correct, we set the session to NO session_start(); $_SESSION["Login"] = "NO"; echo "<h1>You are NOT logged correctly in </h1>"; echo "<p><a href='document.php'>Link to protected file</a></p>"; }

?>

</body> </html>

In the protected files, we want to check whether the user is logged in properly. If this isnot the case, the user is sent back to the login form. This is how the protection is made:

<?php

// Start up your PHP Session session_start();

// If the user is not logged in send him/her to the login form if ($_SESSION["Login"] != "YES") { header("Location: form.php"); }

?>

Created By www.ebooktutorials.blogspot.in

Content Downloaded from www.html.net 45

Page 47: PHP Tutorial

<html> <head> <title>Login</title> </head>

<body> <h1>This document is protected</h1>

<p>You can only see it if you are logged in.</p> </body> </html>

Click here to test the login system

Now you've been introduced to the Session object. In the next lesson, we are stillworking in the same area but will take a closer look at cookies.

Created By www.ebooktutorials.blogspot.in

Content Downloaded from www.html.net 46

Page 48: PHP Tutorial

Lesson 13: CookiesHow and what kind of information websites are collecting from their users, andespecially how they use it, is a hot topic. Cookies are often mentioned as an example ofhow information is collected and pose a threat to your privacy. But are there reasons tobe worried? Judge for yourself. Once you have gone through this lesson, you will knowwhat can be done with cookies.

What is a cookie?

A cookie is a small text file in which a website can store different information. Cookiesare saved on the user's hard drive and not on the server.

Most cookies expire (delete themselves) after a predetermined time period, which canrange from one minute to several years. But the user can also identify and delete anycookies on his/her computer.

Most browsers, such as Microsoft Internet Explorer, Mozilla Firefox and Google Chrome,can be configured to let the user choose whether or not he/she will accept a cookie. Butthen, why not just say no to all cookies? It is possible. But many websites would notwork as intended without cookies, since cookies in many contexts are used to improvethe usability and functionality of the website.

How is information stored in a cookie?

It's easy to set or modify a cookie in PHP with setcookie. In the firstexample, we will create a cookie and set the value.

First, you need a name for the cookie. In this example we will use the name"HTMLTest". Next, you set the value of the cookie like this:

<?php

// Setting the cookie setcookie("HTMLTest", "This is a test cookie");

?>

By default, a cookie is kept untill the browser is closed, but it can easily be modified byadding another parameter setting the expiry time:

<?php

// Setting the cookie setcookie("Name", "C. Wing, time()+3600); setcookie("Interests", "plane spotting", time()+3600); ?>

Created By www.ebooktutorials.blogspot.in

Content Downloaded from www.html.net 47

Page 49: PHP Tutorial

"Time()+3600" specified that the cookie should expire in 3600 seconds (60 minutes)from now.

In the example above, we stored information about a user's name and interests. Thisinformation can, for example, be useful to target the website specifically for theindividual visitor.

How do you retrieve the value of a cookie?

To get the value of the cookie, $_COOKIE is used. For example, if we need theinformation from the example above, we do it like this:

<?php

// Retrieve values from the cookie $strName = $_COOKIE["Name"]; $strInterest = $_COOKIE["Interest"]; // Write to the client echo "<p>" . strName . "</p>" echo "<p>Your interest is . " strInterest . "</p>" ?>

Who can read the cookie?

By default, a cookie can be read at the same second-level domain (e.g. html.net) as itwas created. But by using the parameters domain and path, you can put furtherrestrictions on the cookie using the following syntax:

setcookie(name, value, expiration time, path, domain);

Let us look at an example:

<?php // Setting the cookie: name, value, expiration time, path, domain setcookie("Name", "C. Wing", time()+60*60*24*365, "/tutorials/php/", "www.html.net"); ?>

In the example above, we set a cookie called "Name" with the value "C. Wing." Thecookie expires after one year (60 seconds * 60 minutes * 24 hours * 365 days) and canbe read only by sites located in the directory "/tutorials/php/" on the (sub-)domain"www.html.net".

Created By www.ebooktutorials.blogspot.in

Content Downloaded from www.html.net 48

Page 50: PHP Tutorial

Example of a cookie

We can try to save a sample cookie on your computer and then see how it looks.

The following code sets the cookie:

<?php

// Setting the cookie setcookie("HTMLTest", "This text is in a cookie!", time()+60*60*24, "/tutorials/php/", "www.html.net"); // Write the information to the client echo $_COOKIE ["HTMLTest"];

?>

Show example

The cookie is being placed on your hard drive. Depending on what operating systemyou use, your cookies may be saved in different places. Once you find them, they willprobably look like this:

As you can see, a cookie is a normal text file that can be open with Notepad, forexample. The contents of the cookie we have just created will probably look somethinglike this:

HTMLTest TEXT=This+text+is+in+a+cookie% 21 www.html.net/tutorials/php 0 80973619229399148 4216577264 29399141 *

We will not go into detail with the different codes, but simply note that the user has fullcontrol over cookies on his/her computer.

In this lesson, we have looked at what cookies can do but not what they can be usedfor. It's a common concern that some sites use cookies for inappropriate activities. Butin most cases, cookies are used to make sites more user-friendly or relevant for theindividual users.

If you choose to use cookies on your site, it might be a good idea to tell your users thatyour site uses cookies. This can, for example, be communicated in a privacy policy orregistration process.

Created By www.ebooktutorials.blogspot.in

Content Downloaded from www.html.net 49

Page 51: PHP Tutorial

Lesson 14: FilesystemWith PHP, you can access the server's filesystem. This allows you to manipulate foldersand text files in PHP scripts.

For example, you can use PHP to read or write a text file. Or you can list all files in aspecified folder. There are many possibilities and PHP can save you lots of tedious work.

Here, we'll look at how you can use PHP to work with folders and files. The goal is togive you a quick overview. In the next lessons, we will look more closely at the differentpossibilities. We will not go through all the different possibilities. Again, see thedocumentation for a complete listing.

filemtimeReturns the time for which the contents of a file was last edited (as UNIXtimestamp - see lesson 4)).

fileatimeReturns the time when a file was last accessed / opened (as a UNIX timestamp -see lesson 4)).

filesizeReturns the size of a file in bytes.

Let us try to find the three properties of the file you are looking at now:"/tutorials/php/lesson14.php"

<html>

<head> <title>Filesystem</title> </head> <body> <?php // Find and write properties echo "<h1>file: lesson14.php</h1>"; echo "<p>Was last edited: " . date("r", filemtime("lesson14.php")); echo "<p>Was last opened: " . date("r", fileatime("lesson14.php")); echo "<p>Size: " . filesize("lesson14.php") . " bytes"; ?>

</body> </html>

Show example

Folders

PHP also allows you to work with folders on the server. We will not go through all thedifferent possibilities - only show an example. Again, see the documentation for more

Created By www.ebooktutorials.blogspot.in

Content Downloaded from www.html.net 50

Page 52: PHP Tutorial

information.

opendirOpens a specified folder.

readdirReturns the filename of the next file in the open folder (cf. opendir)

closedirCloses a specified folder.

The example below lists the contents of the folder "tutorials/php/".

<html> <head> <title>FileSystemObject</title> </head> <body>

<?php // Opens the folder $folder = opendir("../../tutorials/php/");

// Loop trough all files in the folder while (($entry = readdir($folder)) != "") { echo $entry . "<br />"; }

// Close folder $folder = closedir($folder);

?>

</body>

</html>

Show example

In the example the directory "../../tutorials/php/" is first opened. Then a loop is used towrite the name of the next file in the folder as long as there are more files. At the end,the folder is closed.

In the next lessons, we will look at how to read from and write to a text file.

Created By www.ebooktutorials.blogspot.in

Content Downloaded from www.html.net 51

Page 53: PHP Tutorial

Lesson 15: Reading from a text fileIn the previous lesson, we learned how to use PHP to access the server's filesystem. Inthis lesson, we will use that information to read from an ordinary text file.

Text files can be extremely useful for storing various kinds of data. They are not quiteas flexible as real databases, but text files typically don't require as much memory.Moreover, text files are a plain and simple format that works on most systems.

Open the text file

We use the fopen function to open a text file. The syntax is as follows:

fopen(filename, mode)

filenameName of the file to be opened.

modeMode can be set to "r" (reading), "w" (writing) or "a" (appending). In this lesson,we will only read from a file and, therefore, use "r". In the next lesson, we willlearn to write and append text to a file.

The examples in this lesson use the text file unitednations.txt. This is a simple list of theProgrammes and Funds of the United Nations and their domains. You can eitherdownload the file, or you can create your own file and test the examples with it.

First, let's try to open unitednations.txt:

<?php

// Open the text file $f = fopen("unitednations.txt", "r");

// Close the text file fclose($f);

?>

Example 1: Read a line from the text file

With the function fgets, we can read a line from the text file. This method reads untilthe first line break (but not including the line break).

<html>

<head> <title>Reading from text files</title>

Created By www.ebooktutorials.blogspot.in

Content Downloaded from www.html.net 52

Page 54: PHP Tutorial

</head> <body>

<?php

$f = fopen("unitednations.txt", "r");

// Read line from the text file and write the contents to the client echo fgets($f);

fclose($f);

?>

</body> </html>

Show example

Example 2: Read all lines from the text file <html>

<head> <title>Reading from text files</title> </head> <body>

<?php

$f = fopen("unitednations.txt", "r");

// Read line by line until end of file while(!feof($f)) { echo fgets($f) . "<br />"; }

fclose($f);

?>

</body> </html>

Show example

In the example, we loop through all the lines and use the function feof (for end-of-file) to check if you are at the end of the file. If this is not the case ("!" - see lesson 6),the line is written.

Instead of looping through all the lines, we could have achieved the same result withthe function fread. If you work with very large text files with thousands oflines, be aware that the fread function uses more resources than the fgetsfunction. For smaller files, it makes very little difference.

Example 3: A simple link directory

Created By www.ebooktutorials.blogspot.in

Content Downloaded from www.html.net 53

Page 55: PHP Tutorial

As mentioned at the beginning of this lesson, text files can be excellent for datastorage. This is illustrated in the next example where we create a simple link directoryfrom the contents of the text file unitednations.txt.

The file is systematically written with the name of the program, then a comma, andthen the domain. As you can probably imagine, more information could easily be storedin this comma-separated data file.

To get the information in each line, we use an array. See Lesson 8 for more informationon arrays.

<html> <head> <title>Reading from text files</title>

</head> <body>

<?php $f = fopen("unitednations.txt", "r");

// Read line by line until end of file while (!feof($f)) {

// Make an array using comma as delimiter $arrM = explode(",",fgets($f));

// Write links (get the data in the array) echo "<li><a href='http://" . $arrM[1] . "'>" . $arrM[0]. "</a></li>";

}

fclose($f); ?>

</body> </html>

Show example

Quite handy, right? In principle, you could now just expand the text file with hundredsof links or perhaps expand your directory to also include address information.

In the next lesson, we will look at how to write to a text file.

Created By www.ebooktutorials.blogspot.in

Content Downloaded from www.html.net 54

Page 56: PHP Tutorial

Lesson 16: Writing to a text fileIn the previous lesson, we learned to read from a text file. In this lesson, we will learnto write to a text file.

The two methods are very similar, but there is one very important difference: You musthave write permissions to the file. This means that the file will have to be located in afolder where you have the necessary permissions.

If you work locally on your own computer, you can set the permissions yourself: right-click on the folder and choose "Properties". With most web hosts, you will normallyhave one folder with write permissions. It's often called something like "cgi-bin", "log","databases" or something similar. If your web host permits it, you might also be able toset permissions yourself. Usually you can simply right-click on a folder in your FTP clientand choose "properties" or "permissions" or something similar. The screendumps belowshows how it's done in FileZilla.

Read more on your web host's support pages.

Note that it is the text file that needs to be in the folder with write permissions - not thePHP file.

Open the text file for writing

In the same way as when reading from a text file, the fopen function is used forwriting, but this time we set the mode to "w" (writing) or "a" (appending).

The difference between writing and appending is where the 'cursor' is located - either atthe beginning or at the end of the text file.

The examples in this lesson use an empty text file called textfile.txt. But you can also

Created By www.ebooktutorials.blogspot.in

Content Downloaded from www.html.net 55

Page 57: PHP Tutorial

create your own text file if you like.

First, let us try to open the text file for writing:

<?php

// Open the text file $f = fopen("textfile.txt", "w");

// Close the text file fclose($f);

?>

Example 1: Write a line to the text file

To write a line, we must use the function fwrite, like this:

<html>

<head> <title>Writing to a text file</title> </head> <body>

<?php

// Open the text file $f = fopen("textfile.txt", "w");

// Write text line fwrite($f, "PHP is fun!");

// Close the text file fclose($f);

// Open file for reading, and read the line $f = fopen("textfile.txt", "r"); echo fgets($f);

fclose($f);

?>

</body> </html>

Show example

Since we opened the file for writing, the line is added at the top, and thus overwritesthe existing line. If we instead open the file appending, the line is added at the bottomof the text file, which then will increase by one line each time it's written to.

Example 2: Adding a text block to a text file

Of course, it is also possible to add an entire text block, instead of just a single line, likethis:

Created By www.ebooktutorials.blogspot.in

Content Downloaded from www.html.net 56

Page 58: PHP Tutorial

<html> <head> <title>Write to a text file</title> </head> <body>

<h1>Adding a text block to a text file:</h1> <form action="myfile.php" method='post'> <textarea name='textblock'></textarea> <input type='submit' value='Add text'> </form>

<?php

// Open the text file $f = fopen("textfile.txt", "w");

// Write text fwrite($f, $_POST["textblock"]);

// Close the text file fclose($f);

// Open file for reading, and read the line $f = fopen("textfile.txt", "r");

// Read text echo fgets($f); fclose($f);

?> </body>

</html>

Show example

In the next lessons, we look at another way of storing data: databases

Created By www.ebooktutorials.blogspot.in

Content Downloaded from www.html.net 57

Page 59: PHP Tutorial

Lesson 17: DatabasesA database is a collection of information / data that is organized so that it can easily beretrieved, administrated and updated. Databases thereby enable the opportunity tocreate dynamic websites with large amounts of information. For example, all data onmembers of HTML.net and all posts in the forums are stored in databases.

A database usually consists of one or more tables. If you are used to working withspreadsheets, or maybe have used databases before, tables will look familiar to youwith columns and rows:

There are many different databases: MySQL, MS Access, MS SQL Server, Oracle SQLServer and many others. In this tutorial, we will use the MySQL database. MySQL is thenatural place to start when you want to use databases in PHP.

You need to have access to MySQL in order to go through this lesson and the nextlessons:

If you have a hosted website with PHP, MySQL is probably already installed on theserver. Read more at your web host's support pages.If you have installed PHP on your computer yourself and have the courage toinstall MySQL as well, it can be downloaded in a free version (MySQL CommunityEdition) at the MySQL's website.If you use XAMPP (see lesson 2), MySQL is already installed and ready to use onyour computer. Just make sure MySQL is running in the Control Panel:

Created By www.ebooktutorials.blogspot.in

Content Downloaded from www.html.net 58

Page 60: PHP Tutorial

In the rest of this lesson, we will look more closely at how you connect to yourdatabase server, before we learn to create databases and retrieve and update data inthe following sessions.

Connection to database server

First, you need to have access to the server where your MySQL database is located.This is done with the function mysql_connect with the following syntax:

mysql_connect(server, username, password)

Pretty straightforward: First, you write the location of the database (server), and thentype in the username and password.

If you have your own website, you should read about location of your MySQL server onyour host's support pages. Username and password will often be the same as those youuse for FTP access. Otherwise contact your provider.

Example of a MySQL connection on a hosted website:

mysql_connect("mysql.myhost.com", "user001", "sesame") or die(mysql_error());

Example of a MySQL connection with XAMPP (default settings):

mysql_connect("localhost", "root", "") or die (mysql_error());

Created By www.ebooktutorials.blogspot.in

Content Downloaded from www.html.net 59

Page 61: PHP Tutorial

In the examples are added or die(mysql_error()) which, in brief, interrupts the scriptand writes the error if the connection fails.

Now we have made a connection to a MySQL server, and can now start creatingdatabases and retrieve and insert data. This is exactly what we will look at in the nextlessons.

By the way, keep in mind that it is good practice to close the database connection againwhen you're finished retrieving or updating data. This is done with the function mysql_close.

Created By www.ebooktutorials.blogspot.in

Content Downloaded from www.html.net 60

Page 62: PHP Tutorial

Lesson 18: Create databases and tablesIn the previous lesson we looked at how to create a connection to a database server. Next step is tocreate databases and tables.

We'll look at two ways to create databases and tables. First, how it is done in PHP, and then how it'smade with the more user-friendly tool PhpMyAdmin, which is standard on most web hosts and inXAMPP.

If you have a hosted website with PHP and MySQL, a database has probably been created for youalready and you can just skip this part of the lesson and start creating tables. Again, you shouldconsult your host's support pages for more information.

Create a database and tables with PHP

The function mysql_query are used to send a query to a MySQL database. The queries arewritten in the language Structured Query Language (SQL). SQL is the most widely used language fordatabase queries - not only for MySQL databases - and is very logical and easy to learn. In this lessonand the next, you will learn the most important SQL queries.

When creating a database, the SQL query CREATE DATABASE is used with the followingsyntax:

CREATE DATABASE database name

Logical and easy, right!? Let's try to put it into a PHP script:

mysql_connect("mysql.myhost.com", "user", "sesame") or die(mysql_error());

mysql_query("CREATE DATABASE mydatabase") or die(mysql_error());

mysql_close();

First, we connect to the MySQL server. Next, we create a database named "mydatabase". And finally,we close the connection to the MySQL server again.

So far so good... but things become a little bit more complicated when we want create tables in PHP.When creating tables, we use the SQL query CREATE TABLE with the following syntax:

CREATE TABLE table name ( column1_name DATA_TYPE, column2_name DATA_TYPE, column3_name DATA_TYPE, ... )

table_name and column_name are of course the name of the table and the columns, respectively.DATA_TYPE are used to specify the data type to be inserted into the column. The most commonly useddata types are:

INTFor numbers without decimals

DECIMAL

Created By www.ebooktutorials.blogspot.in

Content Downloaded from www.html.net 61

Page 63: PHP Tutorial

For numbers with decimalsCHAR

Short text up to 255 charactersTEXT

For plain text up to 65,535 charactersLONGTEXT

For long passages of text up to 4,294,967,295 charactersDate

For dates in the format YYYY-MM-DDTime

For time in the format HH:MM:SSDATETIME

For date and time in the format YYYY-MM-DD HH:MM:SS

All in all, logical and relatively easy. Let's try to put it into an example:

mysql_connect("mysql.myhost.com", "user", "sesame") or die(mysql_error()); mysql_select_db("people") or die(mysql_error());

mysql_query("CREATE TABLE MyTable ( id INT AUTO_INCREMENT, FirstName CHAR, LastName CHAR, Phone INT, BirthDate DATE PRIMARY KEY(id) )") Or die(mysql_error()); mysql_close ();

In the example, we start by connecting to the MySQL server. Next we use the function mysql_select_db to select the database "people". Then we create the table "persons" with 5 columns.

Note that at the "id" column, we first use INT to specify that the column contains numbers and thenadd AUTO_INCREMENT to automatically increase the number and ensure a unique ID for each row.

At the end, we use PRIMARY KEY to set the "id" column as the primary key. The primary keyuniquely identifies each record (/row) in the table, which becomes very useful later when we updatethe database.

Create database and tables with phpMyAdmin

It can be useful to be able to create databases and tables directly in PHP. But often, it will be easier touse phpMyAdmin (or any other MySQL administration tool), which is standard on most web hosts andXAMPP. The screendumps below shows how to create a database and tables in phpMyAdmin.

Start by logging onto phpMyAdmin. Often, the address will be the same as your MySQL server (eg."http://mysql.myhost.com") and with the same username and password. In XAMPP, the address ishttp://localhost/phpmyadmin/.

When you are logged on, simply type a name for the database and press the button "Create":

Created By www.ebooktutorials.blogspot.in

Content Downloaded from www.html.net 62

Page 64: PHP Tutorial

At some hosts, it's possible the have already created a database, and you may not have the rights tocreate more. If that is the case, you obviously just use the assigned database.

To create a table, click on the tab "Databases" and choose a database by clicking on it:

Then there will be a box titled "Create new table in database", where you type the name of the tableand the number of columns and press the button "Go":

Then you can name the columns and set the data type, etc., as in the SQL example above.

Notice, that here we also set "id" as PRIMARY KEY and uses AUTO_INCREMENT (A_I).

Created By www.ebooktutorials.blogspot.in

Content Downloaded from www.html.net 63

Page 65: PHP Tutorial

Now you have created your own database and table. In the next lessons, we look at how to insert,retrieve and delete data in a database

Created By www.ebooktutorials.blogspot.in

Content Downloaded from www.html.net 64

Page 66: PHP Tutorial

Lesson 19: Insert data into a databaseIn this lesson, we look at how you can insert data into the database directly from your PHP scripts.

Insert data using SQL

You use SQL to insert data in a database in the same way that you can use SQL to create databasesand tables. The syntax of the SQL query is:

INSERT INTO TableName(column1, column2, ...) VALUES(value1, value2, ...)

As you can see, you can update multiple columns in the SQL statement by specifying them in a comma-separated list. But of course, it is also possible to specify just one column and one value. The columnsthat are not mentioned in the SQL statement will just be empty.

Example: Insert a new person in the table

In this example we use the database from lesson 18. Let's say we want to insert a person into thedatabase. It could be the person Gus Goose with the phone number 99887766 and 1964-04-20 as thedate of birth.

The SQL statement would then look like this:

$strSQL = "INSERT INTO people(FirstName,LastName,Phone,BirthDate) VALUES('Gus','Goose','99887766 ','1964-04-20')";

mysql_query($strSQL) or die(mysql_error());

As you can see, SQL statements can get quite long, and you can easily lose track. Therefore, it can bean advantage to write the SQL statement in a slightly different way:

strSQL = "INSERT INTO people(";

strSQL = strSQL . "FirstName, "; strSQL = strSQL . "LastName, " strSQL = strSQL . "Phone, "; strSQL = strSQL . "birth) ";

strSQL = strSQL . "VALUES (";

strSQL = strSQL . "'Gus', "; strSQL = strSQL . "'Goose', "; strSQL = strSQL . "'99887766', ";

strSQL = strSQL . "'1964-04-20')"; mysql_query($strSQL) or die(mysql_error());

This way, the SQL statement is built up by splitting the sentence into small parts and then puttingthose parts together in the variable $strSQL.

In practice, it makes no difference which method you choose, but once you start working with largertables, it's crucial that you always keep track, so choose the method you find most convenient.

Try running the following code to insert Gus Goose into the database:

<html>

Created By www.ebooktutorials.blogspot.in

Content Downloaded from www.html.net 65

Page 67: PHP Tutorial

<head> <title>Insert data into database</title> </head> <body> <?php

// Connect to database server mysql_connect("mysql.myhost.com", "user", "sesame") or die (mysql_error ());

// Select database mysql_select_db("mydatabase") or die(mysql_error());

// The SQL statement is built

$strSQL = "INSERT INTO people(";

$strSQL = $strSQL . "FirstName, "; $strSQL = $strSQL . "LastName, ";

$strSQL = $strSQL . "Phone, "; $strSQL = $strSQL . "BirthDate) ";

$strSQL = $strSQL . "VALUES(";

$strSQL = $strSQL . "'Gus', ";

$strSQL = $strSQL . "'Goose', "; $strSQL = $strSQL . "'99887766', ";

$strSQL = $strSQL . "'1964-04-20')";

// The SQL statement is executed mysql_query($strSQL) or die (mysql_error());

// Close the database connection mysql_close(); ?>

<h1>The database is updated!</h1> </body> </html>

Save user input into a database

Often you want to save user input in a database.

As you've probably already figured out, this can be done by creating a form as described in lesson 11 -where the values from the form fields can be inserted in the SQL statement. Suppose you have asimple form like this:

<form action="insert.php" method="post"> <input type="text" name="FirstName" /> <input type="submit" value="Save" />

</form>

The form submits to the file insert.php where you, as shown in lesson 11, can get the user's input byrequesting the form content. In this particular example, an SQL statement could look like this:

strSQL = "INSERT INTO people(FirstName) values('" . $_POST["FirstName"] . "')"

In the same way, it is possible to retrieve data from cookies, sessions, query strings, etc.

Most common beginner mistakes

In the beginning, you will probably get a lot of error messages when you try to update your databases.There is no room for the slightest inaccuracy when you work databases. A misplaced comma can mean

Created By www.ebooktutorials.blogspot.in

Content Downloaded from www.html.net 66

Page 68: PHP Tutorial

the database is not being updated, and you get an error message instead. Below, we describe the mostcommon beginner mistakes.

Wrong data types

It is important that there is consistency between the type of data and column. Each column can be setto a data type. The screenshot below shows the data types for the table "people" in our example.

An error occurs if you, for example, attempt to insert text or numbers in a date field. Therefore, try toset the data types as precisely as possible.

Below is the most common data types listed:

Setting Data Type Size

CHAR Text or combinations of text and numbers. Can also be used for numbersthat are not used in calculations (e.g., phone numbers).

Up to 255 characters - or thelength defined in the "Length"

TEXT Longer pieces of text, or combinations of text and numbers. Up to 65,535 characters.INT Numerical data for mathematical calculations. 4 bytes.DATE Dates in the format YYYY-MM-DD 3 bytes.TIME Time in the format hh:mm:ss 3 bytes.DATETIME Date and time in the format YYYY-MM-DD hh:mm:ss 8 bytes.

SQL statements with quotes or backslash

If you try to insert text that contains the characters single quote ('), double quote (") or backslash (\),the record may not be inserted into the database. The solution is to add backslashes before charactersthat need to be quoted in database queries.

This can be done with the function addslashes this way:

<?php

$strText = "Is your name O'Reilly?"; $strText = addslashes($strText);

?>

All single quotes ('), double quotes (") and backslashs (\) will then get an extra backslash before thecharacter. This would only be to get the data into the database, the extra \ will not be inserted. Pleasenote that PHP runs addslashes on all $_GET, $_POST, and $_COOKIE data by default. Therefore donot use addslashes on strings that have already been escaped.

In the next lesson you will learn to retrieve data from your database. But first, try to insert some morepeople in your database (as shown in the example above with Gus Goose).

Created By www.ebooktutorials.blogspot.in

Content Downloaded from www.html.net 67

Page 69: PHP Tutorial

Lesson 20: Get data from databaseNow it's time to retrieve data from our database to our PHP pages.

This is really one of the most important lessons in this tutorial. Once you have read andunderstood this lesson, you will realize why database-driven web solutions are sopowerful, and your views on web development will be expanded dramatically.

SQL queries

To retrieve data from a database, you use queries. An example of a query could be:"get all data from the table 'people' sorted alphabetically" or "get names from the table'people'".

Again, the language Structured Query Language (SQL) is used to communicate with thedatabase. Try looking at this simple example:

Get all data from the table 'people'

Will be written like this in SQL:

SELECT * FROM people

The syntax is pretty self-explanatory. Just read on and see how SQL statements areused in the examples below.

Example 1: Retrieve data from a table

This example uses the database and table from lesson 19 and lesson 18. Therefore, it isimportant that you read these lessons first.

The example shows how data in the table "people" is retrieved with an SQL query.

The SQL query returns a result in the form of a series of records. These records arestored in a so-called recordset. A recordset can be described as a kind of table in theserver's memory, containing rows of data (records), and each record is subdivided intoindividual fields (or columns).

A recordset can be compared to a table where each record could be compared to a rowin the table. In PHP, we can run through a recordset with a loop and the function mysql_fetch_array, which returns each row as an array.

The code below shows how to use mysql_fetch_array to loop through a recordset:

Created By www.ebooktutorials.blogspot.in

Content Downloaded from www.html.net 68

Page 70: PHP Tutorial

<html> <head> <title>Retrieve data from database </title> </head> <body>

<?php // Connect to database server mysql_connect("mysql.myhost.com", "user", "sesame") or die (mysql_error ());

// Select database mysql_select_db("mydatabase") or die(mysql_error());

// SQL query $strSQL = "SELECT * FROM people";

// Execute the query (the recordset $rs contains the result) $rs = mysql_query($strSQL); // Loop the recordset $rs // Each row will be made into an array ($row) using mysql_fetch_array while($row = mysql_fetch_array($rs)) {

// Write the value of the column FirstName (which is now in the array $row) echo $row['FirstName'] . "<br />";

}

// Close the database connection mysql_close(); ?> </body> </html>

Show example

Notice that for every record how we get the content of the column "FirstName" bytyping $row['FirstName']. Similarly, we can get the content of the column "Phone" bywriting $row['Phone'], for example.

The order of the recordset is exactly the same as in the table in the database. But in thenext example, it will be shown how to sort recordset.

Example 2: Sort the data alphabetically,chronologically or numerically

Often it can be helpful if a list or table of data is presented alphabetically,chronologically or numerically. Such sorting is very easy to do with SQL, where thesyntax Order By ColumnName is used to sort according to the column contents.

Look at the SQL statement from the example above:

strSQL = "SELECT * FROM people"

The records can, for example, be sorted alphabetically by the first name of the people

Created By www.ebooktutorials.blogspot.in

Content Downloaded from www.html.net 69

Page 71: PHP Tutorial

this way:

strSQL = "SELECT * FROM people ORDER BY FirstName"

Or chronologically by date of birth like this:

strSQL = "SELECT * FROM people ORDER BY BirthDate"

The sorting can be charged from ascending to descending by adding DESC:

strSQL = "SELECT * FROM people ORDER BY BirthDate DESC"

In the following example, the people are sorted by age:

<html> <head>

<title>Retrieve data from database </title>

</head> <body> <?php // Connect to database server mysql_connect("mysql.myhost.com", "user", "sesame") or die (mysql_error ());

// Select database mysql_select_db("mydatabase") or die(mysql_error());

// SQL query $strSQL = "SELECT * FROM people ORDER BY BirthDate DESC";

// Execute the query (the recordset $rs contains the result) $rs = mysql_query($strSQL); // Loop the recordset $rs while($row = mysql_fetch_array($rs)) {

// Write the value of the column FirstName and BirthDate echo $row['FirstName'] . " " . $row['BirthDate'] . "<br />";

}

// Close the database connection mysql_close(); ?>

</body> </html>

Show example

Try to change the SQL statement yourself and sort the records by first name, last nameor phone number.

Retrieve selected data

Created By www.ebooktutorials.blogspot.in

Content Downloaded from www.html.net 70

Page 72: PHP Tutorial

Until now, our SQL statement retrieves all rows from the table. But often you need toset criteria in the SQL query for the data to be retrieved, for instance, if we only wantthe rows for those who have a particular phone number or a certain last name.

Say, we only want to retrieve people from the database who have the phone number"66554433". That could be done like this:

strSQL = "SELECT * FROM people WHERE Phone = '66554433 '"

There are six relational operators in SQL:

= Equals< Less than> Greater Than<= Less than or equal to>= Greater than or equal to!= Not equal to

In addition, there are some logical operators:

ANDORNOT

See lesson 6 for more information on how to set up conditions.

In the next example, we use conditions to set up an address book.

Example 3: Address book

In this example, we will try to combine many of the things you have just learned. Wewill make a list of the names from the database where each name is a link to furtherdetails about the person.

For this, we need two files - list.php and person.php - with the following code:

The code of list.php

<html> <head> <title>Retrieve data from the database</title> </head> <body>

<ul>

<?php // Connect to database server mysql_connect("mysql.myhost.com", "user", "sesame") or die (mysql_error

Created By www.ebooktutorials.blogspot.in

Content Downloaded from www.html.net 71

Page 73: PHP Tutorial

());

// Select database mysql_select_db("mydatabase") or die(mysql_error());

// SQL query $strSQL = "SELECT * FROM people ORDER BY FirstName DESC";

// Execute the query (the recordset $rs contains the result) $rs = mysql_query($strSQL); // Loop the recordset $rs while($row = mysql_fetch_array($rs)) {

// Name of the person $strName = $row['FirstName'] . " " . $row['LastName'];

// Create a link to person.php with the id-value in the URL $strLink = "<a href = 'person.php?id = " . $row['id'] . "'>" . $strNavn . "</a>";

// List link echo "<li>" . $strLink . "</li>";

}

// Close the database connection mysql_close(); ?>

</ul> </body> </html>

The code for person.php

<html> <head> <title>Retrieve data from database</title> </head> <body>

<dl>

<?php // Connect to database server mysql_connect("mysql.myhost.com", "user", "sesame") or die (mysql_error ());

// Select database mysql_select_db("mydatabase") or die(mysql_error());

// Get data from the database depending on the value of the id in the URL $strSQL = "SELECT * FROM people WHERE id=" . $_GET["id"]; $rs = mysql_query($strSQL); // Loop the recordset $rs while($row = mysql_fetch_array($rs)) {

// Write the data of the person echo "<dt>Name:</dt><dd>" . $row["FirstName"] . " " . $row["LastName"] . "</dd>"; echo "<dt>Phone:</dt><dd>" . $row["Phone"] . "</dd>"; echo "<dt>Birthdate:</dt><dd>" . $row["BirthDate"] . "</dd>";

}

// Close the database connection mysql_close();

Created By www.ebooktutorials.blogspot.in

Content Downloaded from www.html.net 72

Page 74: PHP Tutorial

?>

</dl> <p><a href="list.php">Return to the list</a></p>

</body>

</html>

Show example

The address book example is rather simple, but it shows the potential of working withPHP and databases.

Imagine that the database had contained 10,000 products with detailed descriptions. Bymaking a few changes in the above files, you could easily create a product cataloguewith more than 10,000 pages with only one database and two PHP files.

Welcome to a world with extensive websites that are easy to develop and maintain!Once you've learned to work with databases, your web solutions will never be the sameagain.

Created By www.ebooktutorials.blogspot.in

Content Downloaded from www.html.net 73

Page 75: PHP Tutorial

Lesson 21: Delete data from databaseIn the two previous lessons, you have learned to insert and retrieve data from adatabase. In this lesson, we'll look at how to delete records in the database, which isconsiderably easier than inserting data.

Delete data using SQL

The syntax for an SQL statement that deletes records is:

DELETE FROM TableName WHERE condition

Example: Delete a record

When deleting a record, you can use the unique AutoNumber field in the database. Inour database, it is the column named id. Using this unique identifier ensures that youonly delete one record. In the next example, we delete the record where id has thevalue 24:

<html> <head> <title>Delete data in the database</title> </head>

<body> <?php // Connect to database server mysql_connect("mysql.myhost.com", "user", "sesame") or die (mysql_error ());

// Select database mysql_select_db("mydatabase") or die(mysql_error());

// The SQL statement that deletes the record $strSQL = "DELETE FROM people WHERE id = 24"; mysql_query($strSQL); // Close the database connection mysql_close(); ?>

<h1>Record is deleted!</h1>

</body> </html>

Remember that there is no "Recycle Bin" when working with databases and PHP. Onceyou have deleted a record, it is gone and cannot be restored.

Created By www.ebooktutorials.blogspot.in

Content Downloaded from www.html.net 74

Page 76: PHP Tutorial

Lesson 22: Update data in a databaseIn previous lessons, you have learned to insert, retrieve and delete data from adatabase. In this lesson, we will look at how to update a database, i.e., edit the valuesof existing fields in the table.

Update data with SQL

The syntax for an SQL statement that updates the fields in a table is:

UPDATE TableName SET TableColumn='value' WHERE condition

It is also possible to update multiple cells at once using the same SQL statement:

UPDATE TableName SET TableColumn1='value1', TableColumn2='value2' WHERE condition

With the knowledge you now have from the lessons 19, 20 and 21, it should be quiteeasy to understand how the above syntax is used in practice. But we will of course lookat an example.

Example: Update cells in the table "people"

The code below updates Donald Duck's first name to D. and changes the phonenumber to 44444444. The other information (last name and birthdate) are notchanged. You can try to change the other people's data by writing your own SQLstatements.

<html> <head> <title>Update data in database</title>

</head> <body>

<?php // Connect to database server mysql_connect("mysql.myhost.com", "user", "sesame") or die (mysql_error ());

// Select database mysql_select_db("mydatabase") or die(mysql_error()); // The SQL statement is built $strSQL = "Update people set "; $strSQL = $strSQL . "FirstName= 'D.', "; $strSQL = $strSQL . "Phone= '44444444' ";

$strSQL = $strSQL . "Where id = 22";

Created By www.ebooktutorials.blogspot.in

Content Downloaded from www.html.net 75

Page 77: PHP Tutorial

// The SQL statement is executed mysql_query($strSQL);

// Close the database connection mysql_close(); ?>

<h1>The database is updated!</h1> </body> </html>

This example completes the lessons on databases. You have learned to insert, retrieve,delete and update a database with PHP. Thus, you are actually now able to make veryadvanced and dynamic web solutions, where the users can maintain and update adatabase using forms.

If you want to see a sophisticated example of what can be made with PHP anddatabases, try to join our community. It's free and takes approximately one minute tosign up. You can, among other things, maintain your own profile using the form fields.Maybe you will get ideas for your own site.

This also ends the tutorial. PHP gives you many possibilities for adding interactivity toyour web site. The only limit is your imagination - have fun!

Created By www.ebooktutorials.blogspot.in

Content Downloaded from www.html.net 76


Recommended