0
    $query = "SELECT  SUM(amount) FROM income_daily";
    $sum = mysqli_fetch_row(mysqli_query($con, $query));
     echo "Total Income : ". "¢" .$sum[0];

     echo '<br>';
    echo '-';
    echo '<br>';

     $query1 = "SELECT  SUM(amount) FROM expenses_daily";
    $sum = mysqli_fetch_row(mysqli_query($con, $query));
    echo "Total Expenses : ". "¢" .$sum[0];
2
Contributors
1
Reply
11
Views
1 Month
Discussion Span
Last Post by alan.davies
1

There are a few ways you could do this, depending on your needs. Here's a botch-job, but gives a single value based on a date:

SELECT (SELECT COALESCE(SUM(di.`amount`),0) FROM `daily_income` di WHERE di.`income_date` = ?) - (SELECT COALESCE(SUM(de.`amount`),0) FROM `daily_expenses` de WHERE de.`expenses_date` = ?) AS daily_difference

The question marks are anonymous placeholders for use with PDO or mysqli prepared statements - so you will need to bind these parameters (date). But if you want a nice one-liner with date data you have sanitized:

echo $mysqli->query("SELECT (SELECT COALESCE(SUM(di.`amount`),0) FROM `daily_income` di WHERE di.`income_date` = '$date') - (SELECT COALESCE(SUM(de.`amount`),0) FROM `daily_expenses` de WHERE de.`expenses_date` = '$date') AS daily_difference")->fetch_object()->daily_difference; 

Alternatively of course, you could just retrieve both table data sums individually and subtract using php!

BTW - the "coalesce" may be required as SUM gives NULL if no values exist for it - and therefore the difference will also be NULL, regardless of whether the other SUM value is not null.

Edited by alan.davies

Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.