I\'m learning php and built an experimental form-based calculator (also using html & POST method) that returns values to a table. The calculator is functional when I ent
try this
if(isset($itemCost) != '' && isset($itemQty) != '')
{
$diffPricePercent = (($actual * 100) / $itemCost) / $itemQty;
}
else
{
echo "either of itemCost or itemQty are null";
}
You need to wrap your form processing code in a conditional so it doesn't run when you first open the page. Something like so:
if($_POST['num1'] > 0 && $_POST['num2'] > 0 && $_POST['num3'] > 0 && $_POST['num4'] > 0){
$itemQty = $_POST['num1'];
$itemCost = $_POST['num2'];
$itemSale = $_POST['num3'];
$shipMat = $_POST['num4'];
$diffPrice = $itemSale - $itemCost;
$actual = ($diffPrice - $shipMat) * $itemQty;
$diffPricePercent = (($actual * 100) / $itemCost) / $itemQty ;
}
If a variable is not set then it is NULL
and if you try to divide something by null you will get a divides by zero error
You can try with this. You have this error because we can not divide by 'zero' (0)
value. So we want to validate before when we do calculations.
if ($itemCost != 0 && $itemCost != NULL && $itemQty != 0 && $itemQty != NULL)
{
$diffPricePercent = (($actual * 100) / $itemCost) / $itemQty;
}
And also we can validate POST
data. Refer following
$itemQty = isset($_POST['num1']) ? $_POST['num1'] : 0;
$itemCost = isset($_POST['num2']) ? $_POST['num2'] : 0;
$itemSale = isset($_POST['num3']) ? $_POST['num3'] : 0;
$shipMat = isset($_POST['num4']) ? $_POST['num4'] : 0;
$diffPricePercent = (($actual * 100) / $itemCost) / $itemQty;
$itemCost
and $itemQty
are returning null
or zero, check them what they come with to code from user input
also to check if it's not empty data add:
if (!empty($_POST['num1'])) {
$itemQty = $_POST['num1'];
}
and you can check this link for POST validation before using it in variable
https://www.virendrachandak.com/techtalk/php-isset-vs-empty-vs-is_null/
when my divisor has 0 value
if ($divisor == 0) {
$divisor = 1;
}