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

 

 

 

 

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;

 

 

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.