I am stack when i need to combine php inside HTML to print the result inside the HTML table <td>

#1

<?php
if(isset($_POST[‘check’])){
$n1=$_POST[‘n1’];
$n2=$_POST[‘n2’];
$ans=$n1+$n2;
echo “The sum is $ans”;
}
?>

<form action="" method="post">
    <table border="1"><tr>

            <td>Enter Fnumber:<input type="text" name="n1"></td>
            <td>Enter Snumber:<input type="text" name="n2"></td>
            <td><input type="submit" name="check"></td>
            
            <td>the answer is $ans</td>
    </tr> 
    </table>
</form>
#2

Stuck on what exactly?

#3

When I run that code it display error variable $ans not found (I know variable answer need to be available after calculation. How I can spot HTML to display error at the first run)

#4

i would say at least your quotes are broken.

#5

Hello, you are actually mixing a variable with raw html. The browser will treat it as text and display $ans instead of the results.

Use this code

<td> The answer is <?=$ans ?> </td>
OR
<td> The answer is <?php echo $ans ?> </td>

#6

@peninsula, that is one part of the problem. The other is that the OP is trying to use a variable without checking if it exists first and/or not setting a default empty value.

1 Like
#7

@benanamen , yh sure. His code is more vulnerable to attacks provided it is set for a real world usage. It all boils down to also checking if the variable exist and it’s value is not empty.

@emacha1 , you are going to need a more clean way to do this if you intend using it in a public project

1 Like
#8

Hello, as a beginner, you should be aware that input needs to be sanitized if you are going to output any input. Also, you should be checking the request method.

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
  $n1 = trim($_POST['n1']);
  $n2 = trim($_POST['n2']);
      if (is_numeric($n1) && is_numeric($n2)) { 
          $ans = $n1 + $n2;
          echo 'The sum is: ' . htmlentities($ans);
      } else {
          echo 'non numeric value.';
      }
  exit;
}

many ways to validate, many ways to sanitize. find what is best for you but remember to use it.

1 Like
#9

Correct. What you described is exactly what empty does.

A variable is considered empty if it does not exist or if its value equals FALSE . empty() does not generate a warning if the variable does not exist.

https://www.php.net/manual/en/function.empty.php