Jump to content

[SOLVED] Adding more than one amount in one field


ajentp

Recommended Posts

Hi

 

I am wondering if it is possible to get sum for more than one numerical amount submitted through one form field.

 

Such as a user types "200 + 300 + 400 " into one of the form fields. Then the form is submitted.  The value retrieved though POST method. Now can we get the value as 900 through PHP function or JS.

 

Thanks for your time

 

 

 

 

Link to comment
Share on other sites

eval() is the simplest option, but not safe (especially in this case where it's direct user input that you want to execute)

PHPExcel has a built-in formula parser, which would allow you to execute this formula in a sandbox

 

/** Include path **/
set_include_path(get_include_path() . PATH_SEPARATOR . 'PHPExcel/Classes/');

include('PHPExcel/Calculation.php');

if (isset($_POST['EQUATION'])) {
$displayFormula = $formula = stripslashes($_POST['EQUATION']);
} else {
$displayFormula = $formula = '200 + 300 + 400';
}

?>
<h1>Equation Calculator</h1>

<form method="post">
<table border="0">
	<tr>
		<td>
			<b>Equation:</b> 
		</td>
		<td>
			<input type="text" name="EQUATION" size="80" value="<?php echo htmlentities($displayFormula); ?>">
		</td>
	</tr>
	<tr>
		<td colspan="2" align="right">
			<input type="submit" value="Calculate">
		</td>
	</tr>
</table>
</form>


<hr />
<?php

if ($displayFormula{0} == '=') { $displayFormula = substr($displayFormula,1); }
if ($formula{0} != '=') { $formula = '='.$formula; }


echo '<h3>Evaluation Result for '.$displayFormula.' is:</h3>';
try {
$result = PHPExcel_Calculation::getInstance()->calculateFormula($formula);
} catch ( Exception $ex ) {
$result = '<font color="red"><b>ERROR: </b>'.$ex->getMessage().'</font>';
}


/**	Display the calculated $result	**/
if (is_bool($result)) {
$result = ($result) ? 'boolean: TRUE' : 'boolean FALSE';
} elseif(is_string($result)) {
$result = 'string: '.$result;
} elseif(is_float($result)) {
$result = 'float: '.$result;
} else {
$result = 'integer: '.$result;
}
echo 'Result is '.$result;

 

 

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.