Question

So, I have this code

<?php
if(!isset($_POST["step1_submit"]))
{
    echo "Fill step1!";
    step1();
}


function step1()
{
    if(isset($_POST["step1_submit"]))
    {
        step2();
    }
    else
    {
        echo '<form action="" method="post">STEP 1: <input name="step1_input"/><input name="step1_submit" type="submit" value=">>STEP 2>>"/></form>';
    }
}

function step2()
{
    echo "reached step 2";
    if(isset($_POST["step2_submit"]))
    {
        echo '<br/>'.$_POST["step2_input"];
        step3();    
    }
    else
    {
        echo '<form method="post">STEP 2: <input name="step2_input"/><input name="step2_submit" type="submit" value=">>STEP 3>>"/></form>';
    }
}

function step3()
{
    echo '<strong>WELL DONE</strong>';  
}
?>

It shows the input for step1, but never gets to show step2. In my opinion, it gets stuck on calling the function step2, because while doing it, the isset($_POST(step1_submit)) changes it value to NULL.

How can I manage to make this code work? It should be like: filling step 1 input >> getting to fill step 2 input >> submit step 2 >> get to see the 'WELL DONE' echo.

Was it helpful?

Solution

Basically the conditional statement on top needs an else branch:

if(!isset($_POST["step1_submit"]))
{
    echo "Fill step1!";
    step1();
} else {
    step2();
}

...

However, if you have more steps it should look like this:

switch(TRUE) {

    case isset('step1_submit') :
        step2();
        break;

    case isset('step2_submit') :
        step3();
        break;

    ...

    default: 
        echo "Fill step1!";
        step1();

}

Then change your functions to:

function step1()
{
    echo '<form action="" method="post">STEP 1: <input name="step1_input"/><input name="step1_submit" type="submit" value=">>STEP 2>>"/></form>';
}


function step2()
{
    echo '<form action="" method="post">STEP 2: <input name="step2_input"/><input name="step2_submit" type="submit" value=">>STEP 3>>"/></form>';
}

...

The if conditionals aren't required there.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top