简体   繁体   中英

I have tables name as "expenses" and "orders" i want to get there total separately and then subtract orders total from expenses

Orders Table Total i get by this query:

<?php $res = mysqli_query($conn,'SELECT sum(totalprice) FROM orders');
if (FALSE === $res) die("Select sum failed: ".mysqli_error);
$row = mysqli_fetch_row($res);
$sum = $row[0];
echo $sum;?>

Expenses Table Total i get by this query:

<?php $res = mysqli_query($conn,'SELECT sum(amount) FROM expenses');
if (FALSE === $res) die("Select sum failed: ".mysqli_error);
$row = mysqli_fetch_row($res);
$sum = $row[0];
echo $sum;?>

Now i want to subtract there totals from orders and expenses table. Example Orders Total- Expenses Total

You can do like below if your mentioned sript is working fine:

$resOrder = mysqli_query($conn,'SELECT sum(totalprice) FROM orders');
if (FALSE === $resOrder) die("Select sum failed: ".mysqli_error);
$row = mysqli_fetch_row($resOrder);
$total = $row[0];
echo $orderTotal;

$resExp = mysqli_query($conn,'SELECT sum(amount) FROM expenses');
if (FALSE === $resExp) die("Select sum failed: ".mysqli_error);
$row = mysqli_fetch_row($resExp);
$expensesTotal = $row[0];
echo $expensesTotal ;

Now to get result just do like:

echo $result = $expensesTotal - $orderTotal; 

Please let me know if you are getting any problem.

You are so close. You just need to give your total values different variable names.

<?php 
    $orderRes = mysqli_query($conn,'SELECT sum(totalprice) as orders_total FROM orders');   //Aliases are a beautiful thing to use. In this case I am giving the sum of orders an alias - orders_total
    $row = mysqli_fetch_assoc($orderRes);
    $ordersTotal = $row['orders_total'];

    $res = mysqli_query($conn,'SELECT sum(amount) as expenses_total FROM expenses');
    $row = mysqli_fetch_assoc($res);
    $expensesTotal = $row['expenses_total']

    $diff = $ordersTotal - $expensesTotal;    //Simply substract expensesTotal from ordersTotal
    echo $diff; ?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM