PHP Syntax Weird and Wonderful PHP Help

You’ve got a couple of PHP programs running, and have a handle on how PHP can interact with an HTML form. Still, although you’re a little more comfort-able with how PHP as a whole interacts with web servers and web browsers, what’s actually going on in those PHP scripts? It’s time to dig a good deal deeper and start to c. =aersta»: what’s going on in the code you’re writing. In this chapter, you’re going to get comfortable with a lot of the PHP syntax. That means learning what special words-usually called !,evwo(os-you type into your programs and what each one of those keywords instructs PHP to do.

Fortunately, this learning doesn’t mean you can’t still build interesting programs that run in a web browser. In fact. because almost everything that’s done with PHP involves web pages, all of your scripts in this chapter will accept information from a web form and work with that information. So, you’re not just learning PHP; you’re learning to write web applications.

Get Information from a Web Form

In you used the following line to get the value of a variable called “name” from the sayHel1o.htrni web form:

echo $_REOUEST[‘name’];

You might remember that $_REQUESTis a special PHP variable that lets you get information from a web request (page 53). You used it to get one particular piece of information-the user’s name-but it can do a lot more

Accessing Request Parameters Directly

In fact, to see just how handy $_ REQUESTreally is, go ahead and start your text editor. Enter the code that follows, which lets your user enter in his name and several other important bits of contact information, like his Twitter handle, Facebook page URL, and email address.

<html>
<head>
<link href= •…/css/phpr.v.l.css•.rel=”stylesheet” type=”text/css” />
</head>
<body>
<div id=”header”><hl>PHP & MySOL: The Missing Manual</hl></div>
<div id=”example”>Example -l</div>
<div id=”content”>
<hl>Join the Missing Manual (Digital) Social Club</hl>
<p>Please enter your online connections.below:</p>
<form action=”scripts/getFormlnfo.php” method=”POST”>
<fieldset>
<label for=”first_name”>First Name:</label>
<input type=”text” name=”first_name” size=”20″ /><br />
<label for=”last_name”>Last Name:</label>
<input type=”text” name=”last_name” size=”20″ /><br />
<label for= •.email •.>E-Mail Address:</label>
<input type=”text” name=”email” size=”SO” /><br />
<label for=”facebook_url”>Facebook URL:</label>
<input type=”text” name=”facebook_url” size=”So” /><br />
<label for=”twitter_handle”>Twitter Handle:</label>
<input type=”text” name=”twitter_handle” size=”20″ /><br />
</fieldset>
<br />
<field set c~ass;”center”>
<input type;”submit” value;”Join the Club” I>
<input type;”reset” value;”Clear and Restart” I>
</fieldset>
</form>
</div>
<div id;”footer”></div>
</body>
</html>

HTML Should Be Semantically Meaningful

You might have noticed some pretty big changes in this HTML from the simple form in Chapter 2. In that chapter, the form used < p> tags to break up the form labels and input boxes, and manually formatted the form labels with <i> tags. That got the job done, but it’S not a good use of HTML.

Whenever you’re writing HTML. you’re actually structuring your page. 50 a form tag doesn’t really do anything visually; it jusllets a browser know, “Hey, here’s a form.” When you use tags like c i >, though, you’re not describing structure; you’re telling the browser how something should ‘0 . That’s really not what HTMLis for, though-it’s a job for C55.

In this form, however, all the formatting has been pulled out. Instead, all the labels are identified with the <label> element and a for attribute. That identifies the labels 1\ labels-regardless of how those labels end up looking-and also connects each label with the specific input field to which it matches. There’s also a <fieldset> element that surrounds the different blocks within the form: one for the labels and text fields, and a second for the form buttons. This also provides in other words, it provides information that has meaning .

By making the HTMLmean something, a browser (and other HTMLauthors) knows what thing’s actually sr: in your form: labels are meant for …well. ..labeling things. Fields are grouped together with <fieldset>. And italic and boldface formatting
are left to your C55,as they should be. What’s really cool here is that now your C55 can do an even job of styling your form. Because you’ve eliminated formatting in the HTMLitself, you can style all your form labels the same way-perhaps by bolding them, right-aligning them, and adding a right margin of 5 pixels. The same is true of your sets of fields; you might put a border around related1ields, which is exactly what’s gOing on in the C55 applied to this form. In fact, to see how the C55affects these HTMLelements, check out Figure H In truth, if you’re new to making your pages semantically meaningful, it might take time to get used to using HTMLjust for structure and keeping all your style in C55. But, stick with it; your pages will look better, and anyone who has to update your pages down the line will thank you.

PHP & MySQL

PHP & MySQL

By examining this code, you can already see what’s going on here. In addition to grabbing the value of the “first_name” and “last_name” fields-similar to getting the value of the “name” field in 5(“”. Hf”It..’W{~f)ilc; (page 53)-the code uses $_ REQUEST  to pull in the values the user entered into the other form fields

Go back to your”tm! web form, enter your information, and then submit the form. You should see the result of running, and your
browser should show you something similar to Figure 3-2.

PHP & MySQL

PHP & MySQL

In fact, the following line is the way you’ll use the $_ REQUEST variable in most of your Pl+P’proqrarns:

echo $_REOUEST[‘FORM_INPUT_FIELD_NAME’];

Create Your Own Variables

Of course, there might be times when you don’t want to just display out the value of a field. Think back to your first program, ::ayiiei:0.pho (the version from page 48 that didn’t run on the web). In that program, you created your own variable:

$name : trim(fgets(STDIN));

PHP lets you create all the variables you want. Just give each one a descriptive name (as described in the box below) and put a dollar sign before that name, like this:

$numberSix : 6;
$thisIsMyName : “Brett”;
$carMake : “Honda”;

What’s in a Name? A Whole Lot

PHP doesn’t actually require you to use descriptive names. In fact, there are t~ousands of PHP programs on the Web with code that looks like this

$x : $_REOUEST[‘username’];
$y : $_REOUEST[‘password’];

This code runs just as well assimilar code that usesmuch more descriptive names

$username : $_REOUEST[‘username’];
$password : $_REOUEST[‘password’];

So,what’s the big deal? Many programmers will try to convince you that it’s a lot of extra work to type in these longer descriptive names. That’s true, too

Now that you know the basic code for creating a variable, go back to your new program, QetFormlnf::; one. Instead of just using echo to print out the submitted information, store each piece of information in a variable. By doing so, you can use that information however you want, and as many times as you want. Here’s what your variables might look like

<?php
$first_name : $_REOUEST[‘first_name’];
$last_name = $_REQUEST[‘last_name’];
$email = $_REOUEST[’email’];
$facebook_url = $_REOUEST[‘facebook_url’)j
$twitter_handle’= $_REOUEST[‘twitter_handle’)j
?>

<html>
<head>
<link href=” ../../css/php/oVol.css” rel=”stylesheet” type=”text/css” />
</head>
<body>
<!– Existing HTML code –>
</body>
</html>

Notice that you can create blocks of PHP code-beginning with <?php and ending with ?>-anywhere you want. In this script, there’s now a block of PHP bef6re any HTML and then several small blocks of PHP within the big chunk of HTML. It’s up to you when and where your PHP goes, as long as it gets the job done. You could have put this block of PHP between the page’s opening html and head element or between the head and the body elements; that choice is up to you.

You can check out your form in a browser, but you shouldn’t see anything different from what you already saw (take a look back to Figure, 3-2). That’s because your HTML-the part of the script that the browser displays to a user-hasn’t changed at all.

But now there’s a little bit of wasteful programming going on. You’re getting the value of each form field through the $_REQUESTvariable once, in the PHP block before all your HTML, and then you’re getting all those variable values again in the HTML itself. Anytime you’re doing something twice, you’re wasting valuable web server resources.

Fortunately, it’s easy to do away with this redundancy. That’s because you have all the values you want, stored in your variables, $first_ name,$last_ name,aM so on. So, in the HTML part of ‘)2″i-, ‘-,”0 C,you can just ec··’ o: -r those variables; you don’t need to deal with $_REQUESTanymore. Here’s how to update the “content” <div>:

Refactor as You Go

Whenever you rearrange code, especially to organize it better or to divide your code’s behavior into separate chunks, you’re “‘dew/in,]. For example, when you created a PHPblock at the beginning of iJ”U Nminfo i)!)P to grab all the information from the submitted form,and then just echoed out each variable within the HTML,you actually were refactoring your script. When you’re writing code, you want to refactor constantly. Anytime you can better organize your script-or, as you’ll do later, better organize lots of scripts that all work together-you should do it. Even if you’re not sure how your better organization might help your program, it’s worth the effort. When you come back to your code a week from now, a month from now, or even a year from now, it’s going to be a lot harder to remember what everything does. Even worse, it’s going to be tough to remember ,vner,;’ things are in your script. (Your scripts are going to get a lot longer soon, too.)

By refactoring as you go, you’re ensuring that it’s easy to see what a script does from a quick look. It also means that when you need to make changes, you can jump right to the spot

But, why put values into a variable? Right now, it’s a little silly: ~II you’re doing is changing the place within your script where you grab information from the $_ REQUESTvariable. That’s not doing you any real good. So, what can you do with these variables once you’ve placed information in them? PHP gives you a lot of options, particularly when you have variables that contain text.

Working with Text in PHP

PHP sees all text the same: a meaningless collection of characters. Those characters can be letters, numbers, spaces, punctuation marks, or just about anything else. In PHP, an English word like “caterpillar” is just as ordinary a piece of text as is something nonsensical like “!(gUHa8@m.@.” To you, “caterpillar” looks like a word. That second group of letters, however, looks like something OBert might have said. To PHP, though, both of them are just text. In fact, because it’s such an important part of the language, PHP and most programming languages have a special word to refer to text: a string. So, a piece of text can also be referred to as a SiT”; thus instead of text searching or text matching, you’ll often hear programmers talk about

Combine Text

The good thing a-bout PHP seeing all text the same way is that you can do all sorts of interesting things with it. regardless of what that text is. So, going back to your script, c; -orrv, T oru: you have five variables, all of which contain text:
$first_name = $_REOUEST[‘first_name’];
$last_name = $_REOUEST[‘last_name’];
$email = $_REOUEST[’email’];
$facebook_url = $_REOUEST[‘facebook_url’];
$twitter_handle = $_REOUEST[‘twitter_handle’];
Two of these are related: $first _nameand $last _name. It’s pretty common to take in information this way-with the names separated-but it’s just as to print them out separately. Imagine walking into your local Pier 1Imports and being greeted by an old friend like this: “Hey there, First Name Brett, Last Name McLaughlin!” That’s pretty awkward; and it’s just as awkward on the Web .

There’s no reason to settle for this separation, though. You can easily combine these two strings by using a technique called ((“neaten ),;C’. That’s a fancy word that just means “combine,” and in the case of strings in particular, combining two pieces of text end-to-end. So, if you concatenate “my” and “girl,” you get a new string, “rnyqirl.”

In PHP,you concatenate with the period (.). For getFortY1!r:ro ono, therefore, find the two lines of HTML that print out the first and last name:
First Name: <?php echo $first_name; ?><br />
Last Name: <?php echo $last_name; ?><br />
Now, change these to a single line, and concatenate the first and last names:
Name: <?php echo $first_name . $last_name; ?><br />
Go back to , enter some information, and then submit your form. You should see something like Figure 3-3: the first name Brett and last name McLaughlin are successfully concatenated. However, if you look closely, you’ll see that the first name and last name are smashed together. What you need is a space between those two bits of text.

PHP & MySQL

PHP & MySQL

This is a situation for which PHP treating all text the same really helps. To add a space, all you have to do is put it in quotes, like this:” ”. PHP doesn’t see that text as any different from the text in your variables. You can just concatenate that string-the empty space-to $first_ name,and then concatenate $last_ nameto the space, like this:

Name: <?php echo $first_name . ” ” . $last_name; ?><br />

Try your form out again, and you should see a proper spacs’between the first and last names. Check out Figure 3-4, which should match what your page now looks like.

PHP & MySQL

PHP & MySQL

Searching Within Text

Of course, if all you could do with strings was smash them together, that would be pretty boring. Thankfully, PHP offers a lot more options. One of the most common things you’ll do with PHP text is search it. For example, take the $facebook_url variable in c.Fc: Y’1 ~0.~rr, Suppose you want to turn that into a live, clickable link. First, add the HTML <a> tag, like so:

PHP & MySQL

PHP & MySQL

But, what happens if someone forgets to put the tscebook. com part of the URL in? Maybe he didn’t read carefully, and he just threw in the part of the URL after ieceoootc.com, like rveti.qever or profiie.pnp?id=699i86223. In this case, the link you create won’t be of any use.

What you need, then, is a way to see whether the text that was entered in your $facebook _url variable contains “facebook.com”. If so, it’s probably safe to turn the text into a URL link. If not, the link probably needs to have added to the beginning of the variable’s value. In other words, your PHP needs to search for the text

The easiest way to do this in PHP is to look for the position of a piece of text inside a bigger piece of text to determine what the position of “facebook.com” is inside of $facebook _url, like this:
$first_name = $_REOUEST[‘first_name’];
$last_name = $_REOUEST[‘last_name’];
$email = $_REOUEST[’email’];
$facebook_url = $_REOUEST[‘facebook_url’];
$position = strpos($facebook_url, “facebook.com”)j
$twitter_handle = $_REOUEST[‘twitter_handle’];

The strpos () function, which just stands for “string position,” returns a number that indicates where in the string the searched-for text exists. So, if $posi tion was 5, that would mean that “facebook.com” appeared at position 5 within $facebook _url. (For more information on how these position numbers work.)

However, it’s not enough to just determine a position. You need to do something with it. Better still, you need to figure out whether it indicates a position within $facebook _url-which would mean that $facebook _url contains “facebook.com”-or if $facebook_url doesn’t have “facebook.com” within it at all. You can do this by seeing if $posi tion is false, something PHP defines for you by using the keyword false. Otherwise, strposj ) returns the position within $facebook_url at which the searched-for string appears

$first_name = $_REOUEST[‘first_name’];
$last_name = $_REOUEST[‘last_name’];
$email = $_REOUEST[’email’];
$facebook_url = $_REOUEST[‘facebook_url’];
$position = strpos($facebook_url, “facebook.com”);
if ($position ===false)

At first glance, it probably looks like there’s a lot of new stuff going on here, but don’t sweat it. You already understand almost all of this code

1. First, strposO checks to see if $facebook_url has the text “facebook.com” within it. The value returned from strpos 0 is stuffed into a new variable, $position.
2. $position is compared to the special PHPvalue false by using an if statement. You’ll learn a lot more about if statements soon, but it does just what it looks like: if $posi tion is false, then execute the code within the curly brackets. { and }.
3. Thecode that’s within {and} only runs ifthe statement above istrue-in this case, if $position === false. If that’s true. then is inserted before the string in $facebook _url, to make a real link to Facebook.
4. There’s also a hidden step inthis if statement: if$position is not false, then nothing happens. The line of code within { and} is completely skipped over.

Now that you’ve made these changes to your script. save it and go back to your web This time. enter a Facebook link without the part of the URL; for example. profile. php?id=100000039185327. Tl’fen. submit your form and see what your result looks like

PHP & MySQL

PHP & MySQL

Changing Text

You’ve combined two pieces of text, you’ve searched within text, so what’s left? Well, changing text, of course. And it turns out that you’ve already got a lot of the information you need to do it.

Consider the Twitter handle people are entering into your web form. Most people put an @ before their Twitter handle, like so: @bdmclaughlin. But to see someone’s Twitter profile on the twitter.com website, you actually don’t want that @. So if the Twitter handle is @phpGuy, the Twitter URL to see that profile would be

Turning a Twitter handle into an active link requires a few steps. Here they are in plain English

Hop back to your entry page, fill it up with information, and then submit the form to your updated script. Try it with and without an @ character in your Twitter handle, and the results should be the same: an output page with links to your Facebook and Twitter page, with the @ correctly removed, as illustrated in Figure 3-8.

PHP & MySQL

PHP & MySQL

PHP’s Angle on Brackets

When you’re using PHP to show a lot of HTML and then dropping little bits of PHP into that HTML,things can get pretty confusing.
Take a look at one of the lines that’s in

<a href:”<?php echo $facebook_url; ?>”>
Your Facebook page
</a><br />

Some of this code looks strange, to say the least: there are two opening brackets before a single closing bracket. and then there’s iiii(l1n’:’fclosing bracket at the end of that first line. On top of that, you’ve got all the PHPwithin Quotation marks. Unfortunately, this is one of the downsides to inserting PHP into HTML.It’s a necessary evil, and it’s something you’ll get used to, but it can still trip you up. Anytime you have PHP code, you ri’d/iv ~hould surround it in < ?php and t». (You don’t have to, though; you can leave off ?> if you’re ending your script with PHP,but that’s generally considered a pretty lazy practice.) If you’re using PHP to insert something into an element that’s already in brackets, you’ll get this strange double-bracketed code

Just be sure you don’t open something with single Quotes and then close it with double Quotes, or vice versa. Mismatching Quotes cause things to break, and nobody wants that. There actually are some differences in how PHP handles doubts-uuoted strings and single-Quoted strings, but it’s nothing you need to worry about right now

Trim and Replace Text

Once you start trying to help your users by correcting possible errors in their form entry, the world of PHP strings becomes a big toolkit at your disposal. Take two other common problems in web forms, especially web forms in which users enter URLs:

You know how PHP strings work, and you’ve already used several PHP functions. You just need to learn two more functions to handle these common problems.

REMOVING EXTRA WHITE SPACE BY USING TRIM

PHP has a trim() function that eliminates any empty characters-what PHP calls “‘L J( -around a string. For example, trimming” I love my space bar. “gives you “I love my space bar.” So, with just a couple of simple additions to your script, you can make sure that extra spaces around your users’ entries is a thing of the past:

$first_name = trim($_REOUEST[‘first_name’])j
$last_name = trim($_REQUEST[‘last_name’)j
$email = trim($_REQUEST[’email’)j
$facebook_url = trim($_REQUEST[‘facebook_url’)j
$position = strpos($facebook_url, “facebook.com”);
if ‘($position === false) {
$facebook_url = http://ww.I.facebook.com/.. . $facebook_url;
$twitter_handle = trim($_REQUEST[‘twitter_handle’)j
$twitter_url = http://ww.I.twitter.com/ ;
$position = strpos($twitter _handle, “@”);
if ($position === false) {
$twitter_url = $twitter_url $twitter_handle;
} else {
$twitter_url = $twitter_url substr($twitter_handle, $position + 1);

This change is simple to implement: every time you get a value from $_REQUEST, just wrap the value in trim(). You’ll never have to worry about white space around your text again.

REPLACING CHARACTERS IN TEXT BY USING STR_REPLACE()

It’s also easy to replace text in a string. You use strJeplaceO, and give it three things:

1. The text to search for, In quotes. For example, “facebook.org”.
2. The replacement text. If you want to replace every occurrence of facebook.org with facebook.com, your replacement text would be “facebook.com” .
3. The string In which to search; that is the value that the user typed Into your web form.

In PHP, you can put all this together on one line (see the box on page 81). You get something like this:
$facebook_url = str_replace(“facebook.org”, “facebook.com”,
trim($_REQUEST[‘facebook_url’));
$position = strpos($facebook_url, “facebook.com”);
if ($position === false) {
$facebook_url = ”http://IWIW.facebook.com/”. $facebook_url;

Make these changes, and then visit your web form again. Enter some information that might have been a problem for a less-skilled PHP programmer, with lots of spaces and a bad facebook.org URL, as shown in Figure 3-9.

php and MySQL

php and MySQL

php and MySQL

php and MySQL

Chain Your Methods (Or Not!)

YOu’might have noticed that PHP lets you do in a single step what might otherwise take several steps. For example, look at this line in your PHPscript

$facebook_url = strJeplace(“facebook.
~rg”, “facebook.com”, trim($_
REOUEST[‘facebook_url’)));

This code actually combines several different things. You could rewrite this code like the following example, to make all those
separate things a little clearer

$facebook_url = $_REOUEST[‘facebook_url’);
$facebook_url = trim($facebook_url);
$facebook_url = str_replace(“facebook.
org”, “facebook.com”, $facebook_url);

Both of these code examples carry out the same task. and from a performance and technical point of view, one isn’t better than the other. That means it’s up to you which version you prefer. So, how do you decide?

The other school of thought is a little less popular among programmers …unless those programmers have to teach what they’re doing to someone else. This school of thought tries to make code really easy to understand. Of course, the more you can break down that chain of actions, the easier it is to quickly figure out what’s going on. This takes a lot more code, but all that extra code is easier to understand, and (at least in theory) to fix if something goes wrong

Realistically, you’ll probably want to end up somewhere in the middle of these two approaches. For instance, your code in “(f”’~’ “.’ .ls n~e and clear, even though a few things are chained together. But if you end up with lines that have 6, 7, or even 10 things attached to one another, it might be time to split things up (and layoff the triple ventis from Starbucks

working with text in PHP

working with text in PHP

PHP Offers a Slew of String Functions

Believe it or not, you’ve only just scratched the surface of what PHP has to offer in dealing with strings and text

So, what do you do? Freak out about how much you con’: yet know? Print out this web page and start memorizing a few functions every night? No, not at all. Just bookmark the page-and while you’re at it, the PHP manual at

Instead of worrying about memorizing the odds and ends of every function in the PHP language, work on understanding the of PHPand how those patterns work. For instance, you now know that most string manipulation involves calling some function, passing it a few pieces of information, and assigning the result to a variable what’s important, and now, every time you do look up a string function in the PHP manual, you know exactly how to use that function correctly

The $_REQUEST Variable Is an Array

It’s probably no surprise to you that PHP is a lot more than a tool to work with text. You’ve been working with strings non-stop, but there are a lot more types of information you’ll need to work with in your PHP scripts. As you might expect, there are all kinds of ways to work with numbers, and you’ll work with them quite a bit before long.

But there’s another important type of information you need to understand. In fact, you’ve already been working with this type as much as you’ve worked with text. This mystery type is an which is a sort of container that holds other values within it.

Arrays Can Hold Multiple Values

An array is a which is an organization of data that can be referenced
all at once. It’s _another one of those terms that will gain you respect at a local Google get together (but might get you some odd looks if you’re having cocktails at a political fund raiser). But, arrays aren’t hard to understand. Think of an array as a file cabinet of information, and you’ve got the idea.

As an example, if you have a variable called $file _cabinet that’s an array, it can store other information within it. You might stuff URLs, and first names, and last names, and emails into that $file _cabinet. You can fill up the file cabinet by tell- II ing PHP where you want your information by using numbers surrounded by square brackets, right after the array variable name, like this

<?php
$file_cabinet(o] = “Derek”;
$file_cabinet (1] = “Trucks”;
$file_cabinet(2] = “derek@DerekTrucks.com”;
$file_cabinet(3] = ••http://www.facebook.com/DerekTrucks ..;
$file_cabinet(4] = “@derekandsusan”;
?>

Think of these numbers as drawers in the file cabinet, or if you like things a little more compact, labels on file folders within the cabinet

Then, you can get information out of $file _cabinet by using those same numbers within brackets

$first_name = $file_cabinet[o];
$last_name = $file_cabinet[l];
$email = $file_cabinet[2];
$facebook_url = $file_cabinet[3];
$twitter_handle = $file_cabinet[4];

From this point. you can do whatever you want with those values, including print them out. Here’s a complete program that isn’t very useful, but certainly puts an array through its paces. It fills an array, pulls information out of the-array, and then does a little printing.

<?php
$file_cabinet[o]
$file_cabinet[l]
$file_cabinet[2]
$file cabinet[3]
$file_cabinet[4]
“Derek”;
“Trucks”;
“derek@DerekTrucks.com” ;
http://www.facebook.com/DerekTrucks ..;
“@derekandsusan”; II
$first_name = $file_cabinet[o];
$last_name = $file_cabinet[l];
$email = $file_cabinet[2];
$facebook_url = $file_cabinet[3];
$twitter_handle = $file_cabinet[4];
echo $first_name . ” ” . $last_name;
echo “\nEmail: ” . $email;
echo “\nFacebook URL:” $facebook_url;
echo “\nTwitter Handle: ” . $twitter_handle;
?>

This program does a fine job filing pieces of information away for use later-but there’s a bit of a problem here. Are you really going to remel1).ber that you have a last name at position 2, and at position 4, you stored the Facebook URL? That’s a disaster waiting to happen

Fortunately, the wise folks that came up with PHP thought this through. PHP arrays are assoCiative, which means simply that you can associate labels with each item in the array. Going back to the idea of each number being a folder in a file cabinet, you can use an actual label on the folder. Better yet, that label can be anything you want.

Following is that same simple program; this time it uses associative labels. You should make these changes to your own copy of this script if you’re following along.

<?php .. ,
$file_cabinet[‘first_name’] = “Derek”;
$file_cabinet[‘last_name’] = “Trucks”;
$file_cabinet[’email’] = “derek@OerekTrucks.com”;
$file_cabinet[‘facebook_url’]
“http://www.facebook.com/DerekTrucks •.;
$file_cabinet[‘twitter_handle’] = :@derekandsusan”;
$first_name = $file_cabinet[‘first_name’];
$last_name = $file_cabinet[‘last_name’];
$email = $file_cabinet[’email’];
$facebook_url = $file_cabinet[‘facebook_url’];
$twitter_handle = $file_cabinet[‘twitter_handle’];
echo $first_name . ” ” . $last_name;
echo ..\nEmail: ” . $email;
echo “\nFacebook URL:” $facebook_url;
echo “\nTwitter Handle: ” . $twitter_handle;
?>

By now, though, this $file cabinet should be looking a bit familiar. You’ve seen something that looks awfully similar …read on for the full story.

PHP Gives You An Array of Request Information

Yes, you guessed it: $_REQUEST -that special variable PHP gave you to gather all the information from a web form-is an array! And when you’ve written code like $_REQUEST,[first_name’ ], you’ve been grabbing a particular piece of information out of that array.

In fact, you’ve already seen that the most powerful way you use arrays is really behind the scenes. You (or a web browser) stick information into the array and then pull it back out and work with that information. The array just serves as a convenient way to hold things, like when a browser is sending a request to your PHP script

You’ve seen that not only can you retrieve information in an array by a name the label on a file folder-but also by number. This means that you can use $file _cabinet [ , first_name’ ], but you can also use $file _cabinet [@-]. The same is true of $_REQUEST; it’s just an array, therefore, using $_REQUEST[O]is perfectly fine with PHP.

What exactly is in $_REQUEST? Go ahead and create the following new program, and you can see for yourself

<html>
<head>
<link href>” .. 1 . ./css/phpMM.css” rel=”stylesheet” type=”text/css” I>
</head>
<body>
<div id=”header”><hl>PHP & MySQL: The Missing Manual</hl></div>
<div id=”example”>Example 3-2</div>
<div id=”content”>
<p>Here’s a record of everything in the $_REQUEST array:</p>
<?php
foreach($_REQUEST as $value) {
echo “<p>” . $value . “</p>”;
?>
– </div>
<div id=”footer”></div>
</body>
</html>

This is another one of those scripts that can look intimidating at first, but it’s really not bad at all. In fact, the only thing you’ve not seen before is the line with the for each construct. Take a closer look at this line, which begins a PHP loop

foreach($_REQUEST as $value) {

The foreach construct is a nifty PHP element that lets you quickly get at the values of an array (you’ll learn a lot more later, on page 466). In this case, foreach takes an array ($_REQUEST) and then pulls each value out of that array, one at a time. Each time it pulls out a single value, it assigns that value to a new variable called $value; that’s the as $value part of the foreach line. Inside the foreach loop, a $value variable is assigned a single value from within the array. This is repeated until there are no more values from left in the array.

Just as with the if statement you’ve used a few times, the curly braces ({ and}) tell PHP where the beginning and the end of this loop are

foreach($_REQUEST as $value) {
echo “<p>” . $value . “</p>”;

Everything between the { and} runs once for each time through the loop. This means that for every item in $_REQUEST, this line is going to run one time:

echo “<p>” . $value . “</p>”;

This echo line prints out $value with some HTML formatting. Every time for each loops around, $value picks up the next value from $_REQUESTw, hich makes this statement is a quick way to print out every value in $_REQUEST

Now, suppose that $_REQUESThas values within it like “Derek”, “Trucks”, and “@ DerekAndSusan”. When PHP runs your code, it does something like this:

echo “<p>” “Derek” “</p>”;
echo “<p>” “Trucks” “</p>”;
echo “<p>” “@DerekAndSusan” “</p>”;

<form action = ” scripts / show Request Info . php ” method = “POST “>

cfieldset>
<label for=”first_name” >First Name:</label>
<input type=”text” name=”first_name” size=”20″ I><br I>
<label for=”last_name”>Last Name:</label>
<input type=”text” name=”last_name” size=”20″ I><br I>
<label for=”email”>E-Mail Address:</label>
<input type=”text” name=”email” size=”sO” I><br I>
<label for=”facebook_url”>Facebook URL:</label>
<input type=”text” name=”facebook_url” size=”sO” I><br I>
<label for=”twitter_handle”>Twitter Handle:</label>
<input type=”text” name=”twitter_handle” size=”20″ I><br I>
</fieldset>
<br I>
<fieldset class=”center”>
<input type=”submit” value=”Join the Club” I>
<input type=”reset” value=”Clear and Restart” I>
</fieldset>
</form>

Visit your new web form, fill it out, and then submit it. The web form you get back is the result of running your new ~”O~ eo ,}S, ‘o =t:o script. This form finally gives you an idea of what’s being sent between your web browser and a w~ server. and you can ?ee it all in Figure 3-12

php and MySQL

php and MySQL

At this point, you have the raw information, but what does it all mean? The web page in Figure 3-12 is like seeing all the files on a computer, but having none of the names of those files. Or, if you like the file cabinet analogy, imagine having a cabinet 0 folders with all the labels torn off. It makes knowing what’s going on a little trickier.

With the form data, you already know the labels: “first_name”, and “last_name”, “email”, and so on. In an associative array such as what PHP uses, these are called the keys. You can get the value of a particular “folder” in an array with code like this: $value = $file_cabinet[$key];

This line of code gets the value from the array that’s attached to whatever label the $key variable holds. Thus, if $key were “first_name”, the code would basically be the same as this:

$value = $file_cabinet[‘first_name’];

Therefore, in s!lOwR”‘(fuestlnfoo/lO, you just need to also get the keys from the $_REQUESTarray, instead of just the values. Then, you can print out both the key 31′(7 the value. And, wouldn’t you know it, PHP makes that easy, again by using foreach:

<div id-“content”>
<p>Here’s a’record of everything in the $_REQUEST array:</p>
<?php
foreach($_REQUEST as $key -> $value) {
echo “<p>For ” , $key • “, the value is ‘” , $value , ‘”.ctto”;
?>
</div>

This time, you’re instructing foreach to get both the key, as $key, and the value, as svalue, That special => sign tells PHP you want the $key and then the $value attached to the key, In other words, you’re grabbing a label and the folder that label is attached to, which is just what you want.

Fill out your form again and check out the results of your updated PHP script, as shown in Figure 3-13,

php and MySQL

php and MySQL

What Do You Do with User Information

At this point, you’ve got a lot of information stuffed into a lot of variables. In fact, your earlier web form, ~;CCid,E’ ,tryForrn j1tn1i, looks a lot like the signup forms you’ve probably filled out hundreds (or thousands) of times online. But there’s a problem, isn’t there? In fact, you might have already run across it as you worked through all the changes to your ,Jerf-o! “ltnto,phn script none of that information was ever saved! You had to enter in your name and social information, over and over and over

Good PHP programmers are able to solve just about any technical problem you throw at them. They know all the PHP string functions, arrays, and a lot more, to boot. But eh PHP programmers can solve a whole set of problems that those good PHP programmers never think about user expectation problems. These are problems that really aren’t technical-although you might need to be a good programmer to work around users.

Here’s the million-dollar question: What does your user 2′<Ot’ct your pages and scripts to do? For instance, does your user expect to have to come back to your page and enter in the same information, each time? Absolutely not. You’d probably stop visiting _asite like that yourself. What you have is a user expectation problem-and if you want users to hang around and use your site, you’d better solve this problem

In fact, one of the best things you can do is actually use your own pages and programs. Get a cup of coffee, a notepad, and just sit down at your computer. Close all your text editors and programming tools, and think, “I’m a user!” Then, tryout your web form, submit the form, enter weird information in it, and just see what happens. “Take a few notes about things that bug you, but remember: you’re just a user here.

You’ll probably find all sorts of things you didn’t even think about. So, now what? Well, you’ve got to start fixing those things. And first up is this pesky issue of having to enter the same information into your page, over and over . PHP & MYSQL: THE MISSING MANUAL

Posted on January 12, 2016 in Installing PHP on Windows Without WAMP

Share the Story

Back to Top