0

With PHP I generate something like this:

<form>
<table>
<tr> 
    <td>Total:</td>
    <td><input type="text" id="total" disabled value="0"> </td>
</tr>
<tr> 
    <td>Field 1:</td>
    <td><input type="text" id="field1" value="1"> </td>
</tr>
<tr> 
    <td>Field 2:</td>
    <td><input type="text" id="field2" value="2"> </td>
</tr>
</table>

Now the first input ("total") should contain the sum of all the "field" inputs. Summing them in a PHP variable is not a problem. But once I am down at the end of the table, can I change the value of "total"?

Workarounds I can think of are

  • placing the total at the end; but then my page would not look the way I desire.
  • do the loop through the data twice, first to do the sum, then to write the HTML. But that looks inefficient.
  • storing the sum in a hidden input and writing it later with javascript.

So, again, can I still change the value of "total" with PHP after having generated the entire table?

5
  • I think you should use JavaScript Commented Nov 21, 2016 at 12:13
  • You will need to use JavaScript. As soon as your PHP has loaded to screen, that's it. You would need to refresh the page again to update or use an AJAX request to call a PHP script and update your table data stopping the need of a refresh. Commented Nov 21, 2016 at 12:18
  • you should use javascript or ajax. Commented Nov 21, 2016 at 12:18
  • 1
    Option: Loop through the data backwards and assemble the output backwards as well - $output = 'new table row' . $output; // Option: Assemble data in output variable in the right order, and use a placeholder for the total, that can later be replaced using sprintf, str_replace or ... Commented Nov 21, 2016 at 12:19
  • Thanks @CBroe. This is a clever idea, I can even loop forward accumulating the entire rest of the table in a variable before I write the "total" line. Commented Nov 21, 2016 at 12:24

1 Answer 1

2

Well, you can still do it in PHP if that's what you need/want to. Just don't echo your data inside the loop, store the output in 2 variables and print it after the loop in the order you need. Something like this

$total = 0; $bodytr = "";

for($i=1;$i<=10;$i++){
    $total += $i;
    $bodytr .= "<tr><td>$i</td></tr>\n";
}

echo "<table>\n";
echo "<tr><td>$total</td></tr>\n";
echo $bodytr;
echo "</table>";
Sign up to request clarification or add additional context in comments.

1 Comment

Yes, this is more or less what @CBroe suggested in his comment. It looks better to me than my workarounds. Thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.