addition - Add values of multiple fields from one table and subtract it to a field from another table in php -


i have 2 tables : contract bill.
contract table contains following fields(contid (pk), contractnumber, quantity, etc..).
bill contains following fields(billid (pk), billno, contid, checkmtr, etc...).

here every contract can have multiple bills. trying add inwmtr of contract , deduct quantity , display final mtrs pending mtr.

here have tried:

<?php  include("dbconnection.php");  $sql1 = mysql_query("select quantity contract contid = '25'"); while($result1  = mysql_fetch_array($sql1)) { //echo "$result1[quantity]"; //echo "<br/>";   //echo "<br/>";  $sql2 = mysql_query("select checkmtr bill contid = '25'"); while($result2  = mysql_fetch_array($sql2)) { //echo "$result2[checkmtr]"; //echo "<br/>";  $a = $result1['quantity'] - $result2['checkmtr']; echo "$a"; echo "<br/>";  } echo "<br/>";  } echo "<br/>"; ?> 

here subtract checkmtr quantity every bill. doesn't add checkmtrs of bills , subtract.

any suggestions?

$sql2 = mysql_query("select sum(checkmtr) checkmtr bill contid = '25'"); if (mysql_num_rows($sql2) == 1) {   $result2  = mysql_fetch_array($sql2);   $a = $result1['quantity'] - $result2['checkmtr']; } else {   $a = $result1['quantity']; } echo $a; 

there's no need while loop after first query. can never return more 1 row, since you're selecting row primary key.

you can combine 1 query:

select quantity - ifnull(sum(checkmtr), 0) result contract c left join bill using (contid) c.contid = '25' 

to contracts, use group by:

select c.contid, quantity - ifnull(sum(checkmtr), 0) result contract c left join bill using (contid) group c.contid 

sqlfiddle


Comments

Popular posts from this blog

ios - iPhone/iPad different view orientations in different views , and apple approval process -

java Extracting Zip file -

C# WinForm - loading screen -