AMI PHP Data collector

#!/usr/bin/php
<?php
mysql_connect("localhost","root");
@mysql_select_db(crm) or die( "Unable to select database");

$result=mysql_query("SELECT * FROM asterisk");
$row = mysql_fetch_array($result);

$socket = fsockopen($row['amiip'], 5038, $errnum, $errdesc) or die('Connection to host failed');
fputs($socket, "Action: login\r\n");
fputs($socket, "Username: $row[username]\r\n");
fputs($socket, "Secret: $row[password]\r\n\r\n");
fputs($socket, "Action: Filter\r\n");
fputs($socket, "Operation: Add\r\n");
fputs($socket, "Filter: Event: DialBegin|Event: Newchannel|Event: DialEnd|Event: Hangup|Event: QueueMemberStatus|Event: BlindTransfer\r\n\r\n");

$count=0;
$array = "";
$callvalues = "";
$i=0;
$dialstatus="";

while (!feof($socket)) {
   $wrets = fgets($socket);
  if ($wrets != "\r\n") {
     $array[$count][$i]=str_replace("\r\n","",$wrets);
  //         print $array[$count][$i] . "\n";
     if (preg_match('/SIP|DestChannelStateDesc|DestCallerIDNum|DialStatus|CallerIDNum|Uniqueid|Exten|Linkedid|Cause|Status|Queue/',$array[$count][$i])) {
        $pieces = explode(": ", $array[$count][$i]);
        $j=$pieces[0];
        $callvalues[$j]=$pieces[1];
 //            print $j . " -> " . $callvalues[$j] . "\n";
        if (isset($callvalues['DestChannel'])) {
           $channel=$callvalues['DestChannel'];
        } elseif (isset($callvalues['Channel'])) {
           $channel=$callvalues['Channel'];
        }
        if ($callvalues[$j]=="Up") {
 //               print_r($callvalues);

           if (isset($callvalues['Channel'])) {
              $chansplit=explode("-",$channel);
              $sipsplit=explode("/",$chansplit[0]);
              $data['channel']=$sipsplit[1];

              if ($callvalues['DestCallerIDNum']=="<unknown>") {
                 $data['callerid']=$callvalues['CallerIDNum'];
                 if (isset($callvalues['Status'])) {
                    if ($callvalues['Status']=="2") {
                       $data['queue']=$callvalues['Queue'];
                    }
                  }
              } elseif ($callvalues['Cause-txt']=="Unknown") {
                 $data['callerid']=$callvalues['CallerIDNum'];
              } else {
                 $data['callerid']=$callvalues['DestCallerIDNum'];
              }

              $data['uniqueid']=$callvalues['Uniqueid'];
              unset($data['channelhangup']);
              unset($data['exten']);
              unset($callvalues);
              mysql_query("UPDATE calls SET callerid = '$data[callerid]', uniqueid = '$data[uniqueid]' WHERE extension = '$data[channel]';");
              $str = json_encode($data);
              //echo "data: {$str}\n\n";
           }
        } elseif ($j=="Cause" && $callvalues['Exten'] != "" && $callvalues['Exten'] != "s") {
 //               print_r($callvalues);
           $channelhangup=$callvalues['Channel'];
           $chansplit=explode("-",$channelhangup);
           $sipsplit=explode("/",$chansplit[0]);
           $data['channelhangup']=$sipsplit[1];
           unset($data['channel']);
           unset($data['callerid']);
           unset($data['queue']);
           $data['uniqueid']=$callvalues['Linkedid'];
           $data['exten']=$callvalues['Exten'];
           unset($callvalues);
           mysql_query("UPDATE calls SET callerid = '', uniqueid = '' WHERE extension = '$data[channelhangup]';");
           $str = json_encode($data);
           //echo "data: {$str}\n\n";
        } elseif ($j=="Extension") {
//               print_r($callvalues);
           $channelhangup=$callvalues['TransfererChannel'];
           $chansplit=explode("-",$channelhangup);
           $sipsplit=explode("/",$chansplit[0]);
           $data['channelhangup']=$sipsplit[1];
           unset($data['channel']);
           unset($data['callerid']);
           unset($data['queue']);
           $data['uniqueid']=$callvalues['TransfererLinkedid'];
           unset($callvalues);
           mysql_query("UPDATE calls SET callerid = '', uniqueid = '' WHERE extension = '$data[channelhangup]';");
           $str = json_encode($data);
           //echo "data: {$str}\n\n";
        }
     } 
     $i++;
  } else {
     $i=0;
     $count++; 
//         print "-----------\n";
  }
}
fclose($socket);
?>

I am using the following code to collect data on calls being made and received via the AMI. I will like to have any input input or suggestions to clean up the code or even improve it?

This is PHP task and not an Asterisk task, but please at least document your code to understand easily what your code does, or describe the idea of you code beside update the DB with Asterisk AMI event information