Concurrent calls script

Hi everyone. I need a little help with this idea of making graphs about how many concurrent calls are made on each SIP channel during an hour. To do this, i store the asterisk cdr in a mysql database with the always useful import.php found at
Then, i run this self-made script:

require ("./phplot/phplot.php");

$dbhost = "XXX";
$dbuser = "XXX";
$dbpass = "XXX";

$dbconnect = mysql_connect($dbhost, $dbuser, $dbpass)
        or die("Connessione non riuscita: " . mysql_error());

mysql_select_db("CDR_AST") or die('Could not select database.');

$data = array();
$carriers = array("A","B","C","D");
$X = "'2007-12-13 07:00:00'";
$OFFSET = 60;
$end = 60;

$totalcalls = 0;

for ($i=0; $i<$end; $i++) {
	$row = array();
	$row[] = '';
	$row[] = $i;
	foreach ($carriers as $key=>$value) {
		AND calldate <= ($X + INTERVAL $i MINUTE) 
		AND (calldate + INTERVAL billsec SECOND) > ($X + INTERVAL $i MINUTE)
		AND dstchannel LIKE '%$value%'
		$calls4carrier4minute = mysql_num_rows(mysql_query($sql));
		$row[] = $calls4carrier4minute;
		$totalcalls += $calls4carrier4minute;
	$row[] = $totalcalls;
	$data[$i] = $row;
	$totalcalls = 0;

$plot = new PHPlot(800, 480);

$plot->SetDataColors(array('red', 'green', 'blue','yellow','magenta'));

# Main plot title:
$plot->SetTitle("Chiamate per carrier del $X");

# Make a legend for the 2 functions:
$carriers[] = "Tot. chiamate";


$plot->SetYTitle("Chiamate contemp.");



This script (that clearly requires the phplot library) interrogates the db about how many concurrent calls are in action during minute 1, minute 2, minute 3 ecc ecc starting from 07:00:00 of the 12 December. The problem is: rhis script is really heavy, with a lot of queries… Any idea about?!?

PS I take no responsability for any crash made on your computer from thi script!!!