<?php
$sql=mysql_connect("localhost","e5crm.more7.com","5z#JaL");
mysql_select_db("e5crm_more7_com");

$w=$GLOBALS['db']->query("select distinct ee_id,ecmpayment_id from ecmpayments_ecminvoiceouts_rel");
$arr=array();
while($r=$GLOBALS['db']->fetchByAssoc($w)){
	if(in_array($r['ee_id'],$arr))continue;
	if(in_array($r['ecmpayment_id'],$arr))continue;
	$p=array();
	$e=array();
	$total_ee=0;
	$total_p=0;
	$ww=$GLOBALS['db']->query("select ecmpayment_id from ecmpayments_ecminvoiceouts_rel where ee_id='".$r['ee_id']."'");
	while($rr=$GLOBALS['db']->fetchByAssoc($ww)){
		$p[]="id='".$rr['ecmpayment_id']."'";
	}
	$ww=$GLOBALS['db']->query("select ee_id from ecmpayments_ecminvoiceouts_rel where ecmpayment_id='".$r['ecmpayment_id']."'");
	while($rr=$GLOBALS['db']->fetchByAssoc($ww)){
		$e[]="id='".$rr['ee_id']."'";
	}
	$e[]="id='".$r['ee_id']."'";
	$p[]="id='".$r['ecmpayment_id']."'";
	$ww=$GLOBALS['db']->query("select date_entered,total from ecmpayments_ecminvoiceouts where ".implode(" or ",$e));
	while($rr=$GLOBALS['db']->fetchByAssoc($ww))$total_ee+=(float)$rr['total'];	
	$ww=$GLOBALS['db']->query("select date_entered,value from ecmpayments where ".implode(" or ",$p));
	while($rr=$GLOBALS['db']->fetchByAssoc($ww)){$datee=$rr['date_entered'];$total_p+=(float)$rr['value'];}
	if(round(($total_ee-$total_p),2)<0 || round(($total_ee-$total_p),2)>0)
	echo $datee." ".$total_ee."-".$total_p."=".round(($total_ee-$total_p),2)."\n";
}	
echo $total;
mysql_close($sql);
?> 