Jump to content

Difference of 2 sums


robbo5899

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;
?>

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.

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)

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;

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.