seRgiOOOOOO
seRgiOOOOOO

Reputation: 101

PHP - Variable inside a nested if isset doesn't display

I have this two files

A.php

<?

 echo "
     <form action = 'B.php' method = 'post'>
           Age: <input type = 'text' name = 'age'>
           <input type = 'submit' name = 'send' value = 'send'>
      </form>
 ";

?>

B.php

<?

  $age = $_REQUEST ['age'];

  if (isset($_POST['send'])){
      echo "Are you sure you wanna send this age?";
      echo "
             <form action = 'B.php' method = 'post'>
             <input type = 'submit' name = 'age2' value = 'YES'>
          ";

                 if (isset($_POST['age2']) && !isset($_POST['send'])){
                     echo "Your final age is".$age; //It doesn't display!!! :(
                 }
            echo "</form>";
  }
 ?>

If I delete the second if isset, $age will be displayed.

If you realize, in the second isset i have two conditions, first one, that YES button must be clicked, second one, send button mustn't be clicked.

I have tried many this and I don't get this :(

P.S. I want to display it in the same page. No other pages. If it's not possible this, then I'll make in other page.

Upvotes: 0

Views: 2337

Answers (2)

Nuance Jones
Nuance Jones

Reputation: 241

What you mean is. You send the first form. Then it loads another page to confirm. Once you confirm you get the original age. Right?

Try it like this.

<?php
  $age = $_POST['age'];
  if (isset($_POST['send'])):
?>
  Are you sure you want to send this age?
  <form action = 'b.php' method = 'post'>
  <input type = 'hidden' name = 'age' value = '<?php echo $age; ?>'>
  <input type = 'submit' name = 'age2' value = 'YES'>

<?php
  endif;
  // This wont show up if the first form is sent
  if (isset($_POST['age2'])){
      echo "Your final age is ".$_POST['age']; //It does display!!! :(
  }

 ?>

Upvotes: 0

mario
mario

Reputation: 145482

You do need to:

  • Split out the second if. It can't both be true. Either button1 is pressed, or it isn't.
  • Carry on the previous variable with a <input type=hidden>
  • Learn about strings and heredoc syntax.
  • Fix your awful indendation.

So it looks like:

<?php

  $age = $_REQUEST['age'];

  if (isset($_POST['send'])) {

      echo <<<END
             Are you sure you wanna send this age?
             <form action='B.php' method='POST'>
                <input type='submit' name='age2' value='YES'>
                <input type=hidden name=age value='$age'>
             </form>
END;

  }

  if (isset($_POST['age2'])) {
      echo "Your final age is $age";
  }

?>

Upvotes: 3

Related Questions