Page 1 of 1

Calling a form in a loop

Posted: Tue Nov 09, 2010 3:05 pm
by rgren925
Hi. I'm a PHP newbie.
I'm trying to generate a form in a loop.
The user would press the submit button and the loop would iterate.
Ultimately, it's for a project that will read a large flat file and get 500 lines at a time that the user could page through.
But, my little test case is far simpler. just increment a counter every time the user presses submit.
What I've tried doesn't work; causes an endless loop rather than stopping each time for the user to hit submit.
I've just cobbled this together from things I've seen here and elsewhere, so please be gentle.
Any help would be greatly appreciated.
Thanks, Rick

Code: Select all

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>PHP Loop Test</title>
</head>
<body>
<?php
$i = 0;
while ($i < 5) {
    echo '<form name="PHP" action="'.$PHP_SELF.'" method="POST">';
    echo '<input type="submit" name="click_php" value="PHP form" />';
    echo '</form>';
    if($_POST['click_php'])
    {
        echo "This is from PHP form ==> $i";
        $i++;
    }
}
?>
</body>
</html>

Re: Calling a form in a loop

Posted: Wed Nov 10, 2010 9:01 am
by Celauran
You're getting an infinite loop because every time the form is submitted, the page reloads and, in so doing, resets $i to 0. For the value of $i to persist across reloads, you need to store it somewhere; cookies, session data, or in the URL as $_GET data.

Maybe something like this?

Code: Select all

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <title>PHP Loop Test</title>
    </head>
    <body>
<?php

    if (isset($_GET['offset'])) { $i = $_GET['offset']; }
    else { $i = 1; }

    if ($i < 6){
        echo '<form name="PHP" action="'.$PHP_SELF.'" method="get">';
        echo '<input type="hidden" name="offset" value="' . ($i + 1) . '" />';
        echo '<input type="submit" value="Next" />';
        echo '</form>';
    }
?>
    </body>
</html>

Re: Calling a form in a loop

Posted: Wed Nov 10, 2010 10:30 am
by rgren925
Thanks very much Celauran.
that is exactly what I needed to get this going.
Rick