skip to Main Content

I don’t know why it doesn’t show up anything, I already tested my query and it is working in my phpmyadmin, but in my php code it does not work upon adding the AS keyword. My goal for this is to place a value to a variable coming from the SUM() keyword.

<?php 
require_once "user-connect.php";
$user = $_SESSION['id'];
$sql = "SELECT SUM(total) AS sumz FROM cart WHERE userID = $user AND month(orderDate) = month(now()) AND day(orderDate) = day(now())";
$result = $link->query($sql);
if ($result->num_rows > 0) {
    $row = $result->fetch_assoc();
    echo $row['sumz'];
}  
if (mysqli_query($link, $sql)) {

} else {
    echo "Error: " . $sql . "" . mysqli_error($link);
} ?>
<table cellspacing="0">
    <tbody>
        <tr class="cart-subtotal">
            <th>Cart Subtotal</th>
            <td><span class="amount"><?php echo $row['sumz']; ?></span></td>
        </tr>

2

Answers


  1. You can use:

    $sql = "SELECT SUM(total) FROM cart WHERE..."
    

    And in HTML:

    <td><span class="amount"><?php echo $row['SUM(total)']; ?></span></td>
    
    Login or Signup to reply.
  2. Take a look at PHP fetch assoc guide.

    while ($row = $result->fetch_assoc()) {
        echo $row['sumz'];
    }
    

    An example of getting the SUM value

    <?php 
    $sql="SELECT sum(amount) as total FROM table"; 
    $result = mysqli_query($sql); 
    
    while ($row = mysqli_fetch_assoc($result)) { 
    echo $row['total']; 
    } 
    mysqli_close($con);
     ?>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search