0

I keep getting this error even though when I view my cart it lists the item and price and then the total price is calculated and returned with the right value. I am not sure what the error is because it lists everything correctly with the product title and it's price. I do know understand why it is say a non-numeric value because the price is listed and the total price is added up correectly.

<!DOCTYPE html>
<html>
<head>
    <title>Cart</title>
</head>
<body>
    <?php 
    session_start();
    require_once('connect.php'); 
    include('cartHead.php'); 
    include('cartNav.php');
    ?>

    <div class="container">
        <?php 
        $items = $_SESSION['cart'];
        $cartitems = explode(",", $items);
        ?>
        <div class="row">
            <table class="table">
                <tr>
                    <th>Item</th>
                    <th>Item Name</th>
                    <th>Price</th>
                </tr>
                <?php
                $total = '';
                $i=1;
                foreach ($cartitems as $key=>$id) {
                    $sql = "SELECT * FROM products WHERE id = $id";
                    $res=mysqli_query($connect, $sql);
                    $r = mysqli_fetch_assoc($res);
                    ?>      
                    <tr>
                        <td><?php echo $i; ?></td>
                        <td><a href="delCart.php?remove=<?php echo $key; ? 
                        >">Remove</a> <?php echo $r['title']; ?></td>
                        <td>$<?php echo $r['price']; ?></td>
                    </tr>
                    <?php 
                    $total = $total + $r['price'];
                    $i++; 
                } 
                ?>
                <tr>
                    <td><strong>Total Price</strong></td>
                    <td><strong>$<?php echo $total; ?></strong></td>
                    <td><a href="#" class="btn btn-info">Checkout</a></td>
                </tr>
            </table>

        </div>

    </div>

    <?php include('cartFooter.php'); ?>

</body>
</html>
Adam Bridge
  • 13
  • 1
  • 4

1 Answers1

1

You are initializing total as a string but your operations treat it like a number. You can either initialize total as follows:

$total = 0;

Or you can cast total to an int (or whichever type you choose)

$total = (int)$total + 5;

To verify my answer, before making the aformentioned modifications add the following line after instantiating total.

var_dump($total)

This will give the type and value of the parameter. While PHP is a loosely type language, I would be very careful implicitly casting variables from non-numeric to numeric ( and visa versa ). One such issue could be percision loss when converting a string to an int if the int value represented by the string is greater than PHP_INT_MAX. Representing money in code is another topic I highly suggest you research.

Chris Maggiulli
  • 3,375
  • 26
  • 39