Jump to content

Difference of 2 sums


robbo5899
Go to solution Solved by Barand,

Recommended Posts

The tables look like this,

 

Donations has ID Name Date Amount

Costs has ID Name Date Payment_to Server Description and Amount

 

This is the code i have so far but it just prints 0 even although there is data in the tables.

<?php
$con = mysql_connect("ipaddress","username","password");
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }
 
mysql_select_db("rwscnnpe_Donations", $con);
 
$cost = 'SELECT sum(amount) FROM costs';
$donations = 'SELECT sum(amount) FROM donations';
$total = $donations - $cost;
echo $total;
?>
Edited by robbo5899
Link to comment
Share on other sites

All you've done is just write out two strings, and try to subtract one from the other. You'll need to actually execute the queries and then fetch the data.

 

If you don't know how to do that, try googling for a basic MySQL/PHP tutorial. Look for one that uses PDO or mysqli_, not mysql_ functions. Also read the manual, the basic examples in there are really all you'll need.

Link to comment
Share on other sites

That's if you're using the MySQL console or a tool like MySQL Workbench or phpMyAdmin.

 

See how you called some functions to connect and select your database? You need the appropriate functions to run your query.

(You'll want to switch to using PDO/mysqli)

Link to comment
Share on other sites

  • Solution

try

$db = mysqli_connect(HOST, USERNAME, PASSWORD, DATABASE); // connect to database

$costSql = 'SELECT sum(amount) FROM costs';         // define the query
$result = mysqli_query($db, $costSql);              // execute the query
$row = mysqli_fetch_row($result);                   // get return row
$costs = $row[0];                                   // get the total

$donationsSql = 'SELECT sum(amount) FROM donations'; // define the query
$result = mysqli_query($db, $donationsSql);         // execute the query
$row = mysqli_fetch_row($result);                   // get return row
$donations = $row[0];                               // get the total

$result = $donations - $costs;
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.