Simple PHP calculator, half working

Discussion in 'PHP' started by philb, Dec 4, 2008.

  1. #1
    Hi Guys

    I have a wrote a very simple php tool and I have it working but it needs two things ironed out and I'm hopng someone can help.

    I have an html form where a user can work out how many packs of laminate flooring it would take to cover the floor.

    A user enters the lenght (x) width (y) and pack size (a) then the php works out how many packs needed, rounds the figure up to a whole number and displays it.

    The php code is

    $total = ($x * $y) / $a;

    but when the page first loads I get an error message 'Warning: Division by zero'

    Can anyone help with this?

    The half working version is at


    http://www.diylaminateflooring.co.uk



    The full PHP looks like

    <form method="post" action="index.php">
    <table width="100%" border="0" class="border">
    <tr>
    <td>Room Width (m) </td>
    <td>Room Length (m) </td>
    <td>Pack Size (eg 2.48) </td>
    <td>&nbsp;</td>
    <td>No. of Packs Required</td>

    </tr>
    <tr>
    <td><input name="width" type="text" maxlength="10"></td>
    <td><input name="length" type="text" maxlength="10"></td>
    <td><input name="packsize" type="text" maxlength="10"></td>
    <td><label><input type="submit" name="Submit" value="Submit" /></label></td>

    <td><?php
    $x = $_POST['width'];
    $y = $_POST['length'];
    $a = $_POST['packsize'];
    $total = ($x * $y) / $a;
    echo ceil("$total") ?></td>
    </tr>
    </table>
    </form>
     
    philb, Dec 4, 2008 IP
  2. bwp58

    bwp58 Peon

    Messages:
    485
    Likes Received:
    14
    Best Answers:
    0
    Trophy Points:
    0
    #2
    First time it goes through nothing has been entered for the packsize so it will = 0 causing the error.

    Try replacing $a = $_POST['packsize'] with

    if(!$_POST['packsize']){$a=1;}else{$a = $_POST['packsize'];};


    Update: did a quick test seems to work ok
     
    bwp58, Dec 4, 2008 IP
  3. ads2help

    ads2help Peon

    Messages:
    2,142
    Likes Received:
    67
    Best Answers:
    1
    Trophy Points:
    0
    #3
    When the page is loaded the $a or $_POST['packsize'] is not assign any value yet, therefore the error occurs.
    replace the bottom part of your script with:

    
    </tr>
    <tr>
    <td><input name="width" type="text" maxlength="10"></td>
    <td><input name="length" type="text" maxlength="10"></td>
    <td><input name="packsize" type="text" maxlength="10"></td>
    <td><label><input type="submit" name="Submit" value="Submit" /></label></td>
    
    <td><?php
    if (isset($_POST['Submit'])) {
    $x = $_POST['width'];
    $y = $_POST['length'];
    $a = $_POST['packsize'];
    $total = ($x * $y) / $a;
    echo ceil("$total");
    }
    ?></td>
    </tr>
    </table>
    </form>
    
    PHP:
     
    ads2help, Dec 4, 2008 IP