Search code examples
phphtmlfactorial

How to get the result(output) in text box after clicking submit in PHP?


I'm trying to calculate factorial of a number in PHP. I've got two text boxes: 1) for number 2)for result(the factorial of the number)

When I click submit, I want the result in the textbox of result.How can I make it happen.

<html>
    <title>Factorial</title>
    <body>
    <form name="f1" method="POST">
    number :<input type="text" name="T1">
    factorial :<input type="text" name="T2" >
    <input type="submit" name="submit">
</body>
</html> 

<?php
if(isset($_POST['submit']))
{
 $num=$_POST['T1'];
 $fact=1;

 while($num>0)
 {
  $fact=$fact*$num;
   $num--;
  }

  //code for writing result to the textbox.

  }
  ?>

Solution

  • Try this:

    <?php
    if(isset($_POST['submit']))
    {
     $num=$_POST['T1'];
     $fact=1;
    
     while($num>0)
     {
      $fact=$fact*$num;
       $num--;
     }
    
    //code for writing result to the textbox.
    
     }
    ?>
    
    
    <html>
    <title>Factorial</title>
    <body>
    <form name="f1" method="POST">
    number :<input type="text" name="T1" value="<?php isset($num) ? $num : ''?>">
    factorial :<input type="text" name="T2" value="<?php isset($fact)? $fact : '';?>">
    <input type="submit" name="submit">
    </body>
    </html>