PHP 101 (part 3): Looping The Loop

November 30, -0001

Tutorials

Going Deeper
Switching Things Around
Creative Conditionals
One by One
Being Square
Loop First, Ask Questions Later

Doing it by Numbers
Turning the Tables




Going Deeper

If you’ve been paying attention, you remember that in
Part Two I gave you a quick crash course in
PHP’s basic control structures and operators. I also showed you how PHP
can be used to process the data entered into a Web form. In this
tutorial, I’m going to delve deeper into PHP’s operators and control
structures, showing you two new operators, an alternative to the
if-else() family of conditional statements, and some of PHP’s more
interesting loops. So keep reading… this is just about to get interesting!


Switching Things Around

An alternative to the if-else() family of control structures is
PHP’s switch-case() statement, which does almost the same thing. It
looks like this:


switch (decision-variable) {
    case first condition is true:
        do this!

    case second condition is true:
        do this!
      ... and so on...
}

Depending on the value of the decision variable, the appropriate
case() block is executed. A default block can also be created, to
handle all those occasions when the value of the decision variable does
not match any of the listed case() conditions.

I’ll make this a little clearer by re-writing one of my earlier
examples in terms of the switch() statement:


<html>
<head></head>
<body>

<?php

// get form selection
$day = $_GET['day'];
// check value and select appropriate item
switch ($day) {
    case
1:

        $special = 'Chicken in oyster sauce';
        break;
    case
2:
        
$special = 'French onion soup';
        break;

    case 3:
        
$special = 'Pork chops with mashed potatoes and green salad';
        break;
    default:

        $special = 'Fish and chips';

        break;
}

?>

<h2>Today's special is:</h2>
<?php echo $special ?>
</body>

</html>

There are a couple of important keywords here:

  • The break keyword is used to break out of the switch() statement
    block and move immediately to the lines following it.
  • The default keyword is used to execute a default set of statements
    when the variable passed to switch() does not satisfy any of the
    conditions listed within the block.

A common newbie mistake here is to forget the break at the end of
every case() block. Remember that if you forget to break out of a

case() block, PHP will continue executing the code in all the
subsequent case() blocks it encounters.

For more on the switch() statement, see
http://www.php.net/manual/en/control-structures.switch.php.


Creative Conditionals

Normally, when creating and processing forms in PHP, you would place
the HTML form in one file, and handle form processing through a
separate PHP script. However, with the power of conditional statements
at your disposal, you can combine both pages into one.

How do you do this? Simple. All you need to do is assign a name to
the form submit control, and then check whether the special $_POST
container variable contains that name when the script first loads up.
If it does, the form has already been submitted, and you can process
the data; if it does not, that the user has not submitted the form and
you therefore need to generate the initial, unfilled form. Thus, by
testing for the presence or absence of this submit variable, a clever
PHP programmer can use a single PHP script to generate both the initial
form, and the output after it has been submitted, as appropriate.

Here’s a simple example:


<html>
<head></head>
<body>

<?php
/* if the "submit" variable does not exist, the form has not been submitted - display initial page */
if (!isset($_POST['submit'])) {

?>

    <form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
    Enter your age: <input name="age" size="2">
    <input type="submit" name="submit" value="Go">

    </form>

<?php
    }
else {

/* if the "submit" variable exists, the form has been submitted - look for and process form data */
    // display result

    $age = $_POST['age'];

    if ($age >= 21) {
        echo
'Come on in, we have alcohol and music awaiting you!';
        }
    else {
        echo
'You're too young for this club, come back when you're a little older';

    }
}
?>

</body>
</html>

As you can see, the script contains two pages: the initial, empty
form and the result page generated after hitting the submit button. In
order to decide which page to display, the script first tests for the
presence of the $_POST['submit'] variable. If it doesn’t find it, it
assumes that the form has yet to be submitted, and displays the initial
list of days. Once the form has been submitted, the same script will be
called to process the form input. This time, however, the

$_POST['submit'] variable will be set, and so PHP will not
display the initial page, but rather the page containing the result message.

Note that for this to work, your submit button must have a value
assigned to its “name” attribute, and you must check for that value in
the primary conditional statement. And in case you were wondering, the
$_SERVER array is a special PHP variable which always holds server
information, including the path and name of the currently executing script.

Next up, loops.


One by One

For those of you unfamiliar with the term, a loop is a control
structure that enables you to repeat the same set of php
statements or commands over and over again (the actual number of
repetitions can be a number you specify, or depend on the fulfillment
of one or more conditions).

Now, last time out you saw a few comparison and logical
operators, which help in building conditional statements. Since this
segment of the tutorial is going to focus on loops, this is an
appropriate time to introduce you to PHP’s auto-increment and
auto-decrement operators, which see a lot of use in this context.

The auto-increment operator is a PHP operator designed to
automatically increment the value of the variable it is attached to by
1. It is represented by two “plus” signs (++). This snippet of code should
explain it:

<?php

// define $total as 10
$total = 10;
// increment it
$total++;
// $total is now 11

echo $total;

?>

Thus, $total++ is functionally equivalent to $total = $total + 1.

There’s a corresponding auto-decrement operator (–), which does exactly the opposite:


<?php

// define $total as 10
$total = 10;
// decrement it

$total--;
// $total is now 9
echo $total;

?>

These operators are frequently used in loops, to update
the value of the loop counter, speaking of which…


Being Square

The first – and simplest – loop to
learn in PHP is the so-called while() loop, which looks like this:


while (condition is true) {
    do this!
}


In this case, so long as the condition specified evaluates as true
- remember what you learned in Part Two?
- the PHP statements within the curly braces will continue to execute. As
soon as the condition becomes false, the loop will be broken and the statements
following it will be executed.

Here’s a quick example which demonstrates the while() loop:


<html>

<head></head>
<body>
<form action="squares.php" method="POST">
Print all the squares between 1 and <input type="text" name="limit" size="4" maxlength="4">
<input type="submit" name="submit" value="Go">
</form>
</body>
</html>


This is a simple form which asks the user to enter a number. When
the form is submitted, the PHP script that is invoked should take this
number and print the squares of all the numbers between 1 and the
entered value. With a while() loop, this is simplicity itself:


<html>
<head></head>
<body>

<?php

// set variables from form input
$upperLimit = $_POST['limit'];
$lowerLimit = 1;

// keep printing squares until lower limit = upper limit
while ($lowerLimit <= $upperLimit) {
    echo (
$lowerLimit * $lowerLimit).'&nbsp;';

    $lowerLimit++;
}

// print end marker
echo 'END';

?>

</body>

</html>

This script uses a while() loop to count forwards from 1 until the
values of $lowerLimit and $upperLimit are equal.


Loop First, Ask Questions Later

The while() loop executes a set of statements while a specified
condition is true. But what happens if the condition is true on the
first iteration of the loop itself? In the previous example, if you
were to enter the value 0in the form, the while() loop would not
execute even once. Try it yourself and you’ll see what I mean.

If you’re in a situation where you need to execute a set of statements *at least*
once, PHP offers you the do-while() loop. Here’s what it looks like:


do {
    do this!
} while (condition is true)

Let’s take a quick example to better understand the difference
between while() and do-while():



<?php

$x = 100;
// while loop
while ($x == 700) {

    echo "Running...";
    break;
}

?>

In this case, no matter how many times you run this PHP script, you
will get no output at all, since the value of $x is not equal to 700.
But, if you ran this version of the script:


<?php

$x = 100;
// do-while loop
do {
    echo
"Running...";

    break;
} while ($x == 700);

?>

you would see one line of output, as the code within the do()

block would run once.

Let’s now revise the previous PHP script so that it runs at least
once, regardless of what value is entered into the form:


<html>
<head></head>
<body>

<?php

// set variables from form input
$upperLimit = $_POST['limit'];
$lowerLimit = 1;
// keep printing squares until lower limit = upper limit

do {
    echo (
$lowerLimit * $lowerLimit).'&nbsp;';
    
$lowerLimit++;
} while (
$lowerLimit <= $upperLimit);

// print end marker
echo ' END';

?>

</body>
</html>

Thus, the construction of the do-while() loop is such that the
statements within the loop are executed first, and the condition to be
tested is checked afterwards. This implies that the statements within
the curly braces would be executed at least once.

Read more about the while() and do-while() loops at
http://www.php.net/manual/en/control-structures.while.php and

http://www.php.net/manual/en/control-structures.do.while.php.


Doing it by Numbers

Both the while() and do-while() loops continue to iterate for
as long as the specified conditional expression remains true. But what if you
need to execute a certain set of statements a specific number of times
- for example, printing a series of thirteen
sequential numbers, or repeating a particular set of <td> cells
five times? In such cases, clever programmers reach for the for() loop…

The for() loop typically looks like this:



for (initial value of counter; condition; new value of counter) {
    do this!
}

Looks like gibberish? Well, hang in there for a minute…the
“counter” here is a PHP variable that is initialized to a numeric
value, and keeps track of the number of times the loop is executed.
Before each execution of the loop, the “condition” is tested.
If it evaluates to true, the loop will execute
once more and the counter will be appropriately incremented; if it
evaluates to false, the loop will be broken and the lines following it
will be executed instead.

Here’s a simple example that demonstrates how this loop can be used:


<html>
<head>
<basefont face="Arial">
</head>

<body>

<?php

// define the number
$number = 13;
// use a for loop to calculate tables for that number
for ($x = 1; $x <= 10; $x++) {

    echo "$number x $x = ".($number * $x)."<br />";
}

?>

</body>
</html>

The first thing I’ve done here is define the number to be used for
the multiplication table. I’ve used 13 here – for no reason other than that it
rhymes with “green”.

Next, I’ve constructed a for() loop with $x as the counter
variable, initialized it to 1. and specified that the loop should run no
more than 10 times. The auto-increment operator (discussed earlier)
automatically increments the counter by 1 every time the loop is
executed. Within the loop, the counter is multiplied by the
number, to create the multiplication table, and

echo() is used to display the result on the page.


Turning the Tables

As you just saw, a for() loop is a very interesting – and
useful – programming construct. The next example illustrates its usefulness
in a manner that should endear it to any HTML programmer.


<html>
<head></head>

<body>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
Enter number of rows <input name="rows" type="text" size="4"> and columns <input name="columns" type="text" size="4"> <input type="submit" name="submit" value="Draw Table">

</form>

<?php

if (isset($_POST['submit'])) {
    echo
"<table width = 90% border = '1' cellspacing = '5' cellpadding = '0'>";

    // set variables from form input
    $rows = $_POST['rows'];
    
$columns = $_POST['columns'];
    
// loop to create rows

    for ($r = 1; $r <= $rows; $r++) {
        echo
"<tr>";

        // loop to create columns
        for ($c = 1; $c <= $columns;$c++) {
            echo
"<td>&nbsp;</td>
"
;

        }
    echo "</tr>
"
;
    }
    echo
"</table>
"
;
}

?>

</body>
</html>

As you’ll see if you try coding the same thing by hand, PHP’s for()
loop just saved you a whole lot of work! And it looks good too – take a look at the
source code of the dynamically generated table, and you’ll see that
it’s nicely formatted, with line breaks at the end of every table cell
and row. This magic is accomplished by forcing a carriage return
with
in every call to echo().

For more examples of the for() loop in action, visit
http://www.php.net/manual/en/control-structures.for.php.

Loops are frequently used in combination with one of PHP’s more
complex data types, the animal known as the array. That’s a whole topic in itself, and in fact
I’m going to discuss it in detail in the next segment of this tutorial.
Then I’m going to show you how arrays, loops and forms all work together to make
the creation of complex Web forms as easy as eating pie. All that and more in
Part Four!


Copyright Melonfire, 2004 (http://www.melonfire.com).
All rights reserved.

,

41 Responses to “PHP 101 (part 3): Looping The Loop”

  1. johnnya23 Says:

    I don’t understand the creative conditionals example. perhaps because it doesn’t work. single quotes don’t seem to be the issue.

  2. djquazzi Says:

    The apostrophe’s confused the hell out of me for a while… ( you’re )

    echo ‘Your’e too young for this club, come back when you’re a little older’;

    Loving the tutorial…

  3. whateverme Says:

    I have been trying all the above solution
    and all I get is
    a page where there’s a box to enter an age
    then underneath it
    this appear:
    = 21) { echo "Come on in, we have alcohol and music awaiting you!"; } else { echo ‘You\’re too young for this club, come back when you\’re a little older’; } } ?>

    I saved my file .php – doesn’t work
    tried .html doesnt work either.

    I used firefox. in chrome it ended up downloading the file. so that’s why I used firefox.
    any help would be very much appreciated.

  4. kernel-stack Says:

    Ignore the [quote] and [/quote], forum leftovers when i pasted… :P

  5. kernel-stack Says:

    First of all, GREAT guide. So there was a little problem with that age ver. code.

    You need to use " \’ " without the quotes and spaces to add an apostrophe.

    [quote]
    <html>
    <head></head>
    <body>

    <?php

    /* if the "submit" variable does not exist, the form has not been submitted – display initial page */
    if (!isset($_POST['submit'])) {
    ?>

    <form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
    Enter your age: <input name="age" size="2">
    <input type="submit" name="submit" value="Go">
    </form>

    <?php
    }
    else {
    /* if the "submit" variable exists, the form has been submitted – look for and process form data */
    // display result
    $age = $_POST['age'];

    if (is_numeric($age) && strlen($age) <= 2) {
    switch ($age) {
    case ($age >= 21):
    echo ‘Come on in, we have alcohol and music awaiting you! </br></br><a href="test2.php">BACK</a>’;
    break;
    case ($age <= 21): /* Use \’ to insert an apostrophe */
    echo ‘You\’re too young for this club. Grow some and return. </br></br><a href="test2.php">BACK</a>’;
    break;
    }
    }
    else {
    echo ‘Not right. Not right at all… Go <a href="test2.php">BACK</a> to enter a number.’;
    }

    }

    ?>

    </body>
    </html>[/quote]

    Also added a little a if-else in order to validate that the input is a numeric, double-digit value using "is_numeric" and "strlen". Ok, a bit racist for those over 99 but they should probably stay home at nights anyway. :(

  6. nicoswd Says:

    Echoing unfiltered PHP_SELF makes your site vulnerable to XSS (cross site scripting) attacks.

    Come on, Zend! You know better than that!

  7. _____anonymous_____ Says:

    thank you so much for creating a simple guide to getting started with php.
    i have to do a college project and have been struggling to get started.
    i have looked at lots of websites and bought lots books but to no avail.
    this may actually get me my degree in the end.

  8. _____anonymous_____ Says:

    For anyone reading the comments, I figured out the reason for my previous comment. I saved the code as .html not as .php. If you want the server to interpret your php code it has to end with .php but the resulting document needs to be a valid .html document. Newbie mistake.

  9. _____anonymous_____ Says:

    Great tutorial. Did anyone else get a "you are not authorized" page after clicking "generate table"? The address in my browser made it look like it didn’t run the php code that was part of the form action. It showed "http://localhost/&lt;?php%20echo%20$_SERVER['PHP_SELF'];%20?>"

  10. computerwiz Says:

    Hi,

    Anyone have an tips on how to remember how to write and how to use them?

    I for some reason cannot get my head around in understanding them.

    I keep forgetting how to write them and how to use them etc.

    Any tips, advice would be much appreciated.

    Thank you

  11. _____anonymous_____ Says:

    You can make some simple modifications to Vikram’s code in order for the table’s source code to display ‘neatly’. I used the PHP_EOL constant which can be used to insert line breaks into the output without having to use the <br /> tag.

    Here’s where I put my PHP_EOL’s:

    <?php

    if (isset($_POST['submit'])) {
    echo "<table width = 90% border = ’1′ cellspacing = ’5′ cellpadding = ’0′>".PHP_EOL;
    // set variables from form input
    $rows = $_POST['rows'];
    $columns = $_POST['columns'];
    // loop to create rows
    for ($r = 1; $r <= $rows; $r++) {
    echo PHP_EOL.’<tr>’.PHP_EOL;
    // loop to create columns
    for ($c = 1; $c <= $columns;$c++) {
    echo "<td>Row $r Column $c</td>".PHP_EOL;
    } echo ‘</tr>’.PHP_EOL;
    }
    echo ‘</table>’;
    }

    And this makes it generate code like this;

    <table width = 90% border = ’1′ cellspacing = ’5′ cellpadding = ’0′>

    <tr>
    <td>Row 1 Column 1</td>
    <td>Row 1 Column 2</td>
    <td>Row 1 Column 3</td>
    </tr>

    <tr>
    <td>Row 2 Column 1</td>
    <td>Row 2 Column 2</td>
    <td>Row 2 Column 3</td>
    </tr>
    </table>

    You can check it out in action here: http://www.steventhompson.co.uk/tablegenerator/

  12. _____anonymous_____ Says:

    Everyone seems to be having trouble due to the odd number of single quotes, but for me, the darn thing just fails totally! I copied it straight off the site, repaired the quote issue, and when I run it, I get:

    Parse error: parse error in /Users/thomas/Sites/phpinfo.php on line 16

    Line 16 is:

    &lt;?php
    } &lt;— this line right here
    else {

    What’s up? Sure doesn’t inspire confidence in the tutorials on this site if its code breaks on some servers!

  13. dbudry Says:

    I was having problems with the syntax of the statement "echo ‘You’re too young for this club, come back when you’re a little older’;" It has trouble with the extra apostrophe’s. I changed it to "echo ‘You&#39;re too young for this club, come back when you&#39;re a little older’;" and that seemed to work okay for me.

    Thank you again for all your hard work. This stuff is great!

  14. admin_J Says:

    I have been programming for about a year or so. I bought a previous script of a game from someone and it had a lot of errors. Since I did not know anything about anything I have searched months for sites on PHP coding. Alot are confusing and geared for the experience or those who have a better understanding than myself. Now a year later found the best site for me to learn. Thanks so much!!!!!

    Please add more information on PHP PLEASE, I do not wnat to search any more crappy sites.

  15. _____anonymous_____ Says:

    just wondered why it was fun to run the 546 687 or what ever the numbers where in the table generation code, i didn’t see what was fun just a giant table?

  16. _____anonymous_____ Says:

    Fun!!
    Try putting in 564 and 687 for the value of your table rows and columns ;)

    …purty nifty.

  17. _____anonymous_____ Says:

    when doing the Creative Conditionals section of the tut, the browser had trouble parsing this line:

    echo ‘You’re too young for this club, come back when you’re a little older’;

    to make this working change this to

    echo ‘You\’re too young for this club, come back when you\’re a little older’;

    I just added \

  18. _____anonymous_____ Says:

    "And it looks good too – take a look at the source code of the dynamically generated table, and you’ll see that it’s nicely formatted, with line breaks at the end of every table cell and row."

    NO, IT ISN’T. I didn’t think it would be from my previous limited knowledge of PHP and it wasn’t. I’ve just tested the table generator script and taken a look at the source code: each ‘echoed’ piece of code follows directly on from the previous with no line breaks.

    This was a table with 3 rows and one column:

    <table width = 90% border = ’1′ cellspacing = ’5′ cellpadding = ’0′><tr><td>&nbsp;</td> </tr> <tr><td>&nbsp;</td> </tr> <tr><td>&nbsp;</td> </tr> </table>

  19. _____anonymous_____ Says:

    I am a little confused about why when I hit return after typing in an age it will act as if the age has not been set and reload the original page. This only happens on IE so I was wonering if this is something that will happen with all IE + PHP pages or just an issue with this script.

    Thanks
    Todd

    PS. Great Tutorial.

  20. _____anonymous_____ Says:

    I am a little confused about why when I hit return after typing in an age it will act as if the age has not been set and reload the original page. This only happens on IE so I was wonering if this is something that will happen with all IE + PHP pages or just an issue with this script.

    Thanks
    Todd

    PS. Great Tutorial.

  21. _____anonymous_____ Says:

    Try to open your files trough browser!!! You probably do it in an easy way for you – I guess you just press the Enter button on the file in Total Commander or whatever you have…
    I had the same problem first, then I realized that I should write the whole adress in the browser and everything worked in the end!
    Good luck with your studies of PHP!

    Thanks guys for this tutorial! It’s great!

  22. _____anonymous_____ Says:

    A user said:
    CREATIVE CONDITIONALS

    Isthan [unregistered]
    if (!isset($_POST['submit'])) {

    ?>

    <form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">

    I didnt quite understand where !isset was defined/how it is being used here.
    I understand that it is checking for a value from the form $_POST. Before
    with forms we’ve used the action to define a php source file, what does
    $_SERVER['name']; tell us?

    The isset is in simple concept a PHP predefined function that checks to see whether a value has been given for a variable. I havent read all the tutorials here yet, but i bet it ll be explained in later chapters. The $_SERVER is an array, which will also be explained in later tutorials i guess?..

    For now, i think its best you take it as a simple, special variable.

    Good tutorial -> Even if you dont fully understand a concept keep reading.

  23. _____anonymous_____ Says:

    I am just starting with PHP, but my very first PHP script fails to work. I am working as the examples given, but Mozilla (and IE7) ask me to OPEN the php file instead of executing it every time I call it from a html file. What’s going awfully wrong?
    BTW this tutorial has great and clear explanations, thank you very much!

  24. _____anonymous_____ Says:

    Repeating everybodys praise: Great site! I’m really learning PHP here :-) Found a little inconsistency in the text followin the code example:
    "If it doesn’t find it, it assumes that the form has yet to be submitted, and displays the initial list of days."
    This clearly has to do with example in "Switching Things Around". Not a big deal, won’t stop people from understanding the code, but it might confuse someone like me (newbie!) for a while.

  25. _____anonymous_____ Says:

    Before i scroll into your comments i already figured that problem out.
    maybe its just a skill that i can read codes but couldn’t write codes.. hehehe.. :D if the ‘ didn’t work, then switch to "….

    i already have a couple of symfony projects that i debug and the problem is usually the semi-colon, paths and this ‘ and " things.. :D

    anyway gre4at tutorial!!

    i can now write php codes at last! i’m not a debugger anymore! i’m a developer.. hahah

  26. phileasphogg Says:

    I learned a very useful lesson here, this being that if you are working with single quotes, then apostrophes are interpreted as part of the single quote setup. The way to avoid this systemic confusion is EITHER to use double quotes to "wrap" the sentence with (as BC Software (unregistered) suggested in the Comment posted on Nov 11, 2007 above), OR, retaining the single quotes, to "escape" the apostrophes by means of a backslash in front of the apostrophe (as Anonymous User (unregistered) suggested in the Comment posted on Feb 6, 2008 above). I got an error report that there was an incorrect string on Line 25 and that the system was expecting an "or" (when the system get befuddled, one cannot rely on the validity of the error report, although, in this case, it turned out to be the case – and is probably the case in general – that the error was indeed on Line 25 (counting all blank lines as lines too)). It is of course intuitively correct that the system expects an apostrophe to be part of the single-quote setup when using single quotes. I have noted in earlier examples (Lesson 2, or perhaps Lesson 1) that sometimes the Vikram uses single quotes and sometimes he uses double quotes, and no explanation was given. I must revisit those examples and see if there was not an apostrophe present where the choice fell on the double quotes. The value of this little lesson is that one has two methods to solve a potential problem, and that can be handy also if one, instead of using apostrophes, actually uses a real-world quote, which is usually in double quotation marks, together with double quotes as "wrap". Thank you Vikram; thank you sharp users!

  27. _____anonymous_____ Says:

    … and then I’ve saved that as index.php and everything is OK.
    :)

  28. _____anonymous_____ Says:

    I have problem with running Creative Conditionals example. I copy/pasted code and saved as index.htm in root on my local server (WAMP – The Uniform Server).

    When I load it, I get:

    1. form on top of the page (normally displayed)

    2. and this text just below:
    __

    = 21) { echo ‘Come on in, we have alcohol and music awaiting you!’; } else { echo ‘You’re too young for this club, come back when you’re a
    little older’; } } ?>
    __

    Also, when I enter number in form and submit I get this:
    __

    Forbidden
    You don’t have permission to access /< on this server.
    Apache/2.0.59 (Win32) DAV/2 PHP/5.2.3 Server at phpproba.localhost Port 80
    __

    Is this issue have something to do with my PHP5 only enabled server or…?

    Tnx in advance

  29. _____anonymous_____ Says:

    You can also keep the single quotes on the outside, but use a backslash to escape the apostrophes in the two instances of "you’re" (so that php know they’re not supposed to be quotes themselves) – e.g:

    echo ‘You\’re too young for this club, come back when you\’re a little older’;

  30. CryLobo Says:

    Thanks. Newbie here. I kept getting a blank screen when I ran the script, but as soon as I followed your suggestion and changed the quotes from single to double, it ran perfectly. Don’t know if I ever would have figured that out on my own. Thanks again.

  31. _____anonymous_____ Says:

    Hey Guys,
    Great site. I am a .asp developer that needs a quick tutorial on PHP. This site is great.

    The issue with the Creative Conditionals is the quote. You need double quotes around

    ‘You’re too young for this club, come back when you’re a little older’;

    With the single quote which is in the example will not process. Should be

    "You’re too young for this club, come back when you’re a little older";

    This is how it was in the earlier example (Step 2). Once I used double quotes it worked.

    Thanks Again

  32. dangoble Says:

    I get most of what is going on in the creating tables tut, but am stuck on why the column loop is INSIDE the row loop. I understand WHY it has to be done, but wouldn’t the column loop start again every time the row loop incremented?

    By the way as mentioned b4, great tut.

  33. Maistah Says:

    Sami, the solution to the problem is:

    save the file as a .php file

    Except that, the ‘ and ‘ in line 27 are kinda messing up so I had to make are of it instead of ‘re

  34. Maistah Says:

    Sami, I had exactly the same problem… Don’t get it either :)

  35. sami_glasgow Says:

    Hi,

    can i first say thanks for such an easy to use and ejoyable set of tutorials!

    can somebody help me please because i seem to be having a problem.

    i have been following the examples no problem (by simply copying and pasting them then running them myself), but when i get to the stage where the html form and php and combined…my broswer doesnt seem to run it properly

    i have the enter your age box, but below there is part of the code:

    http://img68.imageshack.us/img68/3920/problemko6.png (as shown in this screenshot)

    and if i put it an age, and click go, it tried to load a page ending in /> which doesnt load

    im really finding these tutorials usefull so can anyone please help me overcome this problem

    Thank you,

    Sami

    p.s. i have tried using ie7 and firefox 2.0.0.6

  36. _____anonymous_____ Says:

    if (!isset($_POST['submit'])) {

    ?>

    <form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">

    I didnt quite understand where !isset was defined/how it is being used here. I understand that it is checking for a value from the form $_POST. Before with forms we’ve used the action to define a php source file, what does $_SERVER['name']; tell us?

  37. _____anonymous_____ Says:

    Oh vey. I tried to include backslash t " " and backslash n "
    " but they disappeared from my post. They’re required in the code to include the tabs and newlines that keep the source code neat and pretty.

  38. _____anonymous_____ Says:

    You forgot to include the ‘s and
    ‘s to make the source code ‘neat.’

    Try this instead:

    <html>
    <head></head>
    <body>
    <form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
    Enter number of rows <input name="rows" type="text" size="4"> and columns <input name="columns" type="text" size="4"> <input type="submit" name="submit" value="Draw Table">
    </form>

    <?php

    if (isset($_POST['submit'])) {
    echo "<table width = 90% border = ’1′ cellspacing = ’5′ cellpadding = ’0′>
    ";
    // set variables from form input
    $rows = $_POST['rows'];
    $columns = $_POST['columns'];
    // loop to create rows
    for ($r = 1; $r <= $rows; $r++) {
    echo " <tr>
    ";
    // loop to create columns
    for ($c = 1; $c <= $columns;$c++) {
    echo " <td>&nbsp;</td>
    ";
    } echo " </tr>
    ";
    }
    echo "</table> ";
    }

    ?>

  39. _____anonymous_____ Says:

    These are very great tutorials, very informative, especially for the beginner user! Just wanted to make a note, I’m not sure if everyone ran into this problem, but when doing the Creative Conditionals section of the tut, the browser had trouble parsing this line:

    echo ‘You’re too young for this club, come back when you’re a little older’;

    It worked if I took out the apostrophe’s in your’re. Just wanted to let anyone know that ran into this problem.

    Thanks for the great tutorials!!!

  40. _____anonymous_____ Says:

    Hate to parrot everyone else’s comments, but I’d like to say how great these tuts are. Thank you for taking the time to write such concise and intelligent articles. Truly the best I have found so far.

  41. _____anonymous_____ Says:

    This is the best tutorial i have ever seen. The table thing was hard but i got through it because this tutorial is soo great