PHP Warning: Division by zero

后端 未结 8 1224
温柔的废话
温柔的废话 2020-12-20 14:46

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

相关标签:
8条回答
  • 2020-12-20 15:05

    try this

    if(isset($itemCost) != '' && isset($itemQty) != '')
    {
        $diffPricePercent = (($actual * 100) / $itemCost) / $itemQty;
    }
    else
    {
        echo "either of itemCost or itemQty are null";
    }
    
    0 讨论(0)
  • 2020-12-20 15:07

    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 ;
    }
    
    0 讨论(0)
  • 2020-12-20 15:09

    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

    0 讨论(0)
  • 2020-12-20 15:19

    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;
    
    0 讨论(0)
  • 2020-12-20 15:21
    $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/

    0 讨论(0)
  • 2020-12-20 15:21

    when my divisor has 0 value

    if ($divisor == 0) {
        $divisor = 1;
    }
    
    0 讨论(0)
提交回复
热议问题