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

<?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>

Stuck on what exactly?

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)

i would say at least your quotes are broken.

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>

@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

@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

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

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

Sponsor our Newsletter | Privacy Policy | Terms of Service