Sunday, November 14, 2021

[SOLVED] Getting the TOTAL of the Multiple Fetched data on curl Api

Issue

I am trying to get the total of the multiple Fetched API using curl... THe first fetch was coming from my databas and the second is from API using curl! I Successfuly fetch the data's but my problem is I dont know how to get the total of the sale of! This is my code that I use for succesful fetch. The name are fetched from the database and the datesale and sale are from API

And I want the output to be 310+502+210 The output is [1022]

Name  Datesale   Sale
mike   12-01-19   310
jake   12-09-19   502
jex    12-03-19   210

Below is my sample code!

<table>
<tr>
        <th>Name</th>
        <th>datesale</th>
        <th>sale</th>
    </tr>
        <?php
        $query = 
        "SELECT 
        * 
        FROM 
        user 
        ";
        
        $result = mysqli_query($conn, $query);
        while($row = mysqli_fetch_array($result))
        {
        $id= $row['id'];
        $fname = $row['fname'];
        $lname = $row['lname'];
        $address = $row['address'];
        $userid = $row['userid'];
    
            //* API //
            date_default_timezone_set('Asia/Manila');
            $url = 'api.sample.com/'.$userid;
            $ch=curl_init($url);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            $r=curl_exec($ch);
            curl_close($ch);
            $data = json_decode($r, true);
            $datesale =$data[datesale];
            $sale=$data[sale];
            ?>
           <tr>
            <td><?php echo $fname. " " .$lname;?></td>
            <td class="centralize"><?php echo $datesale;?></td>
            <td class="centralize"><?php echo $sale;?></td>
        <?php } ?> 
        </table> 

Solution

Just add the values together as you go along and output the total at the end.

$result = mysqli_query($conn, $query);
$total = 0;

while($row = mysqli_fetch_array($result))
{
//...
    $sale=$data[sale];
    $total += $sale;
    ?>
...
</table> 

echo "Total: ". $total;


Answered By - ADyson