Monday, 01 October 2007 13:38

Vamp the Linux LAMP through PHP part 2

By

Last time we showed how anyone can get started writing, or reading, web pages coded with PHP, the “P” in “LAMP” (the rest being Linux, Apache and MySQL.) We received kind reader feedback that this was the friendliest and simplest PHP introduction they’d seen. What’s best of all is PHP is for everyone; even if you don’t run Linux, you can use PHP on the web space provided by your ISP.

Now to take it to the next level. So far, we’ve showed how to switch from HTML into PHP mode, how to perform basic mathematics and how to alter the flow of the program via conditional and looping constructs. These are foundational concepts but by themselves are not ultimately of great value: what’s missing is user input.

Here’s how to prompt the user for information through standard HTML forms, and then have PHP act on these. Before we can get to that, though, it’s important to understand arrays.

Arrays
An array is an indexed collection of variables which share the same name. This means instead of having two variables called, say, $a and $b, you might have two variables called $a[0] and $a[1]. These two variables are separate; if you change the value of one the other is not affected. You can retrieve the value later and it will still be as expected no matter how much else you have done to other elements in the array.

There are two main benefits of using an array. The first is that you can use a loop to perform an operation on a whole bunch of data items with a very small amount of program code. This works by using another variable to act as an index into the array; each time through the loop increase the value of this variable. To act on a large set of individually named variables would be a more complex piece of program code, and would not easily lend itself to differing numbers of variables.

Additionally – and this is something particularly nice about PHP – the index into an array doesn’t have to be an integer number; it could be a text string. This means it is dead simple to (for example) hold a count of the number of times different words are used in a sequence of text; all you need to do is have an array which is indexed by the actual word itself, and which simply holds an increasing count. Most other languages don’t have this flexibility and only allow arrays to be indexed by an integer.

Here’s what some real code looks like which implements these concepts, including how to actually define an array:

<?php
  $arr = array(10, 20, 30, 40);
  $counter = 0;
  while ($counter < 4) {
    $counter++;
    echo “Position “ . $counter . “ holds value ” . $arr[$counter] . “<br />”;
}
?>


The first line of code makes an array with four elements (namely, the numbers 10, 20, 30 and 40). The while loop then displays each of these in turn, one to a line. To make the output more readable, we also add a bit of text (“Position “, “ holds value “, and a HTML line break code, “<br />”.)


Note that the array is indexed by a variable called $counter which begins at 0. That’s because, unless you specify otherwise, PHP will make arrays starting at index 0. This means we have to stop the loop before $counter is equal to the number 4 because the fourth element is actually at index 3.

It doesn’t have to be that way. We can tell PHP to use index numbers of our choice with syntax like this:

$arr = array(1 => 10, 2 => 20, 3 => 30, 4 => 40);


In this case, $arr[1] holds the value 10 and $arr[4] holds the value 40. Actually, the index into the array doesn’t have to be consecutive. And nor does it have to be numbers. You could also declare the array like this:

$arr = array(“cat” => 10, “dog” => 20, “frog” => 30, “fish” => 40);


This time, $arr[“cat”] has the value 10 and $arr[“fish”] has the value 40. You might think this makes it harder to use a loop like the one above with a numeric counter if your array is indexed using string keys but that’s not actually the case. When we specify values like this, PHP actually considers them “keys”. The array is still indexed and we can still access any individual item by an index number but we also have a way of getting values using distinct keys which are special for each entry.

We could go on for a long time: PHP is one of the most flexible and versatile programming languages which partially owes to its popularity (the fact that it is free and open source helps a lot too!) and offers no end of options to declaring and using arrays. To illustrate, here’s some more array code. All these lines are in sequence and are acting on the same array:

$arr = array(“cat” => 10, 2 => 20, “frog” => 30.3, 55 => 40);
$arr[] = “Hello”;
$arr[“more”] = array(1, 2, 3, “a”, “b”, “c”);

The first line declares an array with four elements. The keys are not strictly numeric, nor are they strictly text strings. The key is “cat” for the first element, 2 for the second, “frog” for the third, and 55 for the fourth. You really can make any key you like, whether it is a number or a string and whether it is sequential or not – just so long as it is unique over the entire array.

You’ll also see that $arr[“frog”] holds the value 30.3 this time just to illustrate that the array doesn’t care if all its values are the same type either. The one array can hold numeric values, string values or any other data type at any given position. It doesn’t matter what type of data is stored elsewhere.

The second line adds another element to the array, with the value “Hello”. The catch this time is that there is no key (but there is an index value; there always will be.)

Finally, the third line adds another element to the array and gives it the key “more”. However, the value is not just a number or a string but another array, with six elements defined. You can print out the items in the array by using two sets of square brackets – so this line:

$echo $arr[“more”][0]


- will show the value 1, being the first item (the 0th index) in the array stored in $arr[“more”].

It might be worth thinking about all that for a moment. Arrays in PHP are hugely powerful owing to their remarkable flexibility.


Handling web forms


This leads us to actually making your web pages more useful. In standard HTML you can make web forms which prompt the user for input. PHP is able to act on the input using a special array which is defined for you.


Here’s a sample form. You should create it using any text editor and save it to your web space.


<html>
<head>
  <title>Sample form</title>
</head>
<body>
  <h1>Please enter your username and password to continue:</h1>
  <form method=”post” action=”login.php”>
    Username: <input type=”text” name=”tUsername” /><br />
    Password: <input type=”password” name=”tPassword:” /><br />
    <input type=”submit” />
  </form>
</body>
</html>


This form displays two fields, which are named tUsername and tPassword. Both hold text strings. The form’s action is to move to page login.php when the user clicks the submit button. So, if this page were displayed in a web browser, the user would be able to enter a username and password and click submit. The web browser would then call the next page, login.php, and pass it the data which the user entered. It’s up to login.php to read these values and use them in some way and here’s where the magic happens.

When a PHP page is called as the target of a form, a special array is created called $_REQUEST. You can use the values in this array just as if it were an array you made yourself. Here’s a sample login.php page which shows back what the user typed in:

<html>
<head>
  <title>Form response</title>
</head>
<body>
  <h1>You typed:</h1>
<?php
  echo “Username: “ . $_REQUEST[“tUsername”] . “<br />”;
  echo “Password: “ . $_REQUEST[“tPassword”] . “<br />”;
?>
</body>
</html>

This is a perfectly legal and valid PHP page. We don’t declare the $_REQUEST array anywhere; it is provided automatically by PHP. We don’t have to tell it that array elements exist with keys “tUsername” or “tPassword”; PHP does that by itself – and you can see right away that those keys are the names given to the form fields in the HTML page. If we had more form elements – be they checkboxes, radio buttons, selection lists, drop-down lists or anything else, these would also be automatically defined as elements in the array.

If you ran this example and gave a username of “tomthumb” and a password “jemima” then $_REQUEST[“tUsername”] would have the value “tomthumb” and $_REQUEST[“tPassword”] would have the value “jemima”. It really is that simple.

And that’s how to handle HTML forms in PHP. This gives you loads of power to make dynamic web pages which respond intelligently to what the user asks, or enters as responses to questions your web site asks.

With this knowledge, there’s nothing stopping you making your own PHP calculator, say. Or an expert system which asks the user questions to diagnose a problem and then gives its considered opinion. You can chain multiple pages of forms together to make a series of questions. In fact, as the PHP echo command lets your output your own HTML tags, you could dynamically generate entire HTML pages and forms on the fly. Mix this with conditional statements like if ... else and you can have your PHP pages produce different output – and different forms with different target pages when submitted – based on the flow of data.

From here the best thing I can do is to advocate further reading in three areas.

  • Firstly, learn more about HTML forms.
  • Secondly, learn more about PHP.
  • Thirdly, even when you can respond to user input there’s still something your pages don’t do and that’s save data to a back-end database, or display pre-stored data out of a database. This is where MySQL comes in, the “M” in LAMP. We’ll cover that with another easy-to-follow tutorial in time, but for the moment you can find other online guides to working with MySQL in PHP.

    Good luck!

  • BACK TO HOME PAGE

    NEW OFFER - ITWIRE LAUNCHES PROMOTIONAL NEWS & CONTENT

    Recently iTWire remodelled and relaunched how we approach "Sponsored Content" and this is now referred to as "Promotional News and Content”.

    This repositioning of our promotional stories has come about due to customer focus groups and their feedback from PR firms, bloggers and advertising firms.

    Your Promotional story will be prominently displayed on the Home Page.

    We will also provide you with a second post that will be displayed on every page on the right hand side for at least 6 weeks and also it will appear for 4 weeks in the newsletter every day that goes to 75,000 readers twice daily.

    POST YOUR NEWS ON ITWIRE NOW!

    INVITE DENODO EXECUTIVE VIRTUAL ROUNDTABLE 9/7/20 1:30 PM AEST

    CLOUD ADOPTION AND CHALLENGES

    Denodo, the leader in data virtualisation, has announced a debate-style three-part Experts Roundtable Series, with the first event to be hosted in the APAC region.

    The round table will feature high-level executives and thought leaders from some of the region’s most influential organisations.

    They will debate the latest trends in cloud adoption and technologies altering the data management industry.

    The debate will centre on the recently-published Denodo 2020 Global Cloud Survey.

    To discover more and register for the event, please click the button below.

    REGISTER HERE!

    BACK TO HOME PAGE
    David M Williams

    David has been computing since 1984 where he instantly gravitated to the family Commodore 64. He completed a Bachelor of Computer Science degree from 1990 to 1992, commencing full-time employment as a systems analyst at the end of that year. David subsequently worked as a UNIX Systems Manager, Asia-Pacific technical specialist for an international software company, Business Analyst, IT Manager, and other roles. David has been the Chief Information Officer for national public companies since 2007, delivering IT knowledge and business acumen, seeking to transform the industries within which he works. David is also involved in the user group community, the Australian Computer Society technical advisory boards, and education.

    BACK TO HOME PAGE

    Webinars & Events

    VENDOR NEWS

    REVIEWS

    Comments