Sei sulla pagina 1di 77

PHP Tutorial

Created By www.ebooktutorials.blogspot.in

PHP Tutorial - Table of contents


Introduction A brief introduction to the tutorial and what you can expect to learn. Lesson 1: What is PHP A little on how PHP works, what it means that PHP is a server-side technology, and what you will learn in the next lessons. Lesson 2: Servers We look at different options to run PHP on your own computer or on a web host. Lesson 3: Your first PHP page In this lesson, you create your first very simple PHP page. Here, you can also test whether your server is set up properly to run PHP. Lesson 4: Working with time and dates Introduction to functions that can be used in work with time and dates. Lesson 5: Loops Loops can repeat parts of a script. In this lesson, we look at loops such as while and for . Lesson 6: Conditions Conditions can be used to control the execution of a PHP script. We look at if ... elseif ... else... and switch ... case . Lesson 7: Comment your scripts Comments make your PHP scripts more clear and easier to understand. Comments can be a great help if you or someone else needs to make changes in your codes at later stage. Lesson 8: Arrays In this lesson, you will learn what an array is, how it is used, and what it can do. Lesson 9: Functions In previous lessons, you have learned to use different, built-in functions. Now you will learn how to create your own functions. Lesson 10: Passing variables in a URL Learn how to pass variables and values from one page to another using the HTTP query string. Lesson 11: Passing form variables Interactive websites require input from users. One of the most common ways to get input is using forms. Lesson 12: Sessions Sessions can be used to store and retrieve information during a user's visit on your site. Lesson 13: Cookies Cookies can be used to store and retrieve information about a user from visit to visit. Lesson 14: Filesystem With the filesystem, you can access the server's filesystem. This allows you to manipulate files, folders and drives with PHP scripts.
Content Downloaded from www.html.net 1

Created By www.ebooktutorials.blogspot.in

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

Content Downloaded from www.html.net

Created By www.ebooktutorials.blogspot.in

Introduction
PHP 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 introduction to PHP. It starts from scratch but requires that you already have a good knowledge of HTML. 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 your imagination. PHP is not hard to learn, but be aware that PHP is more sophisticated and demanding to learn than HTML. Therefore, patience in the process is a virtue. This tutorial cannot show you everything. Therefore, some engagement and a will to experiment are required. If you need help along the way, we recommend that you use the forums for such support. This is where you meet the real experts who are willing and 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 HTML and CSS, PHP is not affected by which browser your visitors use, but by the type of server 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 up your 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 to unlimited possibilities for adding interactivity to your webpages.

Content Downloaded from www.html.net

Created By www.ebooktutorials.blogspot.in

Lesson 1: What is PHP


Whenever 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 understand such basics related to PHP before you start developing you own PHP pages. Such basic understanding 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 recursive acronym for PHP: Hypertext Preprocessor. PHP was originally developed by the Danish Greenlander Rasmus Lerdorf, and was subsequently developed as open source. PHP is not a proper web standard - but an open-source technology. PHP is neither real programming language - but PHP lets you use so-called scripting in your documents. To describe what a PHP page is, you could say that it is a file with the extension .php that 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 way you request an HTML page. It could be illustrated like this:

Content Downloaded from www.html.net

Created By www.ebooktutorials.blogspot.in

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

The server first reads the PHP file carefully to see if there are any tasks that need to be executed. Only when the server has done what it is supposed to do, the result is then sent to the client. It is important to understand that the client only sees the result of the server's work, not the actual instructions. This means that if you click "view source" on a PHP page, you do not see the PHP codes - only basic HTML tags. Therefore, you cannot see how a PHP page is made by using "view source". You have to learn PHP in other ways, for example, by reading this
Content Downloaded from www.html.net 5

Created By www.ebooktutorials.blogspot.in

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't need to buy a new computer. You just need to install some software on your computer that makes it function as a server. Another option is to have a website on a hosted server 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.

Content Downloaded from www.html.net

Created By www.ebooktutorials.blogspot.in

Lesson 2: Servers
PHP is a server-side technology. Therefore, you need to have a server to run PHP. But it doesn't need to cost you anything to make this upgrade and there are several options for doing so. Since you ultimately only need to choose one option, this lesson is divided into three parts. First comes a little introduction on the different options (just choose the one that suits you best). When your server is up and running, we'll pick up with Lesson 3 to make 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 PHP If you don't already have a website on hosted server you can create a free account on 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 recommend for experienced computer users, but it can obviously be done. Here are links to downloads and installtion guides: Windows Installation Guide Mac Installation Guide Linux Installation Guide

Option 3: XAMPP
XAMPP is a program that makes it easy and possible for us ordinary folks to run the PHP directly on our computer without having to install PHP on our own. Learn how to install XAMPP

Content Downloaded from www.html.net

Created By www.ebooktutorials.blogspot.in

Lesson 3: Your first PHP page


From lesson 1 and 2, you now know a little about what PHP is, and you've installed (or have access to) a server. Now we are ready to begin making our first PHP page. We keep it simple and easy, but after you have gone through this lesson, you will understand 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: Text HTML tags PHP Scripts You already know what text and HTML tags are. So let's look a little more at PHP scripts.

PHP Scripts
PHP Documentation Group has issued detailed documentation for PHP. Throughout the tutorial, there will be many links to the documentation. The goal is that you become accustomed to looking up and finding answers to your questions. PHP is so extensive that 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 in the 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 more abot saving PHP files in XAMPP. If you have a website on a host that supports PHP, you simply upload/ftp the file to your web host. The HTML code should look like this:
<html> <head> <title>My first PHP page</title> </head> <body> </body> </html>
Content Downloaded from www.html.net 8

Created By www.ebooktutorials.blogspot.in

As you probably remember from lesson 1, PHP is all about writing commands to a server. 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 the tags <?php and ?> to mark the start and end for the PHP codes that the server must execute (on most servers it will be suficient to use just <? as start tag, but <?php is the 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"):

Content Downloaded from www.html.net

Created By www.ebooktutorials.blogspot.in

The PHP codes are gone! As you may remember from lesson 1, it is only the server that can 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>. In a more technical language, one would say that we used the string function echo to write a specified string to the client where the semicolon ends the command. But do not worry! 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's only 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 the current 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:

Content Downloaded from www.html.net

10

Created By www.ebooktutorials.blogspot.in

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 that if you refresh the page in the browser, a new time is written. The server writes the current 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 PHP codes. Therefore, the example is not affected by which browser is used. Actually, all functionalities that are made with server-side technologies always work in all browsers! And again, notice the semicolon after the code line. It is a separator and very important to include - otherwise the script won't work. In the example, we used date, which is a function that returns the current date and
11

Content Downloaded from www.html.net

Created By www.ebooktutorials.blogspot.in

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:

Content Downloaded from www.html.net

12

Created By www.ebooktutorials.blogspot.in

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

date function and the different

Content Downloaded from www.html.net

13

Created By www.ebooktutorials.blogspot.in

Lesson 4: Working with time and dates


In this lesson, we will try to look at the many different options for working with time and dates in PHP. We went through some very simple examples in the previous lesson mostly to show you what PHP is. In this lesson, we will take a closer look at the date function.

Time and date functions


PHP provides a wide range of funtions in relation to time and date. In this lesson, we will look at the most important of these functions: date. With different parameters, the date function can return the current date / time in many 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, it returns: 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
<html> <head> <title>Time and date</title>
Content Downloaded from www.html.net 14

date function:

Created By www.ebooktutorials.blogspot.in </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() returns the 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 a so-called "timestamp" (UNIX timestamp) and is quite useful when you work with dates/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 thus work with the future or the past. In the example below, we set the timestamp to 0 seconds from January 1, 1970 12:00 PM, GMT. Thereby we can check what day of week 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>"; ?>
Content Downloaded from www.html.net 15

Created By www.ebooktutorials.blogspot.in

</body> </html>

Show example Unless you are a mathematical genius, it quickly becomes complicated to count the number of seconds since January 1, 1970 to a specific time in the future or past. But here you can get help from another nifty function: mktime, which does the calculations for you. The syntax for mktime is (hour, minute, second, month, day, year). The example below 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 historic 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>

date function and find out which weekday this

Show example

What can you use it for?


Content Downloaded from www.html.net 16

Created By www.ebooktutorials.blogspot.in

All this may seem a bit theoretical at this stage. After all, what on earth can you use a function like time() for? More importantly, when will you learn something you can actually use on your pages? The answer is that what you learn here are building blocks - the only limitations to what you can build are your creativity and imagination! I would venture to say that you have already learned more than you think. For example, do you think you can make a website with different background images each day of the week and that works in all browsers? 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 make seven 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 as background, 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 to make loops and repetitions in your codes. PHP is fun, don't you think?

Content Downloaded from www.html.net

17

Created By www.ebooktutorials.blogspot.in

Lesson 5: Loops
In PHP, it is possible to manage the execution of scripts with different control structures. In this lesson, we will look at loops. Loops can be used to repeat parts of a script 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 a condition 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 always start with a "$" character. It's easy to forget this at first, but it's absolutely necessary to remember or else the script doesn't work. Apart from that, the example is almost self-explanatory. First the variable $x is set to be equal to 1. Then the loop asks the server to repeat the text while $x is less or equal to 50. In each loop, the variable $x will be increased by 1.

"for" loops
Content Downloaded from www.html.net 18

Created By www.ebooktutorials.blogspot.in

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'. If that 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 will continue as long as $x is below or equals 50. Also note how the value $x is used as part of 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 heading at level $x (h1, h2, h3, etc.) until $x is equal to six.
Content Downloaded from www.html.net 19

Created By www.ebooktutorials.blogspot.in

Loops within loops


In principle, there are no limitations on how loops can be used. For instance, you can easily 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 16 million colors! In order not to make the page slow, we have drastically reduced the number by putting the 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 value between 0 and 255. Any combination of the three colors creates a color on the form rgb(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 understand the principle in a loop, you can proceed to the next lesson, where we look at conditions.

Content Downloaded from www.html.net

20

Created By www.ebooktutorials.blogspot.in

Lesson 6: Conditions
Conditions 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 after January 1, 2012 or that a variable is greater than 7.

If...
The first type of condition we will look at is
if (condition) { statement }

if, which has the following syntax:

Again, the syntax is very close to ordinary English: If a condition is met, then execute something . 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 following form:
if (condition) { statement } else { statement }

else , which may be presented in the

Again, the syntax is very close to ordinary English: if a condition is met execute something or else execute something else.
Content Downloaded from www.html.net 21

Created By www.ebooktutorials.blogspot.in

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 when it'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 expand the above example to include all the spring months:
<html> <head> <title>Conditions</title> </head> <body> <?php
Content Downloaded from www.html.net 22

Created By www.ebooktutorials.blogspot.in 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 covered by 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>
Content Downloaded from www.html.net 23

Created By www.ebooktutorials.blogspot.in

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

switch ... case


Another way of writing conditions is to use the
switch (expression) { case 1: statement break; case 2: statement break; default: statement break; }

switch method:

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 an example. As you may remember from lesson 4, the function date("w") returns the current weekday. This can be used in an example where we write the name of the day (instead of a number):
<html> <head> <title>Conditions</title> </head> <body> <?php switch(date("w")) { case 1: echo "Now break; case 2: echo "Now break; case 3: echo "Now break; case 4: echo "Now break; case 5: echo "Now break; case 6: echo "Now it's Monday"; it's Tuesday"; it's Wednesday"; it's Thursday"; it's Friday"; it's Saturday";
24

Content Downloaded from www.html.net

Created By www.ebooktutorials.blogspot.in 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 use in a given situation depends on which method you find easiest and most logical. Making your 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 explain how they work. Good comments can be crucial if you or somebody else has to make changes in your codes at a later stage.

Content Downloaded from www.html.net

25

Created By www.ebooktutorials.blogspot.in

Lesson 7: Comment your scripts


As you may have noticed, PHP scripts can easily look confusing. In this lesson, we cover why 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 use a highly formal language that may not clearly reflect your thoughts when making the script. Therefore, it can be difficult for others (or yourself) to understand how the script is structured, and thus hard to identify and correct errors in the script. Comments can be used to write short explanatory text in the script. The server completely ignores the comments, and the comments do not affect the actual functionality of the script. In the business world, it is often a requirement that scripts and programming are commented, otherwise it would be too risky for a company to take over a system in which 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 . "
Content Downloaded from www.html.net 26

Created By www.ebooktutorials.blogspot.in </span>";

// Closes the loops } } } ?>

For the sake of the example, we have included many extra comments, so it should be clear that you are far better off debugging a script with comments than without. Therefore, remember to comment your scripts!

Content Downloaded from www.html.net

27

Created By www.ebooktutorials.blogspot.in

Lesson 8: Arrays
In 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 identification number. Sound confusing? It's actually not that complicated. Imagine a list of words separated by commas. It is called a comma-separated list, and it could, 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 unique identification number like this:

What you see is an array. We can, for example, name the array "fruits". The idea is that we can access the array with a number and get a value back, like this: fruits(0) fruits(1) fruits(2) fruits(3) fruits(4) = = = = = apples pears bananas oranges 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 real array. First, we set a variable equal to the list of fruits:
<?php $fruitlist = "apples, pears, bananas, oranges, lemons";
Content Downloaded from www.html.net 28

Created By www.ebooktutorials.blogspot.in ?>

Next, we use the function


<?php

explode to split the list at each comma:

$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 split 2. 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 a delimiter. 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 echo echo echo echo echo echo ?> </body> </html> "<ul>"; "<li>" . "<li>" . "<li>" . "<li>" . "<li>" . "</ul>"; $arrFruits[0] $arrFruits[1] $arrFruits[2] $arrFruits[3] $arrFruits[4] . . . . . "</li>"; "</li>"; "</li>"; "</li>"; "</li>";

Show example This example is very simple, and it might be a bit difficult to see the advantage of using
Content Downloaded from www.html.net 29

Created By www.ebooktutorials.blogspot.in

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

Loop through an array


Back in lesson 5 you learned about loops. Now we will look at how you can loop through an array. When you know how many elements an array contains, it is not a problem defining the loop. 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 to call 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 element more - which will get the identification number 5. Do you see the problem? Then we need to change the loop, so it runs from 0 to 5, or else not all of the elements will be included. Wouldn't it be nice if we automatically could find out how many elements an array
Content Downloaded from www.html.net 30

Created By www.ebooktutorials.blogspot.in

contains? That's exactly what we can do with the function foreach. Now we can make a loop that 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. array instead of the function explode to create an

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

Content Downloaded from www.html.net

31

Created By www.ebooktutorials.blogspot.in

Lesson 9: Functions
In previous lessons you have learned to use functions like date() and array(). In this 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, you have a wide range of data you have processed or if you have calculations or routines that 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. It could 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 or anything else. You can also create functions that are called by many different parameters. 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 more parameters. In the next example, we'll create a function that is called with three numbers and then returns the value of the three numbers added together:
<html> <head> <title>Functions</title>
Content Downloaded from www.html.net 32

Created By www.ebooktutorials.blogspot.in </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 function can 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 date and 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>
Content Downloaded from www.html.net 33

Created By www.ebooktutorials.blogspot.in

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. The method has no effect on the code itself. The function above works on all web servers regardless of language. This means that you 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 little about how functions work.

Content Downloaded from www.html.net

34

Created By www.ebooktutorials.blogspot.in

Lesson 10: Passing variables in a URL


When 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 example above, 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 using the 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>";
Content Downloaded from www.html.net 35

Created By www.ebooktutorials.blogspot.in

?> </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 own name 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 can get 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 the next lesson, we'll look at another method: forms.

Content Downloaded from www.html.net

36

Created By www.ebooktutorials.blogspot.in

Lesson 11: Passing variables with forms


Interactive websites require input from users. One of the most common ways to get input 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 and method. action Is used to enter the URL where the form is submitted. It would be the PHP file that you want to handle the input. method Can either have the value "post" or "get", which are two different methods to pass data. 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 block of data through standard input service (STDIN). In the last lesson, we looked at how data is retrieved through the URL using $_GET. In this lesson, we look at how 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 need not 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:


Content Downloaded from www.html.net 37

Created By www.ebooktutorials.blogspot.in

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


Content Downloaded from www.html.net 38

Created By www.ebooktutorials.blogspot.in

In the next example, we will try to use user input to create conditions. First, we need a form:
<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 background color according to what the user's favorite color is. We can do this by creating a condition (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:
Content Downloaded from www.html.net 39

Created By www.ebooktutorials.blogspot.in $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 the form. This is done by using default to specify what should happen if none of the above conditions are met. But what if the user does not fill out his name? Then it only says "Hello" in the title. We will 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>

Content Downloaded from www.html.net

40

Created By www.ebooktutorials.blogspot.in

Show example. In the example above, we use a condition to validate the information from the user. In this case, it might not be so important if the user did not write his name. But as you code more and more advanced stuff, it's vital that you take into account that the user may 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 form using 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 = "name@mydomain.com"; // Get user inputs $strSubject = $_POST["subject"]; $strMessage = $_POST["message"]; mail($strEmail,$strSubject,$strMessage); echo "Mail Sent."; ?> </body> </html>
Content Downloaded from www.html.net 41

Created By www.ebooktutorials.blogspot.in

Please note that the example will only work if you have access to a mail server. By default, this is not the case in XAMPP and most free hosts. Also, some hosts may require that you include a from header, which is done with an extra parameter:
mail("you@yourdomain.com", "Test", "This is a test mail", "From: me@mydomain.com");

Content Downloaded from www.html.net

42

Created By www.ebooktutorials.blogspot.in

Lesson 12: Sessions


When you visit a website, you do a number of different things. You click from one page to another. Perhaps you also fill out a form or purchase a product. As a web developer, such information is of great importance to developing successful web solutions. Suppose, for example, that you want to make a site where some pages are protected with login and password. To make this protection effective, the password-protected pages should have access to information on whether the user has logged in at an earlier time. 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 and retrieve information during a user's visit to your site.

Session
PHP session allows you to manage information about a user's session. You can 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 but focus on the case where a session starts by a value being stored. A session ends/dies if the user hasn't requested any pages within in a certain timeframe (by the standard 20 minutes). 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 the same time. Information on what each of them have in their shopping cart would best be stored in a session. In order to identify the individual users, the server uses a unique user ID that is stored in a cookie. A cookie is a small text file stored on the user's computer (more about cookies in lesson 13). Therefore, sessions often require support of 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 that I 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 PHP script:
<?php session_start(); $_SESSION["StartTime"] = date("r");
Content Downloaded from www.html.net 43

Created By www.ebooktutorials.blogspot.in ?>

Thereby, a session was started. As described above, each session is given an ID by the server. 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 you have 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. But if 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 of the 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>
Content Downloaded from www.html.net 44

Created By www.ebooktutorials.blogspot.in <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 been entered. If that is the case, we set a session that says that this user is logged in with the 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 is not 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"); } ?>
Content Downloaded from www.html.net 45

Created By www.ebooktutorials.blogspot.in <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 still working in the same area but will take a closer look at cookies.

Content Downloaded from www.html.net

46

Created By www.ebooktutorials.blogspot.in

Lesson 13: Cookies


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

What is a cookie?
A cookie is a small text file in which a website can store different information. Cookies are saved on the user's hard drive and not on the server. Most cookies expire (delete themselves) after a predetermined time period, which can range from one minute to several years. But the user can also identify and delete any cookies 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. But then, why not just say no to all cookies? It is possible. But many websites would not work as intended without cookies, since cookies in many contexts are used to improve the 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 example, we will create a cookie and set the value. setcookie. In the first

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 by adding another parameter setting the expiry time:
<?php // Setting the cookie setcookie("Name", "C. Wing, time()+3600); setcookie("Interests", "plane spotting", time()+3600); ?>
Content Downloaded from www.html.net 47

Created By www.ebooktutorials.blogspot.in

"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. This information can, for example, be useful to target the website specifically for the individual 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 the information 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 it was created. But by using the parameters domain and path , you can put further restrictions 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." The cookie expires after one year (60 seconds * 60 minutes * 24 hours * 365 days) and can be read only by sites located in the directory "/tutorials/php/" on the (sub-)domain "www.html.net".
Content Downloaded from www.html.net 48

Created By www.ebooktutorials.blogspot.in

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 system you use, your cookies may be saved in different places. Once you find them, they will probably look like this:

As you can see, a cookie is a normal text file that can be open with Notepad, for example. The contents of the cookie we have just created will probably look something like 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 full control over cookies on his/her computer. In this lesson, we have looked at what cookies can do but not what they can be used for. It's a common concern that some sites use cookies for inappropriate activities. But in most cases, cookies are used to make sites more user-friendly or relevant for the individual users. If you choose to use cookies on your site, it might be a good idea to tell your users that your site uses cookies. This can, for example, be communicated in a privacy policy or registration process.
Content Downloaded from www.html.net 49

Created By www.ebooktutorials.blogspot.in

Lesson 14: Filesystem


With PHP, you can access the server's filesystem. This allows you to manipulate folders and 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 a specified 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 to give you a quick overview. In the next lessons, we will look more closely at the different possibilities. We will not go through all the different possibilities. Again, see the documentation for a complete listing. filemtime Returns the time for which the contents of a file was last edited (as UNIX timestamp - see lesson 4)). fileatime Returns the time when a file was last accessed / opened (as a UNIX timestamp see lesson 4)). filesize Returns 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 the different possibilities - only show an example. Again, see the documentation for more
Content Downloaded from www.html.net 50

Created By www.ebooktutorials.blogspot.in

information. opendir Opens a specified folder. readdir Returns the filename of the next file in the open folder (cf. closedir Closes a specified folder.

opendir)

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 to write 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.

Content Downloaded from www.html.net

51

Created By www.ebooktutorials.blogspot.in

Lesson 15: Reading from a text file


In the previous lesson, we learned how to use PHP to access the server's filesystem. In this 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 quite as 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)

filename Name of the file to be opened. mode Mode 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 will learn 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 the Programmes and Funds of the United Nations and their domains. You can either download 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 until the first line break (but not including the line break).
<html> <head> <title>Reading from text files</title>
Content Downloaded from www.html.net 52

Created By www.ebooktutorials.blogspot.in </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-offile) 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 with fread. If you work with very large text files with thousands of the function fread function uses more resources than the fgets lines, be aware that the function. For smaller files, it makes very little difference.

Example 3: A simple link directory


Content Downloaded from www.html.net 53

Created By www.ebooktutorials.blogspot.in

As mentioned at the beginning of this lesson, text files can be excellent for data storage. This is illustrated in the next example where we create a simple link directory from the contents of the text file unitednations.txt. The file is systematically written with the name of the program, then a comma, and then the domain. As you can probably imagine, more information could easily be stored in this comma-separated data file. To get the information in each line, we use an array. See Lesson 8 for more information on 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 hundreds of 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.

Content Downloaded from www.html.net

54

Created By www.ebooktutorials.blogspot.in

Lesson 16: Writing to a text file


In the previous lesson, we learned to read from a text file. In this lesson, we will learn to write to a text file. The two methods are very similar, but there is one very important difference: You must have write permissions to the file. This means that the file will have to be located in a folder where you have the necessary permissions. If you work locally on your own computer, you can set the permissions yourself: rightclick on the folder and choose "Properties". With most web hosts, you will normally have 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 to set permissions yourself. Usually you can simply right-click on a folder in your FTP client and choose "properties" or "permissions" or something similar. The screendumps below shows 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 the PHP file.

Open the text file for writing


In the same way as when reading from a text file, the fopen function is used for writing, 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 at the 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
Content Downloaded from www.html.net 55

Created By www.ebooktutorials.blogspot.in

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
<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>

fwrite, like this:

Show example Since we opened the file for writing , the line is added at the top, and thus overwrites the existing line. If we instead open the file appending, the line is added at the bottom of 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, like this:
Content Downloaded from www.html.net 56

Created By www.ebooktutorials.blogspot.in

<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

Content Downloaded from www.html.net

57

Created By www.ebooktutorials.blogspot.in

Lesson 17: Databases


A database is a collection of information / data that is organized so that it can easily be retrieved, administrated and updated. Databases thereby enable the opportunity to create dynamic websites with large amounts of information. For example, all data on members 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 with spreadsheets, or maybe have used databases before, tables will look familiar to you with columns and rows:

There are many different databases: MySQL, MS Access, MS SQL Server, Oracle SQL Server and many others. In this tutorial, we will use the MySQL database. MySQL is the natural 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 next lessons: If you have a hosted website with PHP, MySQL is probably already installed on the server. Read more at your web host's support pages. If you have installed PHP on your computer yourself and have the courage to install MySQL as well, it can be downloaded in a free version (MySQL Community Edition) at the MySQL's website. If you use XAMPP (see lesson 2), MySQL is already installed and ready to use on your computer. Just make sure MySQL is running in the Control Panel:

Content Downloaded from www.html.net

58

Created By www.ebooktutorials.blogspot.in

In the rest of this lesson, we will look more closely at how you connect to your database server, before we learn to create databases and retrieve and update data in the 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 then type in the username and password . If you have your own website, you should read about location of your MySQL server on your host's support pages. Username and password will often be the same as those you use 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());

Content Downloaded from www.html.net

59

Created By www.ebooktutorials.blogspot.in

In the examples are added or die(mysql_error()) which, in brief, interrupts the script and writes the error if the connection fails. Now we have made a connection to a MySQL server, and can now start creating databases and retrieve and insert data. This is exactly what we will look at in the next lessons. By the way, keep in mind that it is good practice to close the database connection again when you're finished retrieving or updating data. This is done with the function mysql_close.

Content Downloaded from www.html.net

60

Created By www.ebooktutorials.blogspot.in

Lesson 18: Create databases and tables


In the previous lesson we looked at how to create a connection to a database server. Next step is to create 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's made with the more user-friendly tool PhpMyAdmin, which is standard on most web hosts and in XAMPP. If you have a hosted website with PHP and MySQL, a database has probably been created for you already and you can just skip this part of the lesson and start creating tables. Again, you should consult 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 are written in the language Structured Query Language (SQL). SQL is the most widely used language for database queries - not only for MySQL databases - and is very logical and easy to learn. In this lesson and the next, you will learn the most important SQL queries. When creating a database, the SQL query syntax:
CREATE DATABASE database name

CREATE DATABASE is used with the following

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. CREATE TABLE with the following syntax: When creating tables, we use the SQL query
CREATE TABLE ( column1_name column2_name column3_name ... ) table name DATA_TYPE, DATA_TYPE, 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 used data types are:
INT For numbers without decimals DECIMAL
Content Downloaded from www.html.net 61

Created By www.ebooktutorials.blogspot.in

For numbers with decimals CHAR Short text up to 255 characters TEXT For plain text up to 65,535 characters LONGTEXT For long passages of text up to 4,294,967,295 characters Date For dates in the format YYYY-MM-DD Time For time in the format HH:MM:SS DATETIME 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 then add 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 key uniquely identifies each record (/row) in the table, which becomes very useful later when we update the 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 to use phpMyAdmin (or any other MySQL administration tool), which is standard on most web hosts and XAMPP. 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 is http://localhost/phpmyadmin/. When you are logged on, simply type a name for the database and press the button "Create":

Content Downloaded from www.html.net

62

Created By www.ebooktutorials.blogspot.in

At some hosts, it's possible the have already created a database, and you may not have the rights to create 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 table and 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).
63

Content Downloaded from www.html.net

Created By www.ebooktutorials.blogspot.in

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

Content Downloaded from www.html.net

64

Created By www.ebooktutorials.blogspot.in

Lesson 19: Insert data into a database


In 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 databases and 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 commaseparated list. But of course, it is also possible to specify just one column and one value. The columns that 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 the database. It could be the person Gus Goose with the phone number 99887766 and 1964-04-20 as the date 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 be an advantage to write the SQL statement in a slightly different way:
strSQL = "INSERT INTO people("; strSQL strSQL strSQL strSQL = = = = strSQL strSQL strSQL strSQL . . . . "FirstName, "; "LastName, " "Phone, "; "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 putting those parts together in the variable $strSQL. In practice, it makes no difference which method you choose, but once you start working with larger tables, 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>

Content Downloaded from www.html.net

65

Created By www.ebooktutorials.blogspot.in
<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 a simple 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 by requesting 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
Content Downloaded from www.html.net 66

Created By www.ebooktutorials.blogspot.in

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

Wrong data types


It is important that there is consistency between the type of data and column. Each column can be set to 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 to set the data types as precisely as possible. Below is the most common data types listed:
Data Type Text or combinations of text and numbers. Can also be used for numbers CHAR that are not used in calculations (e.g., phone numbers). TEXT Longer pieces of text, or combinations of text and numbers. INT Numerical data for mathematical calculations. DATE Dates in the format YYYY-MM-DD TIME Time in the format hh:mm:ss DATETIME Date and time in the format YYYY-MM-DD hh:mm:ss Setting Size Up to 255 characters - or the length defined in the "Length" Up to 65,535 characters. 4 bytes. 3 bytes. 3 bytes. 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 characters that need to be quoted in database queries. This can be done with the function
<?php $strText = "Is your name O'Reilly?"; $strText = addslashes($strText); ?>

addslashes this way:

All single quotes ('), double quotes (") and backslashs (\) will then get an extra backslash before the character. This would only be to get the data into the database, the extra \ will not be inserted. Please note that PHP runs addslashes on all $_GET, $_POST, and $_COOKIE data by default. Therefore do not 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 more people in your database (as shown in the example above with Gus Goose).

Content Downloaded from www.html.net

67

Created By www.ebooktutorials.blogspot.in

Lesson 20: Get data from database


Now 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 and understood this lesson, you will realize why database-driven web solutions are so powerful, 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 the database. 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 are used 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 is important 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 are stored in a so-called recordset. A recordset can be described as a kind of table in the server's memory, containing rows of data (records), and each record is subdivided into individual fields (or columns). A recordset can be compared to a table where each record could be compared to a row in 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:
68

Content Downloaded from www.html.net

Created By www.ebooktutorials.blogspot.in

<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" by typing $row['FirstName']. Similarly, we can get the content of the column "Phone" by writing $row['Phone'], for example. The order of the recordset is exactly the same as in the table in the database. But in the next 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 the syntax 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
Content Downloaded from www.html.net 69

Created By www.ebooktutorials.blogspot.in

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 name or phone number.

Retrieve selected data


Content Downloaded from www.html.net 70

Created By www.ebooktutorials.blogspot.in

Until now, our SQL statement retrieves all rows from the table. But often you need to set criteria in the SQL query for the data to be retrieved, for instance, if we only want the 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: AND OR NOT 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. We will make a list of the names from the database where each name is a link to further details 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
Content Downloaded from www.html.net 71

Created By www.ebooktutorials.blogspot.in

()); // 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();
Content Downloaded from www.html.net 72

Created By www.ebooktutorials.blogspot.in ?>

</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 with PHP and databases. Imagine that the database had contained 10,000 products with detailed descriptions. By making a few changes in the above files, you could easily create a product catalogue with 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 same again.

Content Downloaded from www.html.net

73

Created By www.ebooktutorials.blogspot.in

Lesson 21: Delete data from database


In the two previous lessons, you have learned to insert and retrieve data from a database. In this lesson, we'll look at how to delete records in the database, which is considerably 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. In our database, it is the column named id. Using this unique identifier ensures that you only delete one record. In the next example, we delete the record where id has the value 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. Once you have deleted a record, it is gone and cannot be restored.

Content Downloaded from www.html.net

74

Created By www.ebooktutorials.blogspot.in

Lesson 22: Update data in a database


In previous lessons, you have learned to insert, retrieve and delete data from a database. In this lesson, we will look at how to update a database, i.e., edit the values of 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 quite easy to understand how the above syntax is used in practice. But we will of course look at an example.

Example: Update cells in the table "people"


The code below updates Donald Duck's first name to D. and changes the phone number to 44444444. The other information (last name and birthdate) are not changed. You can try to change the other people's data by writing your own SQL statements.
<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";
Content Downloaded from www.html.net 75

Created By www.ebooktutorials.blogspot.in // 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 very advanced and dynamic web solutions, where the users can maintain and update a database using forms. If you want to see a sophisticated example of what can be made with PHP and databases, try to join our community. It's free and takes approximately one minute to sign 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 to your web site. The only limit is your imagination - have fun!

Content Downloaded from www.html.net

76

Potrebbero piacerti anche