<?php 
$db = $GLOBALS['db'];

$products = $db->query("SELECT id, code, name FROM ecmproducts WHERE product_active='1'");

while ($product = $db->fetchByAssoc($products)) {
	$price = $db->fetchByAssoc($db->query("
			select (sum(price*quantity)/sum(quantity)) as avg_price from ecmstockstates 
			where product_id='".$product['id']."'"));	
	
	echo $product['code'].'     '.$product['name'].'     '.round($price['avg_price'],2).'<br><br>';
}