More MySQL purging
More MySQL purging

file:a/about.php -> file:b/about.php
--- a/about.php
+++ b/about.php
@@ -1,25 +1,24 @@
 <?php

-

-

 include('./lib/common.inc.php');

 include_header("Map");

 ?>

 

 <div class="msg_list">

-<p class="msg_head">Header-1 </p>

-<div class="msg_body">

-orem ipsum dolor sit amet, consectetuer adipiscing elit orem ipsum dolor sit amet, consectetuer adipiscing elit

+    <p class="msg_head">Header-1 </p>

+    <div class="msg_body">

+        orem ipsum dolor sit amet, consectetuer adipiscing elit orem ipsum dolor sit amet, consectetuer adipiscing elit

+    </div>

+    <p class="msg_head">Header-2</p>

+    <div class="msg_body">

+        orem ipsum dolor sit amet, consectetuer adipiscing elit orem ipsum dolor sit amet, consectetuer adipiscing elit

+    </div>

+    <p class="msg_head">Header-3</p>

+    <div class="msg_body">

+        orem ipsum dolor sit amet, consectetuer adipiscing elit orem ipsum dolor sit amet, consectetuer adipiscing elit

+    </div>

 </div>

-<p class="msg_head">Header-2</p>

-<div class="msg_body">

-orem ipsum dolor sit amet, consectetuer adipiscing elit orem ipsum dolor sit amet, consectetuer adipiscing elit

-</div>

-<p class="msg_head">Header-3</p>

-<div class="msg_body">

-orem ipsum dolor sit amet, consectetuer adipiscing elit orem ipsum dolor sit amet, consectetuer adipiscing elit

-</div>

-</div>

-<?php CNDistributionGraph(); 

+<?php

+CNDistributionGraph();

 // select distinct cnid, "publishDate" from (select ("CNID" - MOD("CNID",100)) as cnid from contractnotice where "CNID" < 999999) as a, contractnotice where a.cnid = contractNotice."CNID" order by cnid

 ?>

 

@@ -35,29 +34,25 @@
 FROM contractnotice WHERE "childCN" is null AND "parentCN" is null AND DATE("importDate") = (select * from (SELECT DATE("importDate") 

 FROM contractnotice ORDER BY "importDate" DESC limit 1) alias) GROUP BY DATE("importDate")';

 $query = $conn->prepare($query);

-	$query->execute();

-	if (!$query) {

-		databaseError($conn->errorInfo());

-	}

+$query->execute();

+databaseError($conn->errorInfo());

 echo "<div>";

 $stats = $query->fetch(PDO::FETCH_ASSOC);

-echo $stats["count"] . " new records in period " . $stats["start"] . "  to " . $stats["end"] ."<br>";

+echo $stats["count"] . " new records in period " . $stats["start"] . "  to " . $stats["end"] . "<br>";

 

 

 $query = 'SELECT DATE("importDate") as importday, count(*) as count, min("publishDate") as start, max("publishDate") as end 

 FROM contractnotice WHERE ("childCN" is not null OR "parentCN" is not null) AND DATE("importDate") = (select * from (SELECT DATE("importDate") 

 FROM contractnotice ORDER BY "importDate" DESC limit 1) alias) GROUP BY DATE("importDate")';

 $query = $conn->prepare($query);

-	$query->execute();

-	if (!$query) {

-		databaseError($conn->errorInfo());

-	}

+$query->execute();

+databaseError($conn->errorInfo());

 echo "<div>";

-$stats =  $query->fetch(PDO::FETCH_ASSOC);

-echo $stats["count"] . " updated records in period " . $stats["start"] . "  to " . $stats["end"] ."<br>";

+$stats = $query->fetch(PDO::FETCH_ASSOC);

+echo $stats["count"] . " updated records in period " . $stats["start"] . "  to " . $stats["end"] . "<br>";

 

 

-echo "Last updated: ". $stats["importday"]."<br>";

+echo "Last updated: " . $stats["importday"] . "<br>";

 /* Check for null Procurement method and 0 ABN when not ABN exempt */

 

 


--- a/admin/linkAmendments.php
+++ b/admin/linkAmendments.php
@@ -5,9 +5,7 @@
 c."parentCN" > 0 AND p."childCN" IS NULL ';
 $query = $conn->prepare($query);
 	$query->execute();
-	if (!$query) {
 		databaseError($conn->errorInfo());
-	}
 foreach ($query->fetchAll() as $row) {
   $conn->exec('UPDATE contractnotice SET "childCN" = \'' .
 			 $row['CNID'] . '\' where "CNID" = \'' .
@@ -36,9 +34,7 @@
 GROUP BY "parentCN" having count(*) > 1';
 $query = $conn->prepare($query);
 	$query->execute();
-	if (!$query) {
 		databaseError($conn->errorInfo());
-	}
 foreach ($query->fetchAll() as $row) {
 	$cnids = explode(",",str_replace(Array("{","}"),"",$row['array_agg']));
 	$last_cnid = array_pop($cnids);

--- a/admin/updateReport.php
+++ b/admin/updateReport.php
@@ -1,30 +1,24 @@
 <?php

-include_once("../lib/common.inc.php");

-$query = "SELECT DATE(importDate) as importday, count(*) as count, min(publishDate) as start, max(publishDate) as end 

-FROM `contractnotice` WHERE childCN is null AND parentCN is null AND DATE(importDate) in (select * from (SELECT DATE(importDate) 

-FROM `contractnotice` ORDER BY `importDate` DESC limit 1) alias)";

-$result = mysql_query($query);

-$stats = mysql_fetch_array($result, MYSQL_BOTH);

-echo $stats["count"] . " new records in period " . $stats["start"] . "  to " . $stats["end"] ."<br>";

+include_once('../lib/common.inc.php');

+$query = 'SELECT DATE("importDate") as importday, count(*) as count, min("publishDate") as start, max("publishDate") as end 

+FROM contractnotice WHERE "childCN" is null AND "parentCN" is null AND DATE("importDate") in (select * from (SELECT DATE("importDate") 

+FROM contractnotice ORDER BY "importDate" DESC limit 1) alias)';

+    $result = $conn->query($query);

+    $stats = $result->fetch();

+echo $stats['count'] . ' new records in period ' . $stats['start'] . '  to ' . $stats['end'] .'<br>';

 

-$query = "SELECT DATE(importDate) as importday, count(*) as count, min(publishDate) as start, max(publishDate) as end 

-FROM `contractnotice` WHERE (childCN is not null OR parentCN is not null) AND DATE(importDate) in (select * from (SELECT DATE(importDate) 

-FROM `contractnotice` ORDER BY `importDate` DESC limit 1) alias)";

-$result = mysql_query($query);

-$stats = mysql_fetch_array($result, MYSQL_BOTH);

-echo $stats["count"] . " updated records in period " . $stats["start"] . "  to " . $stats["end"] ."<br>";

+$query = 'SELECT DATE("importDate") as importday, count(*) as count, min("publishDate") as start, max("publishDate") as end 

+FROM contractnotice WHERE ("childCN" is not null OR "parentCN" is not null) AND DATE("importDate") in (select * from (SELECT DATE("importDate") 

+FROM contractnotice ORDER BY importDate DESC limit 1) alias)';

+    $result = $conn->query($query);

+    $stats = $result->fetch();

+echo $stats['count'] . ' updated records in period ' . $stats['start'] . '  to ' . $stats['end'] .'<br>';

 

-$query = "SELECT count(*) as count FROM `agency` WHERE `abn` = '0'";

-$result = mysql_query($query);

-$stats = mysql_fetch_array($result, MYSQL_BOTH);

-echo $stats["count"] . " agencies with no ABN<br>";

+$query = 'SELECT count(*) as count FROM agency WHERE abn = \'0\'';

+    $result = $conn->query($query);

+    $stats = $result->fetch();

+echo $stats['count'] . ' agencies with no ABN<br>';

 

-/*$query = "SELECT count(*) as count FROM `supplierdetails` WHERE `supplierABN` = '0' and supplierCountry LIKE 'Australia'";

-$result = mysql_query($query);

-$stats = mysql_fetch_array($result, MYSQL_BOTH);

-echo $stats["count"] . " Australian suppliers with no ABN<br>";*/

-

-

-echo "Last updated: ". $stats["importdate"]."<br>";

+echo 'Last updated: '. $stats['importdate'].'<br>';

 ?>

 

--- a/displayAgency.php
+++ b/displayAgency.php
@@ -1,42 +1,41 @@
 <?php

+

 include_once ("./lib/common.inc.php");

 if ($_REQUEST['agency']) {

-    

-include_header("Agency");

-  $agency = htmlentities(strip_tags($_REQUEST['agency']));

-  MethodCountGraph($agency);

-  CnCGraph($agency);

-  MethodValueGraph($agency);

-  /*biggest contracts

-  spending by year

-  spending by industry/category

-  spending by supplier

-  

-  spread procurement methods (stacked bar graph)

-  + percent consultancies + percent confidential (bar graph)

 

- Average value by procurement type

-  

-  --- info

-  website, procurement plan, annual reports

-  Breakdown of divisions/branches

-  Breakdown percentage,number,value by procurement type

-  Histograph, overlaying number value reported per week over X years

-  Compliance statistics: amendments, delay in reporting average and number completely late*/

-  

+    include_header("Agency");

+    $agency = htmlentities(strip_tags($_REQUEST['agency']));

+    MethodCountGraph($agency);

+    CnCGraph($agency);

+    MethodValueGraph($agency);

+    /* biggest contracts

+      spending by year

+      spending by industry/category

+      spending by supplier

+

+      spread procurement methods (stacked bar graph)

+      + percent consultancies + percent confidential (bar graph)

+

+      Average value by procurement type

+

+      --- info

+      website, procurement plan, annual reports

+      Breakdown of divisions/branches

+      Breakdown percentage,number,value by procurement type

+      Histograph, overlaying number value reported per week over X years

+      Compliance statistics: amendments, delay in reporting average and number completely late */

+

     $query = 'SELECT "CNID", "description", "value", "agencyName", "category",

     "contractStart", "supplierName"

     FROM contractnotice

     WHERE "agencyName" = :agency

     ORDER BY "value" DESC';

-$query = $conn->prepare($query);

-$query->bindParam(":agency", $agency);

-	$query->execute();

-	if (!$query) {

-		databaseError($conn->errorInfo());

-	}

+    $query = $conn->prepare($query);

+    $query->bindParam(":agency", $agency);

+    $query->execute();

+    databaseError($conn->errorInfo());

 

-  echo "<table>  <thead>

+    echo "<table>  <thead>

     <tr>

       <th>Contract Notice Number</th>

       <th>Contract Description</th>

@@ -46,46 +45,44 @@
       <th>Supplier</th>

     </tr>

   </thead>";

-  foreach ($query->fetchAll() as $row) {

-    setlocale(LC_MONETARY, 'en_US');

-    $value = number_format(doubleval($row['value']) , 2);

-    echo ("<tr>

+    foreach ($query->fetchAll() as $row) {

+        setlocale(LC_MONETARY, 'en_US');

+        $value = number_format(doubleval($row['value']), 2);

+        echo ("<tr>

     <td><a href=\"displayContract.php?CNID={$row['CNID']}\">{$row['CNID']}</a></td>

     <td><b>{$row['description']}</b></a></td>

     <td>\$$value</td><td>{$row['agencyName']}</td>

     <td>{$row['contractStart']}</td>

     <td>{$row['supplierName']}</td>

     </tr>");

-  }

-  echo "</table>";

+    }

+    echo "</table>";

 } else {

     /*

-     split by portfolio

-    */

-include_header("Agencies");

-agenciesGraph();

-  $query = 'SELECT SUM("value"), "agencyName"

+      split by portfolio

+     */

+    include_header("Agencies");

+    agenciesGraph();

+    $query = 'SELECT SUM("value"), "agencyName"

 FROM contractnotice

 WHERE "childCN" is null 

 GROUP BY "agencyName" ';

-$query = $conn->prepare($query);

-	$query->execute();

-	if (!$query) {

-		databaseError($conn->errorInfo());

-	}

-  echo "<table>  <thead>

+    $query = $conn->prepare($query);

+    $query->execute();

+    databaseError($conn->errorInfo());

+    echo "<table>  <thead>

     <tr>

       <th>Agency</th>

       <th>Total Contracts Value</th>

     </tr>

   </thead>";

-  foreach ($query->fetchAll() as $row) {

-    setlocale(LC_MONETARY, 'en_US');

-    $value = number_format(doubleval($row[0]) , 2);

-    $agency = stripslashes($row[1]);

-    echo ("<tr><td><b><a href=\"displayAgency.php?agency={$agency}\">{$agency}</a></b></td><td>\$$value</td></tr>\n");

-  }

-  echo "</table>";

+    foreach ($query->fetchAll() as $row) {

+        setlocale(LC_MONETARY, 'en_US');

+        $value = number_format(doubleval($row[0]), 2);

+        $agency = stripslashes($row[1]);

+        echo ("<tr><td><b><a href=\"displayAgency.php?agency={$agency}\">{$agency}</a></b></td><td>\$$value</td></tr>\n");

+    }

+    echo "</table>";

 }

 include_footer();

 ?>


--- a/displayAmendments.php
+++ b/displayAmendments.php
@@ -1,10 +1,14 @@
 <?php

+

 include_once ("./lib/common.inc.php");

-    include_header("Amendments");

-$query = "select CNID, description, value, pvalue, (value - pvalue) as diff from contractnotice, (SELECT CNID as cn, childCN as ccn, value as pvalue FROM contractnotice where childCN is not null) a".

-" where ".$agencyQ.$yearQ."CNID = ccn AND (value - pvalue) <> 0 order by diff DESC";

-$result = mysql_query($query);

-  echo "<table>  <thead>

+include_header("Amendments");

+$query = 'select "CNID", description, value, pvalue, (value - pvalue) as diff from contractnotice, 

+    (SELECT "CNID" as cn, "childCN" as ccn, value as pvalue FROM contractnotice where "childCN" is not null) a' .

+        ' where ' . $agencyQ . $yearQ . ' "CNID" = ccn AND (value - pvalue) <> 0 order by diff DESC';

+$query = $conn->prepare($query);

+$query->execute();

+databaseError($conn->errorInfo());

+echo "<table>  <thead>

     <tr>

       <th>Contract</th>

       <th>Original Value</th>

@@ -12,21 +16,17 @@
     <th>Difference</th>

     </tr>

   </thead>";

-if ($result) {

-while ($row = mysql_fetch_array($result, MYSQL_BOTH)) {

-  setlocale(LC_MONETARY, 'en_US');

-  $value = number_format(doubleval($row['value']) , 2);

-  $pvalue = number_format(doubleval($row['pvalue']) , 2);

-  $diff = number_format(doubleval($row['diff']) , 2);

-  echo ("<tr>");

-  echo "<td><A href=\"displayContract.php?CNID={$row['CNID']}\"><b>{$row['description']}</b></a></td>";

-  echo "<td>\$$pvalue</td><td>\$$value</td><td>\$$diff</td></tr>";

+foreach ($query->fetchAll() as $row) {

+    setlocale(LC_MONETARY, 'en_US');

+    $value = number_format(doubleval($row['value']), 2);

+    $pvalue = number_format(doubleval($row['pvalue']), 2);

+    $diff = number_format(doubleval($row['diff']), 2);

+    echo ("<tr>");

+    echo "<td><A href=\"displayContract.php?CNID={$row['CNID']}\"><b>{$row['description']}</b></a></td>";

+    echo "<td>\$$pvalue</td><td>\$$value</td><td>\$$diff</td></tr>";

 }

-} else {

-echo mysql_error();

-}

+

 echo "</table>";

-mysql_free_result($result);

 include_footer();

 ?>

 

--- a/displayCalendar.php
+++ b/displayCalendar.php
@@ -1,30 +1,29 @@
 <?php

+

 include_once("./lib/common.inc.php");

 

 include_header("Months and Years");

 

 if ($_REQUEST['month']) {

-    echo "<center><h1>".$_REQUEST['month']."</h1></center>";

-$monthParts = explode("-",$_REQUEST['month']);

-  $query = 'SELECT "CNID", "description", "value", "agencyName", "category", "contractStart", "supplierName"

+    echo "<center><h1>" . $_REQUEST['month'] . "</h1></center>";

+    $monthParts = explode("-", $_REQUEST['month']);

+    $query = 'SELECT "CNID", "description", "value", "agencyName", "category", "contractStart", "supplierName"

     FROM contractnotice

     WHERE "childCN" is null

     AND extract(year from "contractStart") = :year

     AND extract(month from "contractStart")  = :month

     ORDER BY value DESC';

-$query = $conn->prepare($query);

-$query->bindParam(":month",  $monthParts[0]);

+    $query = $conn->prepare($query);

+    $query->bindParam(":month", $monthParts[0]);

 

-$query->bindParam(":year",  $monthParts[1]);

-  $query->execute();

-  if (!$query) {

+    $query->bindParam(":year", $monthParts[1]);

+    $query->execute();

     databaseError($conn->errorInfo());

-  }

 

-MethodCountGraph($supplier);

-CnCGraph($supplier);

+    MethodCountGraph($supplier);

+    CnCGraph($supplier);

 

-  echo "<table>  <thead>

+    echo "<table>  <thead>

     <tr>

       <th>Contract Notice Number</th>

       <th>Contract Description</th>

@@ -34,55 +33,51 @@
       <th>Supplier</th>

     </tr>

   </thead>";

-  foreach ($query->fetchAll() as $row) {

-    setlocale(LC_MONETARY, 'en_US');

-    $value = number_format(doubleval($row['value']) , 2);

-    echo ("<tr>

+    foreach ($query->fetchAll() as $row) {

+        setlocale(LC_MONETARY, 'en_US');

+        $value = number_format(doubleval($row['value']), 2);

+        echo ("<tr>

     <td><a href=\"displayContract.php?CNID={$row['CNID']}\">{$row['CNID']}</a></td>

     <td><b>{$row['description']}</b></a></td>

     <td>\$$value</td><td>{$row['agencyName']}</td>

     <td>{$row['contractStart']}</td>

     <td>{$row['supplierName']}</td>

     </tr>");

-  }

-  echo "</table>";

-  mysql_free_result($result);

+    }

+    echo "</table>";

 } else {

-/*

-     split by year

-todo:

-Year/Month drilldown - largest contracts, agencies, suppliers

-count per month

-big picture graphs?*/

+    /*

+      split by year

+      todo:

+      Year/Month drilldown - largest contracts, agencies, suppliers

+      count per month

+      big picture graphs? */

 

 

-echo '<img src="graphs/displayContractStartingGraph.php">';

-echo '<img src="graphs/displayContractPublishedGraph.php">';

+    echo '<img src="graphs/displayContractStartingGraph.php">';

+    echo '<img src="graphs/displayContractPublishedGraph.php">';

 

 

-$query = 'SELECT extract(year from "contractStart"), extract(month from "contractStart"),

+    $query = 'SELECT extract(year from "contractStart"), extract(month from "contractStart"),

 SUM(value) as val, count(1) as count FROM contractnotice WHERE "childCN" is null GROUP BY extract(year from "contractStart"), extract(month from "contractStart") ORDER BY extract(year from "contractStart"), extract(month from "contractStart") ';

-$query = $conn->prepare($query);

-  $query->execute();

-  if (!$query) {

+    $query = $conn->prepare($query);

+    $query->execute();

     databaseError($conn->errorInfo());

-  }

 

-  echo "<table>  <thead>

+    echo "<table>  <thead>

     <tr>

       <th>Month/Year</th>

       <th>Total Contracts Value</th>

       <th>Number of Contracts</th>

     </tr>

   </thead>";

-  foreach ($query->fetchAll() as $row) {

-setlocale(LC_MONETARY, 'en_US');

-$value = number_format(doubleval($row["val"]),2);

-$month_name = date( 'F', mktime(0, 0, 0, $row[1]) );

-    echo ("<tr><td><b><a href=\"?month=$row[1]-$row[0]\">$month_name {$row[0]}</a></b></td><td>\$$value</td><td>({$row['count']} contracts)</td></tr>");

-}

-echo "</table>";

-mysql_free_result($result);

+    foreach ($query->fetchAll() as $row) {

+        setlocale(LC_MONETARY, 'en_US');

+        $value = number_format(doubleval($row["val"]), 2);

+        $month_name = date('F', mktime(0, 0, 0, $row[1]));

+        echo ("<tr><td><b><a href=\"?month=$row[1]-$row[0]\">$month_name {$row[0]}</a></b></td><td>\$$value</td><td>({$row['count']} contracts)</td></tr>");

+    }

+    echo "</table>";

 }

 include_footer();

 ?>


--- a/displayCategory.php
+++ b/displayCategory.php
@@ -3,12 +3,16 @@
 if ($_REQUEST['category']) {

     include_header("Category");

     echo "<center><h1>".$_REQUEST['category']."</h1></center>";

-  $query = "SELECT CNID, description, value, agencyName, category, contractStart, supplierName

-    FROM `contractnotice`

-    WHERE childCN is null 

-    AND category = '" . $_REQUEST['category'] . "'

-    ORDER BY value DESC";

-  $result = mysql_query($query);

+  $query = 'SELECT "CNID", description, value, "agencyName", category, "contractStart", "supplierName"

+    FROM contractnotice

+    WHERE "childCN" is null 

+    AND category = :category

+    ORDER BY value DESC';

+$query = $conn->prepare($query);

+$query->bindParam(":category", $_REQUEST['category']);

+	$query->execute();

+		databaseError($conn->errorInfo());

+	

     echo "<table>  <thead>

     <tr>

       <th>Contract Notice Number</th>

@@ -19,7 +23,7 @@
       <th>Supplier</th>

     </tr>

   </thead>";

-  while ($row = mysql_fetch_array($result, MYSQL_BOTH)) {

+  foreach ($query->fetchAll() as $row) {

     setlocale(LC_MONETARY, 'en_US');

     $value = number_format(doubleval($row['value']) , 2);

     echo ("<tr>

@@ -31,30 +35,30 @@
     </tr>");

   }

   echo "</table>";

-  mysql_free_result($result);

 } else {

     /*

      split by main categories

     */

     include_header("Categories");

-$query = "SELECT sum(value), category

-FROM `contractnotice`

-WHERE childCN is null

-GROUP BY category ORDER BY sum(value) DESC ";

-$result = mysql_query($query);

+$query = 'SELECT sum(value), category

+FROM contractnotice

+WHERE "childCN" is null

+GROUP BY category ORDER BY sum(value) DESC ';

+$query = $conn->prepare($query);

+	$query->execute();

+		databaseError($conn->errorInfo());

   echo "<table>  <thead>

     <tr>

       <th>Category</th>

       <th>Total Contracts Value</th>

     </tr>

   </thead>";

-while ($row = mysql_fetch_array($result, MYSQL_BOTH)) {

+  foreach ($query->fetchAll() as $row) {

   setlocale(LC_MONETARY, 'en_US');

   $value = number_format(doubleval($row[0]) , 2);

   echo ("<tr><td><A href=\"displayCategory.php?category={$row[1]}\"><b>{$row[1]}</b></a></td><td>\$$value</td></tr>");

 }

 echo "</table>";

-mysql_free_result($result);

 }

 include_footer();

 ?>

--- a/displayConfidentialities.php
+++ b/displayConfidentialities.php
@@ -14,16 +14,17 @@
 FROM `contractnotice`
 GROUP BY procurementMethod ";
 
-$result = mysql_query($query);
+    $query = $conn->prepare($query);
+    $query->execute();
+    databaseError($conn->errorInfo());
 
 echo "<table>";
-while ($row = mysql_fetch_array($result, MYSQL_BOTH)) {
+    foreach ($query->fetchAll() as $row) {
 setlocale(LC_MONETARY, 'en_US');
 $value = number_format(doubleval($row[0]),2);
     echo ("<tr><td><b>{$row[1]}</b></td><td>\$$value</td></tr>");
 }
 echo "</table>";
-mysql_free_result($result);
 include_footer();
 ?>
 

--- a/displayConsultancies.php
+++ b/displayConsultancies.php
@@ -14,16 +14,18 @@
 FROM `contractnotice`
 GROUP BY procurementMethod ";
 
-$result = mysql_query($query);
+
+    $query = $conn->prepare($query);
+    $query->execute();
+    databaseError($conn->errorInfo());
 
 echo "<table>";
-while ($row = mysql_fetch_array($result, MYSQL_BOTH)) {
+    foreach ($query->fetchAll() as $row) {
 setlocale(LC_MONETARY, 'en_US');
 $value = number_format(doubleval($row[0]),2);
     echo ("<tr><td><b>{$row[1]}</b></td><td>\$$value</td></tr>");
 }
 echo "</table>";
-mysql_free_result($result);
 include_footer();
 ?>
 

--- a/displayContract.php
+++ b/displayContract.php
@@ -8,44 +8,40 @@
 

 $query = $conn->prepare($query);

 $query->bindParam(":CNID", $_REQUEST['CNID']);

-  $query->execute();

-  if (!$query) {

-    databaseError($conn->errorInfo());

-  }

-  foreach ($query->fetchAll(PDO::FETCH_ASSOC) as $row) {

-setlocale(LC_MONETARY, 'en_US');

-foreach (array_filter($row) as $key => $value) {

-	echo "<b>$key</b>&nbsp;";

-switch ($key) {

-case "supplierName":

-case "supplierABN":

-	echo '<a href="displaySupplier.php?supplier='.$row['supplierABN'].'-'.urlencode($row['supplierName']).'">'.$value."</a>";

-	break;

-case "agencyName":

-	echo '<a href="displayAgency.php?agency='.urlencode($value).'">'.$value."</a>";

-	break;

-case "value":

-	echo "$".number_format(doubleval($value),2);

-	break;

-default:

-	echo str_replace("  ","<br>",$value);

+$query->execute();

+databaseError($conn->errorInfo());

+foreach ($query->fetchAll(PDO::FETCH_ASSOC) as $row) {

+    setlocale(LC_MONETARY, 'en_US');

+    foreach (array_filter($row) as $key => $value) {

+        echo "<b>$key</b>&nbsp;";

+        switch ($key) {

+            case "supplierName":

+            case "supplierABN":

+                echo '<a href="displaySupplier.php?supplier=' . $row['supplierABN'] . '-' . urlencode($row['supplierName']) . '">' . $value . "</a>";

+                break;

+            case "agencyName":

+                echo '<a href="displayAgency.php?agency=' . urlencode($value) . '">' . $value . "</a>";

+                break;

+            case "value":

+                echo "$" . number_format(doubleval($value), 2);

+                break;

+            default:

+                echo str_replace("  ", "<br>", $value);

+        }

+        echo "<br>";

+    }

 }

-echo "<br>";

-}

-}

-echo '<br><a href="https://www.tenders.gov.au/?event=public.advancedsearch.keyword&keyword=CN'.$_REQUEST['CNID'].'"> View original record @ tenders.gov.au</a><br>';

+echo '<br><a href="https://www.tenders.gov.au/?event=public.advancedsearch.keyword&keyword=CN' . $_REQUEST['CNID'] . '"> View original record @ tenders.gov.au</a><br>';

 

 

 $query = 'SELECT * FROM `heuristic_results` where "CNID" = :CNID';

 $query = $conn->prepare($query);

-$agencyName = $input.'%';

+$agencyName = $input . '%';

 $query->bindParam(":CNID", $_REQUEST['CNID']);

-  $query->execute();

-  if (!$query) {

-    databaseError($conn->errorInfo());

-  }

-  foreach ($query->fetchAll() as $r) {

-	echo "<b>{$r['heuristic_name']}</b>: {$r['heuristic_value']} (raw value: {$r['raw_value']}, mean: {$r['mean']}, stddev: {$r['stddev']})<br>";

+$query->execute();

+databaseError($conn->errorInfo());

+foreach ($query->fetchAll() as $r) {

+    echo "<b>{$r['heuristic_name']}</b>: {$r['heuristic_value']} (raw value: {$r['raw_value']}, mean: {$r['mean']}, stddev: {$r['stddev']})<br>";

 }

 

 include_footer();


--- a/displayHeatmap.php
+++ b/displayHeatmap.php
@@ -1,5 +1,4 @@
 <?php

-

 

 include('lib/common.inc.php');

 

@@ -28,72 +27,70 @@
 

 $query = 'SELECT "supplierPostcode", sum("value") as value, max(lat) as lat, max(lon) as lon FROM contractnotice inner join postcodes on "supplierPostcode" = postcode::text where "childCN" is null AND "supplierCountry" = \'Australia\' GROUP BY "supplierPostcode"';

 $query = $conn->prepare($query);

-   $query->execute();

-   if (!$query) {

-      databaseError($conn->errorInfo());

-   }

+$query->execute();

+databaseError($conn->errorInfo());

 

 

 $left = "FFFF50";

-$right= "EF0050";

-$leftR = hexdec(substr($left,0,2));

-$leftG = hexdec(substr($left,2,2));

-$leftB = hexdec(substr($left,4,2));

-$rightR = hexdec(substr($right,0,2));

-$rightG = hexdec(substr($right,2,2));

-$rightB = hexdec(substr($right,4,2));

-for($i=0;$i<250;$i++) {

-    $colorset[$i] = imagecolorallocatealpha($handle, $leftR + ($i*(($rightR-$leftR)/250)), $leftG + ($i*(($rightG-$leftG)/250)), $leftB + ($i*(($rightB-$leftB)/250)),117 - ($i/250)*40);

+$right = "EF0050";

+$leftR = hexdec(substr($left, 0, 2));

+$leftG = hexdec(substr($left, 2, 2));

+$leftB = hexdec(substr($left, 4, 2));

+$rightR = hexdec(substr($right, 0, 2));

+$rightG = hexdec(substr($right, 2, 2));

+$rightB = hexdec(substr($right, 4, 2));

+for ($i = 0; $i < 250; $i++) {

+    $colorset[$i] = imagecolorallocatealpha($handle, $leftR + ($i * (($rightR - $leftR) / 250)), $leftG + ($i * (($rightG - $leftG) / 250)), $leftB + ($i * (($rightB - $leftB) / 250)), 117 - ($i / 250) * 40);

 }

 

-  foreach ($query->fetchAll() as $row) {

-   $xpage = round((($XRange - ($MaxX - $row['lon'])) / $xdivlength));

-	if ($row['lat'] < -40.25) $row['lat']-= 0.75;

-   $ypage = round(($YRange - (abs($MaxY) - abs($row['lat']))) / $ydivheight);

-   @$pagevalues[$xpage][$ypage] += $row['value'];

-   //echo $ypage." ".$xpage."<br>";

+foreach ($query->fetchAll() as $row) {

+    $xpage = round((($XRange - ($MaxX - $row['lon'])) / $xdivlength));

+    if ($row['lat'] < -40.25)

+        $row['lat']-= 0.75;

+    $ypage = round(($YRange - (abs($MaxY) - abs($row['lat']))) / $ydivheight);

+    @$pagevalues[$xpage][$ypage] += $row['value'];

+    //echo $ypage." ".$xpage."<br>";

 }

 

 $max = 0;

 $min = 0;

-for ($i = 0;$i < $xdivs; $i++ ) {

-   for ($j = 0;$j < $ydivs; $j++ ) {

-   if (@$pagevalues[$i][$j])

-   {

-      if (@$pagevalues[$i][$j] > $max) $max = @$pagevalues[$i][$j];

-      if ($min == 0 || @$pagevalues[$i][$j] < $min) $min = @$pagevalues[$i][$j];

-   } else {

-      @$pagevalues[$i][$j] = ((@$pagevalues[$i][$j] + (@$pagevalues[$i+1][$j] + @$pagevalues[$i][$j+1]

-                           + @$pagevalues[$i-1][$j] + @$pagevalues[$i][$j-1])/4) /2)-9;

-      @$pagevalues[$i-1][$j] = ((@$pagevalues[$i-1][$j] + (@$pagevalues[$i][$j] + @$pagevalues[$i-1][$j+1]

-                           + @$pagevalues[$i-2][$j] + @$pagevalues[$i-1][$j-1])/4) /2)-9;

-      @$pagevalues[$i][$j-1] = ((@$pagevalues[$i][$j-1] + (@$pagevalues[$i+1][$j-1] + @$pagevalues[$i][$j]

-                           + @$pagevalues[$i-1][$j-1] + @$pagevalues[$i][$j-2])/4) /2)-9;

-   } 

-   }

+for ($i = 0; $i < $xdivs; $i++) {

+    for ($j = 0; $j < $ydivs; $j++) {

+        if (@$pagevalues[$i][$j]) {

+            if (@$pagevalues[$i][$j] > $max)

+                $max = @$pagevalues[$i][$j];

+            if ($min == 0 || @$pagevalues[$i][$j] < $min)

+                $min = @$pagevalues[$i][$j];

+        } else {

+            @$pagevalues[$i][$j] = ((@$pagevalues[$i][$j] + (@$pagevalues[$i + 1][$j] + @$pagevalues[$i][$j + 1]

+                    + @$pagevalues[$i - 1][$j] + @$pagevalues[$i][$j - 1]) / 4) / 2) - 9;

+            @$pagevalues[$i - 1][$j] = ((@$pagevalues[$i - 1][$j] + (@$pagevalues[$i][$j] + @$pagevalues[$i - 1][$j + 1]

+                    + @$pagevalues[$i - 2][$j] + @$pagevalues[$i - 1][$j - 1]) / 4) / 2) - 9;

+            @$pagevalues[$i][$j - 1] = ((@$pagevalues[$i][$j - 1] + (@$pagevalues[$i + 1][$j - 1] + @$pagevalues[$i][$j]

+                    + @$pagevalues[$i - 1][$j - 1] + @$pagevalues[$i][$j - 2]) / 4) / 2) - 9;

+        }

+    }

 }

 //echo $max." ".$min;

 //echo "<table width='100%'>";

-for ($i = 0;$i < $xdivs; $i++ ) {

+for ($i = 0; $i < $xdivs; $i++) {

 //   echo "<tr>";

-   for ($j = 0; $j < $ydivs; $j++ ) {

+    for ($j = 0; $j < $ydivs; $j++) {

 //   echo ("<td>". log10(@$pagevalues[$i][$j])/log10($max) ."</td>");

-   if ((@$pagevalues[$i][$j]) > $min) {

-      $x = $i*($width/$xdivs);

-      $x1 = $borderLeft + $x -($width/$xdivs);

-      $x2 = $borderLeft + $x +($width/$xdivs);

-      $y = $j*($height/$ydivs);

-      $y1 = $borderTop + $y - ($height/$ydivs);

-      $y2 = $borderTop + $y + ($height/$ydivs);

-      imagefilledrectangle ($handle, $x1, $y1, $x2, $y2, $colorset[(int)((log10(@$pagevalues[$i][$j])/log10($max))*249)]);

-   }

-   }

+        if ((@$pagevalues[$i][$j]) > $min) {

+            $x = $i * ($width / $xdivs);

+            $x1 = $borderLeft + $x - ($width / $xdivs);

+            $x2 = $borderLeft + $x + ($width / $xdivs);

+            $y = $j * ($height / $ydivs);

+            $y1 = $borderTop + $y - ($height / $ydivs);

+            $y2 = $borderTop + $y + ($height / $ydivs);

+            imagefilledrectangle($handle, $x1, $y1, $x2, $y2, $colorset[(int) ((log10(@$pagevalues[$i][$j]) / log10($max)) * 249)]);

+        }

+    }

 //echo "</tr>";

 }

 //echo "</table>"

 

-header ("Content-type: image/png");

-ImagePng ($handle); 

-

-

+header("Content-type: image/png");

+ImagePng($handle);

 ?>

--- a/displayProcurementMethod.php
+++ b/displayProcurementMethod.php
@@ -15,16 +15,17 @@
 WHERE childCN is null

 GROUP BY procurementMethod ";

 

-$result = mysql_query($query);

+    $query = $conn->prepare($query);

+    $query->execute();

+    databaseError($conn->errorInfo());

 

 echo "<table>";

-while ($row = mysql_fetch_array($result, MYSQL_BOTH)) {

+    foreach ($query->fetchAll() as $row) {

 setlocale(LC_MONETARY, 'en_US');

 $value = number_format(doubleval($row[0]),2);

     echo ("<tr><td><b>{$row[1]}</b></td><td>\$$value</td></tr>");

 }

 echo "</table>";

-mysql_free_result($result);

 include_footer();

 ?>

 


--- a/displaySupplier.php
+++ b/displaySupplier.php
@@ -1,41 +1,40 @@
 <?php
+
 include_once ("./lib/common.inc.php");
 if ($_REQUEST['supplier']) {
-    
-include_header("Supplier");
-  $supplierS = htmlentities(strip_tags($_REQUEST['supplier']));
-  MethodCountGraph($supplierS);
-   CnCGraph($supplierS);
-  MethodValueGraph($supplierS);
-  /*lobbyist ties
-  
-  links to ABR/ASIC/Google News/ASX/Court records
-  
-  total value to various agencies (bar graph)
-  
-  spread procurement methods + percent consultancies + percent confidential (bar graph)
-  
-  spread of contract values
-  
-  spread of industries (textual?)*/
+
+    include_header("Supplier");
+    $supplierS = htmlentities(strip_tags($_REQUEST['supplier']));
+    MethodCountGraph($supplierS);
+    CnCGraph($supplierS);
+    MethodValueGraph($supplierS);
+    /* lobbyist ties
+
+      links to ABR/ASIC/Google News/ASX/Court records
+
+      total value to various agencies (bar graph)
+
+      spread procurement methods + percent consultancies + percent confidential (bar graph)
+
+      spread of contract values
+
+      spread of industries (textual?) */
     $query = 'SELECT "CNID", "description", "value", "agencyName", "category",
     "contractStart", "supplierName"
-    FROM contractnotice WHERE '.
-    $supplierQ.' '.$standardQ
-    .' ORDER BY value DESC';
+    FROM contractnotice WHERE ' .
+            $supplierQ . ' ' . $standardQ
+            . ' ORDER BY value DESC';
     echo $query;
-$query = $conn->prepare($query);
+    $query = $conn->prepare($query);
 
 //$query->bindParam(":supplierName", $supplierName);
-$query->bindParam(":supplierABN", $supplierABN);
-	$query->execute();
-	if (!$query) {
-		databaseError($conn->errorInfo());
-	}
-echo '<img src="graphs/displayMethodCountGraph.php?month=' . stripslashes($supplier) . '">';
-   echo '<img src="graphs/displayCnCGraph.php?month=' . stripslashes($supplier) . '">';
+    $query->bindParam(":supplierABN", $supplierABN);
+    $query->execute();
+    databaseError($conn->errorInfo());
+    echo '<img src="graphs/displayMethodCountGraph.php?month=' . stripslashes($supplier) . '">';
+    echo '<img src="graphs/displayCnCGraph.php?month=' . stripslashes($supplier) . '">';
 
-  echo "<table>  <thead>
+    echo "<table>  <thead>
     <tr>
       <th>Contract Notice Number</th>
       <th>Contract Description</th>
@@ -45,52 +44,50 @@
       <th>Supplier</th>
     </tr>
   </thead>";
-  foreach ($query->fetchAll() as $row) {
-    setlocale(LC_MONETARY, 'en_US');
-    $value = number_format(doubleval($row['value']) , 2);
-    echo ("<tr>
+    foreach ($query->fetchAll() as $row) {
+        setlocale(LC_MONETARY, 'en_US');
+        $value = number_format(doubleval($row['value']), 2);
+        echo ("<tr>
     <td><a href=\"displayContract.php?CNID={$row['CNID']}\">{$row['CNID']}</a></td>
     <td><b>{$row['description']}</b></a></td>
     <td>\$$value</td><td>{$row['agencyName']}</td>
     <td>{$row['contractStart']}</td>
     <td>{$row['supplierName']}</td>
     </tr>");
-  }
-  echo "</table>";
+    }
+    echo "</table>";
 } else {
     /*
-     histograph of supplier size/value
-    */
-include_header("Suppliers");
-suppliersGraph();
-  $query = 'SELECT SUM("value") as val, MAX("supplierName") as supplierName, "supplierABN",(
+      histograph of supplier size/value
+     */
+    include_header("Suppliers");
+    suppliersGraph();
+    $query = 'SELECT SUM("value") as val, MAX("supplierName") as supplierName, "supplierABN",(
  case when "supplierABN" != 0 THEN "supplierABN"::text ELSE "supplierName" END) as supplierID 
 FROM contractnotice
 WHERE "childCN" is null
 GROUP BY supplierID,"supplierABN"
 ORDER BY val DESC
 LIMIT 100';
-$query = $conn->prepare($query);
-	$query->execute();
-	if (!$query) {
-		databaseError($conn->errorInfo());
-	}
-   echo "<table>  <thead>
+    $query = $conn->prepare($query);
+    $query->execute();
+        databaseError($conn->errorInfo());
+    echo "<table>  <thead>
     <tr>
        <th>Position</th>
        <th>Supplier</th>
       <th>Total Contract Value</th>
     </tr>
   </thead>";
-$i = 1;
-  foreach ($query->fetchAll() as $row) {
-    setlocale(LC_MONETARY, 'en_US');
-    $value = number_format(doubleval($row['val']) , 2);
-    $supplier = stripslashes($row['supplierABN'].'-'.$row['suppliername']);
-    echo ("<tr><td>$i</td><td><b><a href=\"displaySupplier.php?supplier={$supplier}\">".ucsmart($row['suppliername'])."</a></b></td><td>\$$value</td></tr>\n");
-    $i++;
-  }
-  echo "</table>";
+    $i = 1;
+    foreach ($query->fetchAll() as $row) {
+        setlocale(LC_MONETARY, 'en_US');
+        $value = number_format(doubleval($row['val']), 2);
+        $supplier = stripslashes($row['supplierABN'] . '-' . $row['suppliername']);
+        echo ("<tr><td>$i</td><td><b><a href=\"displaySupplier.php?supplier={$supplier}\">" . ucsmart($row['suppliername']) . "</a></b></td><td>\$$value</td></tr>\n");
+        $i++;
+    }
+    echo "</table>";
 }
 include_footer();
 ?>

--- a/exportData.csv.php
+++ b/exportData.csv.php
@@ -11,13 +11,13 @@
  
 (\'https://www.tenders.gov.au/?event=public.advancedsearch.keyword&keyword=CN\'::text || "CNID"::text) as sourceURL 
 FROM contractnotice join agency on contractnotice."agencyName"=agency."agencyName" where "childCN" is null'
-, array(PDO::ATTR_CURSOR => PDO::FETCH_ORI_NEXT));
+        , array(PDO::ATTR_CURSOR => PDO::FETCH_ORI_NEXT));
 // "supplierCity","supplierPostcode","supplierCountry","contactPostcode",
 // (substr( "categoryUNSPSC"::text, 0, 2 ) || \'0000000\'::text) as "categoryUNSPSClv1", "categoryUNSPSC", (substr( "categoryUNSPSC"::text, 0, 3 ) || \'000000\'::text) as "categoryUNSPSClv2" "categoryUNSPSC", (substr( "categoryUNSPSC"::text, 0, 4 ) || \'00000\'::text as "categoryUNSPSClv3")
 $query->execute();
-if (!$query) {
-    databaseError($conn->errorInfo());
-die('Couldn\'t fetch records');
+$errors = $conn->errorInfo();
+if ($errors[2] != "") {
+    die("Export terminated, db error" . print_r($errors, true));
 }
 
 $num_fields = $query->columnCount();
@@ -29,20 +29,19 @@
 $fp = fopen('php://output', 'w');
 if ($fp && $query) {
     header('Content-Type: text/csv');
-    header('Content-Disposition: attachment; filename="export.'.date("c").'.csv"');
+    header('Content-Disposition: attachment; filename="export.' . date("c") . '.csv"');
     header('Pragma: no-cache');
     header('Expires: 0');
     fputcsv($fp, $headers);
- while ($row = $query->fetch(PDO::FETCH_NUM, PDO::FETCH_ORI_NEXT)) {
-	foreach ($row as $key => &$colvalue) {
-       
-			$colvalue =  preg_replace( '/[^[:print:]]/', '',
-			 utf8_encode($colvalue));
-             if ($headers[$key] == "publishDate" || $headers[$key] ==  "contractStart" 
-             || $headers[$key] ==  "contractEnd") {
-                 $colvalue = date("Y-m-d",$colvalue);
-             }
-		}
+    while ($row = $query->fetch(PDO::FETCH_NUM, PDO::FETCH_ORI_NEXT)) {
+        foreach ($row as $key => &$colvalue) {
+
+            $colvalue = preg_replace('/[^[:print:]]/', '', utf8_encode($colvalue));
+            if ($headers[$key] == "publishDate" || $headers[$key] == "contractStart"
+                    || $headers[$key] == "contractEnd") {
+                $colvalue = date("Y-m-d", $colvalue);
+            }
+        }
         fputcsv($fp, array_values($row));
     }
     die;

--- a/heuristics/dateHeuristics.php
+++ b/heuristics/dateHeuristics.php
@@ -1,102 +1,106 @@
 <?php
+
 //long contract period (number of weeks/days?)
 $heuristics["DATE_LONG_CONTRACT_PERIOD"] = Array(
-	"description" => "long contract period (number of weeks/days?)"
+    "description" => "long contract period (number of weeks/days?)"
 );
-function DATE_LONG_CONTRACT_PERIOD($cn)
-{
-	$averageContractPeriod = getAverageContractPeriod();
-	$stddevContractPeriod = getstddevContractPeriod();
-	$diff = strtotime($cn['contractEnd']) - strtotime($cn['contractStart']);
-	$days = intval($diff / (60 * 60 * 24));
-	$value = abs($days - $averageContractPeriod) / $stddevContractPeriod;
-	return Array(
-		"heuristic_value" => $value,
-		"raw_value" => $days,
-		"mean" => $averageContractPeriod,
-		"stddev" => $stddevContractPeriod
-	);
-}
-$averageContractPeriod;
-function getAverageContractPeriod()
-{
-	global $averageContractPeriod, $stddevContractPeriod;
-	if (!$averageContractPeriod) {
-		getStddevAverageContractPeriod();
-	}
-	return $averageContractPeriod;
-}
-$stddevContractPeriod;
-function getstddevContractPeriod()
-{
-	global $averageContractPeriod, $stddevContractPeriod;
-	if (!$stddevContractPeriod) {
-		getStddevAverageContractPeriod();
-	}
-	return $stddevContractPeriod;
-}
-function getStddevAverageContractPeriod()
-{
-	global $averageContractPeriod, $stddevContractPeriod;
-	$query = "select AVG(dateDiff(contractEnd,contractStart)),stddev(dateDiff(contractEnd,contractStart)) from contractnotice";
-	$result = mysql_query($query);
-	$r = mysql_fetch_array($result, MYSQL_BOTH);
-	$averageContractPeriod = $r[0];
-	$stddevContractPeriod = $r[1];
+
+function DATE_LONG_CONTRACT_PERIOD($cn) {
+    $averageContractPeriod = getAverageContractPeriod();
+    $stddevContractPeriod = getstddevContractPeriod();
+    $diff = strtotime($cn['contractEnd']) - strtotime($cn['contractStart']);
+    $days = intval($diff / (60 * 60 * 24));
+    $value = abs($days - $averageContractPeriod) / $stddevContractPeriod;
+    return Array(
+        "heuristic_value" => $value,
+        "raw_value" => $days,
+        "mean" => $averageContractPeriod,
+        "stddev" => $stddevContractPeriod
+    );
 }
 
+$averageContractPeriod;
+
+function getAverageContractPeriod() {
+    global $averageContractPeriod, $stddevContractPeriod;
+    if (!$averageContractPeriod) {
+        getStddevAverageContractPeriod();
+    }
+    return $averageContractPeriod;
+}
+
+$stddevContractPeriod;
+
+function getstddevContractPeriod() {
+    global $averageContractPeriod, $stddevContractPeriod;
+    if (!$stddevContractPeriod) {
+        getStddevAverageContractPeriod();
+    }
+    return $stddevContractPeriod;
+}
+
+function getStddevAverageContractPeriod() {
+    global $averageContractPeriod, $stddevContractPeriod;
+    $query = "select AVG(dateDiff(contractEnd,contractStart)),stddev(dateDiff(contractEnd,contractStart)) from contractnotice";
+    $result = $conn->query($query);
+    $r = $result->fetch(PDO::FETCH_BOTH);
+    $averageContractPeriod = $r[0];
+    $stddevContractPeriod = $r[1];
+}
 
 //Reported late, 45 days? A late contract is a dodgy contract except maybe for variations?
 $heuristics["DATE_REPORTED_LATE"] = Array(
-	"description" => "Reported late, 45 days?"
+    "description" => "Reported late, 45 days?"
 );
-function DATE_REPORTED_LATE($cn)
-{
-	$averageDaysLate = getAverageDaysLate();
-	$stddevDaysLate = getStddevDaysLate();
-	$diff = strtotime($cn['publishDate']) - strtotime($cn['contractStart']);
-	$days = intval($diff / (60 * 60 * 24));
-	if ($days <= 0) {
-		$value = 0;
-	}
-	else {
-		// +1 demerit for exceeding 45 day requirement
-		$value = (abs($days - $averageDaysLate) / $stddevDaysLate) + ($days < 45 ? 0 : 1);
-	}
-	return Array(
-		"heuristic_value" => $value,
-		"raw_value" => $days,
-		"mean" => $averageDaysLate,
-		"stddev" => $stddevDaysLate
-	);
+
+function DATE_REPORTED_LATE($cn) {
+    $averageDaysLate = getAverageDaysLate();
+    $stddevDaysLate = getStddevDaysLate();
+    $diff = strtotime($cn['publishDate']) - strtotime($cn['contractStart']);
+    $days = intval($diff / (60 * 60 * 24));
+    if ($days <= 0) {
+        $value = 0;
+    } else {
+        // +1 demerit for exceeding 45 day requirement
+        $value = (abs($days - $averageDaysLate) / $stddevDaysLate) + ($days < 45 ? 0 : 1);
+    }
+    return Array(
+        "heuristic_value" => $value,
+        "raw_value" => $days,
+        "mean" => $averageDaysLate,
+        "stddev" => $stddevDaysLate
+    );
 }
+
 $averageDaysLate;
-function getAverageDaysLate()
-{
-	global $averageDaysLate;
-	if (!$averageDaysLate) {
-            getDaysLate();
-	}
-	return $averageDaysLate;
+
+function getAverageDaysLate() {
+    global $averageDaysLate;
+    if (!$averageDaysLate) {
+        getDaysLate();
+    }
+    return $averageDaysLate;
 }
+
 $stddevDaysLate;
-function getStddevDaysLate()
-{
-	global $stddevDaysLate;
-	if (!$stddevDaysLate) {
-	getDaysLate();
-	}
-	return $stddevDaysLate;
+
+function getStddevDaysLate() {
+    global $stddevDaysLate;
+    if (!$stddevDaysLate) {
+        getDaysLate();
+    }
+    return $stddevDaysLate;
 }
+
 function getDaysLate() {
-    
-	global $averageDaysLate,$stddevDaysLate;
-    
-    		$query = "select AVG(dateDiff(publishDate,contractStart)), STDDEV(dateDiff(publishDate,contractStart)) from contractnotice";
-		$result = mysql_query($query);
-		$r = mysql_fetch_array($result, MYSQL_BOTH);
-		$averageDaysLate = $r[0];
-                	$stddevDaysLate = $r[1];
 
+    global $averageDaysLate, $stddevDaysLate;
+
+    $query = "select AVG(dateDiff(publishDate,contractStart)), STDDEV(dateDiff(publishDate,contractStart)) from contractnotice";
+    $result = $conn->query($query);
+    $r = $result->fetch(PDO::FETCH_BOTH);
+    $averageDaysLate = $r[0];
+    $stddevDaysLate = $r[1];
 }
+
 ?>

--- a/heuristics/heuristics.inc.php
+++ b/heuristics/heuristics.inc.php
@@ -10,8 +10,8 @@
 {
 	// check  if already ran
 	$query = "select count(*) from heuristic_results where heuristic_name = '$heuristicName' and CNID = '{$cn['CNID']}'";
-	$result = mysql_query($query);
-	$r = mysql_fetch_array($result);
+	    $result = $conn->query($query);
+    $r = $result->fetch(PDO::FETCH_BOTH);
 	if ($r[0] == 0) {
 		// if not, run now
 		$hresults = call_user_func($heuristicName, $cn);
@@ -31,9 +31,10 @@
            '{$cn["supplierID"]}'
     )";
 		// save value and cn data via sql
-		$result = mysql_query($query);
-		if ($result) echo "Saved $heuristicName for {$cn["CNID"]} <br>\n";
-		elseif (strpos(mysql_error() , "Duplicate entry") === false) echo $hresults . " failed insert.<br>" . mysql_error() . " <br>  $query <br><br>\n";
+		$result = $conn->query($query);
+                $errors = $conn->errorInfo();
+		if ($errors[2] == "") echo "Saved $heuristicName for {$cn["CNID"]} <br>\n";
+		elseif (strpos($errors[2] , "Duplicate entry") === false) echo $hresults . " failed insert.<br>" . print_r($errors,true) . " <br>  $query <br><br>\n";
 	}
 }
 ?>

--- a/heuristics/historyHeuristics.php
+++ b/heuristics/historyHeuristics.php
@@ -23,8 +23,8 @@
 	global $agencyTransactions;
 	if (!$agencyTransactions[$agencyName]) {
 		$query = 'select count(*) from contractnotice where agencyName = "' . $agencyName . '"';
-		$result = mysql_query($query);
-		$r = mysql_fetch_array($result, MYSQL_BOTH);
+    $result = $conn->query($query);
+    $r = $result->fetch(PDO::FETCH_BOTH);
 		$agencyTransactions[$agencyName] = $r[0];
 	}
 	return $agencyTransactions[$agencyName];
@@ -52,8 +52,8 @@
 	global $averageAgencyTransactions, $stddevAgencyTransactions;
 	$query = "select avg(count), STDDEV(count) from (select count(*) as count
                 from contractnotice group by agencyName) as a;";
-	$result = mysql_query($query);
-	$r = mysql_fetch_array($result, MYSQL_BOTH);
+    $result = $conn->query($query);
+    $r = $result->fetch(PDO::FETCH_BOTH);
 	$averageAgencyTransactions = $r[0];
 	$stddevAgencyTransactions = $r[1];
 }
@@ -82,16 +82,16 @@
 	if ($supplierABN != 0 && $supplierABN != "") {
 		if (!$supplierTransactions[$supplierABN]) {
 			$query = 'select count(*) from contractnotice where supplierABN = "' . $supplierABN . '"';
-			$result = mysql_query($query);
-			$r = mysql_fetch_array($result, MYSQL_BOTH);
+			    $result = $conn->query($query);
+    $r = $result->fetch(PDO::FETCH_BOTH);
 			$supplierTransactions[$supplierABN] = $r[0];
 		}
 		return $supplierTransactions[$supplierABN];
 	}
 	if (!$supplierTransactions[$supplierName]) {
 		$query = 'select count(*) from contractnotice where supplierName = "' . $supplierName . '"';
-		$result = mysql_query($query);
-		$r = mysql_fetch_array($result, MYSQL_BOTH);
+    $result = $conn->query($query);
+    $r = $result->fetch(PDO::FETCH_BOTH);
 		$supplierTransactions[$supplierName] = $r[0];
 	}
 	return $supplierTransactions[$supplierName];
@@ -118,8 +118,8 @@
 {
 	global $averageSupplierTransactions, $stddevSupplierTransactions;
 	$query = 'select avg(count), stddev(count) from (select IF(supplierABN != "",supplierABN,supplierName) as supplierID, count(*) as count from contractnotice group by supplierID) as a;';
-	$result = mysql_query($query);
-	$r = mysql_fetch_array($result, MYSQL_BOTH);
+    $result = $conn->query($query);
+    $r = $result->fetch(PDO::FETCH_BOTH);
 	$averageSupplierTransactions = $r[0];
 	$stddevSupplierTransactions = $r[1];
 }

--- a/heuristics/metadataHeuristics.php
+++ b/heuristics/metadataHeuristics.php
@@ -14,8 +14,8 @@
 	$averageDuplicatedDescriptions = getAverageDuplicatedDescriptions();
 	$stddevDuplicatedDescriptions = getstddevDuplicatedDescriptions();
 	$query = 'select count(*) from contractnotice where description = "' . $agencyName . '"';
-	$result = mysql_query($query);
-	$r = mysql_fetch_array($result, MYSQL_BOTH);
+    $result = $conn->query($query);
+    $r = $result->fetch(PDO::FETCH_BOTH);
 	$dupeDesc = $r[0];
         if ($dupeDesc == 1) $value = 0;
 	else $value = abs($dupeDesc - $averageDuplicatedDescriptions) / $stddevDuplicatedDescriptions;
@@ -51,8 +51,8 @@
 FROM `contractnotice` 
 group by description having count > 1 
         ) as a;";
-	$result = mysql_query($query);
-	$r = mysql_fetch_array($result, MYSQL_BOTH);
+    $result = $conn->query($query);
+    $r = $result->fetch(PDO::FETCH_BOTH);
 	$averageDuplicatedDescriptions = $r[0];
 	$stddevDuplicatedDescriptions = $r[1];
 }

--- a/heuristics/runHeuristics.php
+++ b/heuristics/runHeuristics.php
@@ -7,9 +7,10 @@
 FROM contractnotice JOIN agency ON contractnotice.agencyName=agency.agencyName
 WHERE  DATE(importDate) = (select * from (SELECT DATE(importDate) 
 FROM contractnotice ORDER BY importDate DESC limit 1) alias)";
-$result = mysql_query($query);
-if (!$result) echo mysql_error().$query;
-while ($cn = mysql_fetch_array($result, MYSQL_BOTH)) {
+    $query = $conn->prepare($query);
+    $query->execute();
+    databaseError($conn->errorInfo());
+foreach ($query->fetchAll() as $cn) {
 	//get each new CN from latest update
 	foreach ($heuristics as $heuristic => $description) {
 		// run all heuristics

--- a/heuristics/valueHeuristics.php
+++ b/heuristics/valueHeuristics.php
@@ -49,8 +49,8 @@
 	global $agencyTransactions;
 	if (!$agencyTransactions[$agencyName]) {
 		$query = 'select count(*) from contractnotice where agencyName = "' . $agencyName . '"';
-		$result = mysql_query($query);
-		$r = mysql_fetch_array($result, MYSQL_BOTH);
+    $result = $conn->query($query);
+    $r = $result->fetch(PDO::FETCH_BOTH);
 		$agencyTransactions[$agencyName] = $r[0];
 	}
 	return $agencyTransactions[$agencyName];

--- a/heuristics/viewHeuristicsColormap.php
+++ b/heuristics/viewHeuristicsColormap.php
@@ -41,17 +41,16 @@
 }
 $Gradients = Gradient("66FF00" , "FF0000" , 10); 
   
-$query = "select max(sum) from (SELECT sum(heuristic_value) 
-as sum FROM heuristic_results group by CNID) as a";
-$result = mysql_query($query);
-$r = mysql_fetch_array($result, MYSQL_BOTH);
+$query = 'select max(sum) from (SELECT sum(heuristic_value) 
+as sum FROM heuristic_results group by "CNID") as a';
+    $result = $conn->query($query);
+    $r = $result->fetch();
 $maxVal = $r[0];
   
-$query = "SELECT sum(heuristic_value) as sum, CNID
-FROM `heuristic_results` group by CNID order by sum DESC LIMIT 300";
-$result = mysql_query($query);
-if (!$result) echo mysql_error().$query;
-while ($r = mysql_fetch_array($result, MYSQL_BOTH)) {
+$query = 'SELECT sum(heuristic_value) as sum, "CNID"
+FROM heuristic_results group by "CNID" order by sum DESC LIMIT 300';
+    $result = $conn->query($query);
+foreach ($result->fetchAll() as $r) {
     echo '<div style="background: #'.$Gradients[floor(($r['sum']/$maxVal) * 10)].';">';
     echo '<a title="'.$r['sum'].'" href="../displayContract.php?CNID='.$r['CNID'].'">X</a>';
     echo "</div>";

--- a/heuristics/viewHeuristicsDistribution.php
+++ b/heuristics/viewHeuristicsDistribution.php
@@ -12,9 +12,8 @@
 
   include_once("../lib/common.inc.php");
 $query = "select heuristic_name, floor(heuristic_value) as val,count(*) from heuristic_results group by heuristic_name, val";
-$result = mysql_query($query);
-if (!$result) echo mysql_error().$query;
-while ($r = mysql_fetch_array($result, MYSQL_BOTH)) {
+    $result = $conn->query($query);
+foreach ($result->fetchAll() as $r) {
     $series[$r["heuristic_name"]][$r["val"]] = $r[2];
 }
 

--- a/lib/common.inc.php
+++ b/lib/common.inc.php
@@ -10,10 +10,12 @@
 	die("A database error occurred.\n");

 }

 

-//    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

+ //   $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

 function databaseError($errMsg)

 {

+    if ($errMsg[2] != "") {

 	die(print_r($errMsg,true));

+    }

 }

 

 function ucsmart($str) {


--- a/lib/graphs.inc.php
+++ b/lib/graphs.inc.php
@@ -1,8 +1,9 @@
 <?php
 $includedFlot = false;
+
 function includeFlot() {
-	if (!$includedFlot) {
-		echo '   <!--[if lte IE 8]><script language="javascript" type="text/javascript" src="lib/flot/excanvas.min.js"></script><![endif]--> 
+    if (!$includedFlot) {
+        echo '   <!--[if lte IE 8]><script language="javascript" type="text/javascript" src="lib/flot/excanvas.min.js"></script><![endif]--> 
  
     <script language="javascript" type="text/javascript" src="lib/flot/jquery.flot.js"></script> 
         <script language="javascript" type="text/javascript" src="lib/flot/jquery.flot.pie.js"></script> 
@@ -10,409 +11,430 @@
               <script language="javascript" type="text/javascript" src="lib/flot/jquery.flot.stack.js"></script> 
 
 ';
-$includedFlot = true;
-	}
+        $includedFlot = true;
+    }
 }
 
 function CNDistributionGraph() {
-	global $conn;
-	includeFlot();
-	 ?>
-	   <center><div id="cndist" style="width:900px;height:550px"></div></center>
-<script type="text/javascript"> 
-       var placeholder = $("#cndist");
-	 $(function () {
-
- var d1 = [];
- var d2 = [];
-<?php
-$query = 'select cnid, count(*) from (select ("CNID" - MOD("CNID",100)) as cnid from contractnotice where "CNID" < 999999 and "parentCN" is null) as a group by cnid order by cnid';
-$query = $conn->prepare($query);
-$query->execute();
-if (!$query) {
-	databaseError($conn->errorInfo());
-	return Array();
-}
-
-foreach ($query->fetchAll() as $delta) {
-
-	echo "d1.push([ ".intval($delta['cnid']).", ".intval($delta['count'])."]); \n";
-};
-$query = 'select cnid, count(*) from (select ("CNID" - MOD("CNID",100)) as cnid from contractnotice where "CNID" < 999999 and "parentCN" is not null) as a group by cnid order by cnid';
-$query = $conn->prepare($query);
-$query->execute();
-if (!$query) {
-	databaseError($conn->errorInfo());
-	return Array();
-}
-
-foreach ($query->fetchAll() as $delta) {
-
-	echo "d2.push([ ".intval($delta['cnid']).", ".intval($delta['count'])."]); \n";
-};
-?>
-
-var data = [
-       {
-            data: d1,
-series: {
-                   lines: { show: true },
-                   points: { show: true }
-               },
-            bars: { show: true }
-        },
-       {
-            data: d2,
-series: {
-                   lines: { show: true },
-                   points: { show: true }
-               },
-            bars: { show: true }
-        },
-    ];
-    var options = 
-    {
-series: {
-                stack: true,
-            },
-            grid: { hoverable: true, clickable: true, labelMargin: 17  },
-            selection: { mode: "x" }
+    global $conn;
+    includeFlot();
+    ?>
+    <center><div id="cndist" style="width:900px;height:550px"></div></center>
+    <script type="text/javascript"> 
+        var placeholder = $("#cndist");
+        $(function () {
+
+            var d1 = [];
+            var d2 = [];
+    <?php
+    $query = 'select cnid, count(*) from (select ("CNID" - MOD("CNID",100)) as cnid from contractnotice where "CNID" < 999999 and "parentCN" is null) as a group by cnid order by cnid';
+    $query = $conn->prepare($query);
+    $query->execute();
+    $errors = $conn->errorInfo();
+    if ($errors[2] != "") {
+        echo("Export terminated, db error" . print_r($errors, true));
+        return Array();
+    }
+
+    foreach ($query->fetchAll() as $delta) {
+
+        echo "d1.push([ " . intval($delta['cnid']) . ", " . intval($delta['count']) . "]); \n";
     };
-
-placeholder.bind("plotselected", function (event, ranges) {
-            plot = $.plot(placeholder, data,
-                          $.extend(true, {}, options, {
-                              xaxis: { min: ranges.xaxis.from, max: ranges.xaxis.to }
-                          }));
-    });
-    var previousPoint = null;
-    placeholder.bind("plothover", function (event, pos, item) {
-        $("#x").text(pos.x.toFixed(2));
-        $("#y").text(pos.y.toFixed(2));
- 
-            if (item) {
-                if (previousPoint != item.dataIndex) {
-                    previousPoint = item.dataIndex;
-                    
+    $query = 'select cnid, count(*) from (select ("CNID" - MOD("CNID",100)) as cnid from contractnotice where "CNID" < 999999 and "parentCN" is not null) as a group by cnid order by cnid';
+    $query = $conn->prepare($query);
+    $query->execute();
+    $errors = $conn->errorInfo();
+    if ($errors[2] != "") {
+        echo("Export terminated, db error" . print_r($errors, true));
+        return Array();
+    }
+
+    foreach ($query->fetchAll() as $delta) {
+
+        echo "d2.push([ " . intval($delta['cnid']) . ", " . intval($delta['count']) . "]); \n";
+    };
+    ?>
+
+            var data = [
+                {
+                    data: d1,
+                    series: {
+                        lines: { show: true },
+                        points: { show: true }
+                    },
+                    bars: { show: true }
+                },
+                {
+                    data: d2,
+                    series: {
+                        lines: { show: true },
+                        points: { show: true }
+                    },
+                    bars: { show: true }
+                },
+            ];
+            var options = 
+                {
+                series: {
+                    stack: true,
+                },
+                grid: { hoverable: true, clickable: true, labelMargin: 17  },
+                selection: { mode: "x" }
+            };
+
+            placeholder.bind("plotselected", function (event, ranges) {
+                plot = $.plot(placeholder, data,
+                $.extend(true, {}, options, {
+                    xaxis: { min: ranges.xaxis.from, max: ranges.xaxis.to }
+                }));
+            });
+            var previousPoint = null;
+            placeholder.bind("plothover", function (event, pos, item) {
+                $("#x").text(pos.x.toFixed(2));
+                $("#y").text(pos.y.toFixed(2));
+         
+                if (item) {
+                    if (previousPoint != item.dataIndex) {
+                        previousPoint = item.dataIndex;
+                            
+                        $("#tooltip").remove();
+                        var x = item.datapoint[0].toFixed(2),
+                        y = item.datapoint[1].toFixed(2);
+                            
+                        showTooltip(item.pageX, item.pageY,
+                        item.series.label + " of " + x + " = " + y);
+                    }
+                }
+                else {
                     $("#tooltip").remove();
-                    var x = item.datapoint[0].toFixed(2),
-                        y = item.datapoint[1].toFixed(2);
-                    
-                    showTooltip(item.pageX, item.pageY,
-                                item.series.label + " of " + x + " = " + y);
+                    previousPoint = null;            
                 }
-            }
-            else {
-                $("#tooltip").remove();
-                previousPoint = null;            
-            }
-    });
-
-    var plot = $.plot(placeholder, data,
-        options);
- });
-
-   function showTooltip(x, y, contents) {
-        $('<div id="tooltip">' + contents + '</div>').css( {
-            position: 'absolute',
-            display: 'none',
-            top: y + 5,
-            left: x + 5,
-            border: '1px solid #fdd',
-            padding: '2px',
-            'background-color': '#fee',
-            opacity: 0.80
-        }).appendTo("body").fadeIn(200);
-    }
- 
-</script> 
-<?php
+            });
+
+            var plot = $.plot(placeholder, data,
+            options);
+        });
+
+        function showTooltip(x, y, contents) {
+            $('<div id="tooltip">' + contents + '</div>').css( {
+                position: 'absolute',
+                display: 'none',
+                top: y + 5,
+                left: x + 5,
+                border: '1px solid #fdd',
+                padding: '2px',
+                'background-color': '#fee',
+                opacity: 0.80
+            }).appendTo("body").fadeIn(200);
+        }
+         
+    </script> 
+    <?php
 }
 
 function agenciesGraph() {
-	
-	global $conn;
-	includeFlot();
-$query = 'SELECT SUM("value") as val, MAX(contractnotice."agencyName") as agencyname FROM contractnotice join agency on contractnotice."agencyName"=agency."agencyName"  WHERE "childCN" is null
+
+    global $conn;
+    includeFlot();
+    $query = 'SELECT SUM("value") as val, MAX(contractnotice."agencyName") as agencyname FROM contractnotice join agency on contractnotice."agencyName"=agency."agencyName"  WHERE "childCN" is null
 GROUP BY abn ORDER BY SUM("value") DESC';
-$query = $conn->prepare($query);
-$query->execute();
-if (!$query) {
-	databaseError($conn->errorInfo());
-	return Array();
-}
-?>
-<script type="text/javascript">
-$(function () {
-	// data
-	var data = [
-  <?php
-foreach ($query->fetchAll() as $row) {
-		echo '{ label: "'.$row['agencyname'].'",  data: '.doubleval($row["val"]).'},';
-  }
+    $query = $conn->prepare($query);
+    $query->execute();
+    $errors = $conn->errorInfo();
+    if ($errors[2] != "") {
+        echo("Export terminated, db error" . print_r($errors, true));
+        return Array();
+    }
     ?>
-	];
-	// GRAPH 7
-	$.plot($("#graph7"), data, 
-	{
-		series: {
-			pie: { 
-				show: true,
-          radius: 1,
-          tilt: 0.75,
-                label: {
-                    show: true,
-                    radius: 1,
-                    formatter: function(label, series){
-                        return '<div style="font-size:8pt;text-align:center;padding:2px;color:white;">'+label+': '+Math.round(series.percent)+'%</div>';
-                    },
-                    background: { 
-                        opacity: 0.5,
-                        color: '#000'
+    <script type="text/javascript">
+        $(function () {
+            // data
+            var data = [
+    <?php
+    foreach ($query->fetchAll() as $row) {
+        echo '{ label: "' . $row['agencyname'] . '",  data: ' . doubleval($row["val"]) . '},';
+    }
+    ?>
+            ];
+            // GRAPH 7
+            $.plot($("#graph7"), data, 
+            {
+                series: {
+                    pie: { 
+                        show: true,
+                        radius: 1,
+                        tilt: 0.75,
+                        label: {
+                            show: true,
+                            radius: 1,
+                            formatter: function(label, series){
+                                return '<div style="font-size:8pt;text-align:center;padding:2px;color:white;">'+label+': '+Math.round(series.percent)+'%</div>';
+                            },
+                            background: { 
+                                opacity: 0.5,
+                                color: '#000'
+                            }
+                        },
+                        combine: {
+                            color: '#999',
+                            threshold: 0.012
+                        }
                     }
-                  },
-				combine: {
-					color: '#999',
-					threshold: 0.012
-				}
-			}
-		},
-		legend: {
-			show: false
-		}
-	});
-});
-</script>
+                },
+                legend: {
+                    show: false
+                }
+            });
+        });
+    </script>
     <div id="graph7" style="width:900px;height:550px"></div>
 
-<?php
-};
+    <?php
+}
+
+;
 
 function agencySuppliersGraph($agency) {
-	$agency = "AusAid";
-$topX = 15;
-$query = 'SELECT SUM(value) as val, supplierName FROM `contractnotice` WHERE (YEAR(contractStart) >= $startYear) AND "childCN" is null AND agencyName = \'$agency\'
+    $agency = "AusAid";
+    $topX = 15;
+    $query = 'SELECT SUM(value) as val, supplierName FROM `contractnotice` WHERE (YEAR(contractStart) >= $startYear) AND "childCN" is null AND agencyName = \'$agency\'
 GROUP BY lower(supplierName) ORDER BY val DESC limit $topX';
-$result = mysql_query($query);
-$suppliers = Array();
-$values = Array();
-while ($row = mysql_fetch_array($result, MYSQL_BOTH)) {
-  $suppliers[] = ucsmart($row['supplierName']);
-  $values[] = doubleval($row["val"]);
-}
-mysql_free_result($result);
-
-$query = 'SELECT sum(a.val) as value, count(1) as count from (SELECT SUM(value) as val, supplierName FROM `contractnotice` WHERE (YEAR(contractStart) >= $startYear) AND "childCN" is null and agencyName = \'$agency\'
+    $query = $conn->prepare($query);
+    $query->execute();
+    databaseError($conn->errorInfo());
+    $suppliers = Array();
+    $values = Array();
+    foreach ($query->fetchAll() as $row) {
+        $suppliers[] = ucsmart($row['supplierName']);
+        $values[] = doubleval($row["val"]);
+    }
+
+
+    $query = 'SELECT sum(a.val) as value, count(1) as count from (SELECT SUM(value) as val, supplierName FROM `contractnotice` WHERE (YEAR(contractStart) >= $startYear) AND "childCN" is null and agencyName = \'$agency\'
 GROUP BY lower(supplierName) ORDER BY val DESC LIMIT 18446744073709551610 OFFSET $topX) as a';
-$result = mysql_query($query);
-while ($row = mysql_fetch_array($result, MYSQL_BOTH)) {
-if ($row['count'] > 0) {
-  $suppliers[] = $row['count'] . " other suppliers";
-  $values[] = doubleval($row[0]);
-}
-}
-mysql_free_result($result);
+    $query = $conn->prepare($query);
+    $query->execute();
+    databaseError($conn->errorInfo());
+    foreach ($query->fetchAll() as $row) {
+        if ($row['count'] > 0) {
+            $suppliers[] = $row['count'] . " other suppliers";
+            $values[] = doubleval($row[0]);
+        }
+    }
 }
 
 function CnCGraph() {
-$query = "select procurementMethod, count(1) as count, SUM(value) as val, MONTH(contractStart) as month, YEAR(contractStart) as year from `contractnotice`
+    $query = "select procurementMethod, count(1) as count, SUM(value) as val, MONTH(contractStart) as month, YEAR(contractStart) as year from `contractnotice`
 where $agencyQ $supplierQ $standardQ group by procurementMethod,year,month order by procurementMethod,year,month";
-$result = mysql_query($query);
-$methods = Array("Direct","Open","Select");
-$dates = Array();
-$methodCountsP = Array();
-$methodCounts = Array();
-$maxValue = 0;
-while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
-  setlocale(LC_MONETARY, 'en_US');
-  if ($row['val'] > $maxValue) $maxValue = $row['val'];
-  $date = date( 'F ', mktime(0, 0, 0, $row["month"]) ). $row["year"];
-  if (array_search($date,$dates) === false ) {
-    $dates[$row["year"]*100 + $row["month"]] = $date;
-    ksort($dates);
-  }
-  $methodCountsP[$row["procurementMethod"]][$date] = $row["count"];
-
-}
-foreach ($methods as $method) {
-    foreach($dates as $date) {
-        if ($methodCountsP[$method][$date] > 0) $methodCounts[$method][] = $methodCountsP[$method][$date];
-        else $methodCounts[$method][] = 0;
-    }
-}
-$dates = array_values($dates);
-$totalRecords = array_sum_all($methodCounts);
-mysql_free_result($result);
-
-
-function formatCallback($aVal) {
-  global $totalRecords;
-  return percent($aVal, $totalRecords) . "%";
-}
-$attributes = Array();
-$attributeNames = Array(
-  "Consultancies",
-  "Confidentialities"
-);
-$query = 'SELECT \'consultancy\', count(1) FROM `contractnotice` WHERE $agencyQ $supplierQ consultancy=\'Yes\' AND "childCN" is null;';
-$result = mysql_query($query);
-$row = mysql_fetch_array($result, MYSQL_BOTH);
-$attributes[0] = $row[1];
-$query = 'SELECT \'confidentiality\', count(1) FROM `contractnotice` WHERE $agencyQ $supplierQ (confidentialityContract=\'Yes\' OR confidentialityOutputs=\'Yes\') AND "childCN" is null;';
-$result = mysql_query($query);
-$row = mysql_fetch_array($result, MYSQL_BOTH);
-$attributes[1] = $row[1];
-mysql_free_result($result);
-	
-}
+    $query = $conn->prepare($query);
+    $query->execute();
+    databaseError($conn->errorInfo());
+
+    $methods = Array("Direct", "Open", "Select");
+    $dates = Array();
+    $methodCountsP = Array();
+    $methodCounts = Array();
+    $maxValue = 0;
+    foreach ($query->fetchAll() as $row) {
+        setlocale(LC_MONETARY, 'en_US');
+        if ($row['val'] > $maxValue)
+            $maxValue = $row['val'];
+        $date = date('F ', mktime(0, 0, 0, $row["month"])) . $row["year"];
+        if (array_search($date, $dates) === false) {
+            $dates[$row["year"] * 100 + $row["month"]] = $date;
+            ksort($dates);
+        }
+        $methodCountsP[$row["procurementMethod"]][$date] = $row["count"];
+    }
+    foreach ($methods as $method) {
+        foreach ($dates as $date) {
+            if ($methodCountsP[$method][$date] > 0)
+                $methodCounts[$method][] = $methodCountsP[$method][$date];
+            else
+                $methodCounts[$method][] = 0;
+        }
+    }
+    $dates = array_values($dates);
+    $totalRecords = array_sum_all($methodCounts);
+
+    function formatCallback($aVal) {
+        global $totalRecords;
+        return percent($aVal, $totalRecords) . "%";
+    }
+
+    $attributes = Array();
+    $attributeNames = Array(
+        "Consultancies",
+        "Confidentialities"
+    );
+    $query = 'SELECT \'consultancy\', count(1) FROM `contractnotice` WHERE $agencyQ $supplierQ consultancy=\'Yes\' AND "childCN" is null;';
+    $result = $conn->query($query);
+    $row = $result->fetch(PDO::FETCH_ASSOC);
+    $attributes[0] = $row[1];
+    $query = 'SELECT \'confidentiality\', count(1) FROM `contractnotice` WHERE $agencyQ $supplierQ (confidentialityContract=\'Yes\' OR confidentialityOutputs=\'Yes\') AND "childCN" is null;';
+    $result = $conn->query($query);
+    $row = $result->fetch(PDO::FETCH_ASSOC);
+    $attributes[1] = $row[1];
+}
+
 function ContractPublishedGraph() {
-	$query = 'SELECT YEAR(publishDate), MONTH(publishDate),
+    $query = 'SELECT YEAR(publishDate), MONTH(publishDate),
 SUM(value) as val, count(1) as count FROM `contractnotice`
 WHERE (YEAR(publishDate) >= 2008)
 AND "childCN" is null
 GROUP BY MONTH(publishDate), YEAR(publishDate) 
 ORDER BY YEAR(publishDate), MONTH(publishDate)';
 
-$result = mysql_query($query);
-$dates = Array();
-$values = Array();
-while ($row = mysql_fetch_array($result, MYSQL_BOTH)) {
-setlocale(LC_MONETARY, 'en_US');
-$value = number_format(doubleval($row["val"]),2);
-$month_name = date( 'F', mktime(0, 0, 0, $row[1]) );
-	$dates[] = $month_name." {$row[0]}";
-	$counts[] = doubleval($row["count"]);
-	$values[] = doubleval($row["val"]);
-}
-mysql_free_result($result);
-
-}
+    $query = $conn->prepare($query);
+    $query->execute();
+    databaseError($conn->errorInfo());
+
+    $dates = Array();
+    $values = Array();
+    foreach ($query->fetchAll() as $row) {
+        setlocale(LC_MONETARY, 'en_US');
+        $value = number_format(doubleval($row["val"]), 2);
+        $month_name = date('F', mktime(0, 0, 0, $row[1]));
+        $dates[] = $month_name . " {$row[0]}";
+        $counts[] = doubleval($row["count"]);
+        $values[] = doubleval($row["val"]);
+    }
+}
+
 function ContractStartingGraph() {
-	$query = 'SELECT YEAR(contractStart), MONTH(contractStart),
+    $query = 'SELECT YEAR(contractStart), MONTH(contractStart),
 SUM(value) as val, count(1) as count FROM `contractnotice`
 WHERE (YEAR(contractStart) >= 2008)
 AND "childCN" is null
 GROUP BY MONTH(contractStart), YEAR(contractStart) 
 ORDER BY YEAR(contractStart), MONTH(contractStart)';
 
-$result = mysql_query($query);
-$dates = Array();
-$values = Array();
-while ($row = mysql_fetch_array($result, MYSQL_BOTH)) {
-setlocale(LC_MONETARY, 'en_US');
-$value = number_format(doubleval($row["val"]),2);
-$month_name = date( 'F', mktime(0, 0, 0, $row[1]) );
-	$dates[] = $month_name." {$row[0]}";
-	$counts[] = doubleval($row["count"]);
-	$values[] = doubleval($row["val"]);
-}
-mysql_free_result($result);
-}
+    $query = $conn->prepare($query);
+    $query->execute();
+    databaseError($conn->errorInfo());
+
+    $dates = Array();
+    $values = Array();
+    foreach ($query->fetchAll() as $row) {
+        setlocale(LC_MONETARY, 'en_US');
+        $value = number_format(doubleval($row["val"]), 2);
+        $month_name = date('F', mktime(0, 0, 0, $row[1]));
+        $dates[] = $month_name . " {$row[0]}";
+        $counts[] = doubleval($row["count"]);
+        $values[] = doubleval($row["val"]);
+    }
+}
+
 function MethodCountGraph() {
-	$query = 'select procurementMethod, count(1) as count, SUM(value) as value, MONTH(contractStart) as month, YEAR(contractStart) as year from `contractnotice`
+    $query = 'select procurementMethod, count(1) as count, SUM(value) as value, MONTH(contractStart) as month, YEAR(contractStart) as year from `contractnotice`
 where $agencyQ $supplierQ $standardQ group by procurementMethod,year,month order by procurementMethod,year,month';
-$result = mysql_query($query);
-$methods = Array("Direct","Open","Select");
-$dates = Array();
-$methodCountsP = Array();
-$methodCounts = Array();
-$maxValue = 0;
-while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
-  setlocale(LC_MONETARY, 'en_US');
-  if ($row['value'] > $maxValue) $maxValue = $row['value'];
-  $date = date( 'F ', mktime(0, 0, 0, $row["month"]) ). $row["year"];
-  if (array_search($date,$dates) === false ) {
-    $dates[$row["year"]*100 + $row["month"]] = $date;
-    ksort($dates);
-  }
-  $methodCountsP[$row["procurementMethod"]][$date] = $row["count"];
-
-}
-foreach ($methods as $method) {
-    foreach($dates as $date) {
-        if ($methodCountsP[$method][$date] > 0) $methodCounts[$method][] = $methodCountsP[$method][$date];
-        else $methodCounts[$method][] = 0;
-    }
-}
-$dates = array_values($dates);
-$totalRecords = array_sum_all($methodCounts);
-mysql_free_result($result);
-}
+    $methods = Array("Direct", "Open", "Select");
+    $dates = Array();
+    $methodCountsP = Array();
+    $methodCounts = Array();
+    $maxValue = 0;
+    $query = $conn->prepare($query);
+    $query->execute();
+    databaseError($conn->errorInfo());
+
+    foreach ($query->fetchAll() as $row) {
+        setlocale(LC_MONETARY, 'en_US');
+        if ($row['value'] > $maxValue)
+            $maxValue = $row['value'];
+        $date = date('F ', mktime(0, 0, 0, $row["month"])) . $row["year"];
+        if (array_search($date, $dates) === false) {
+            $dates[$row["year"] * 100 + $row["month"]] = $date;
+            ksort($dates);
+        }
+        $methodCountsP[$row["procurementMethod"]][$date] = $row["count"];
+    }
+    foreach ($methods as $method) {
+        foreach ($dates as $date) {
+            if ($methodCountsP[$method][$date] > 0)
+                $methodCounts[$method][] = $methodCountsP[$method][$date];
+            else
+                $methodCounts[$method][] = 0;
+        }
+    }
+    $dates = array_values($dates);
+    $totalRecords = array_sum_all($methodCounts);
+}
+
 function MethodValueGraph() {
-	$query = "select procurementMethod, SUM(value) as value, MONTH(contractStart) as month, YEAR(contractStart) as year from `contractnotice`
+    $query = "select procurementMethod, SUM(value) as value, MONTH(contractStart) as month, YEAR(contractStart) as year from `contractnotice`
 where $agencyQ $supplierQ $standardQ group by procurementMethod,year,month order by procurementMethod,year,month";
-$result = mysql_query($query);
-$methods = Array("Direct","Open","Select");
-$dates = Array();
-$methodValuesP = Array();
-$methodValues = Array();
-$maxValue = 0;
-while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
-  setlocale(LC_MONETARY, 'en_US');
-  if ($row['value'] > $maxValue) $maxValue = $row['value'];
-  $date = date( 'F ', mktime(0, 0, 0, $row["month"]) ). $row["year"];
-  if (array_search($date,$dates) === false ) {
-    $dates[$row["year"]*100 + $row["month"]] = $date;
-    ksort($dates);
-  }
-  $methodValuesP[$row["procurementMethod"]][$date] = $row["value"];
-
-}
-foreach ($methods as $method) {
-    foreach($dates as $date) {
-        if ($methodValuesP[$method][$date] > 0) $methodValues[$method][] = $methodValuesP[$method][$date];
-        else $methodValues[$method][] = 0;
-    }
-}
-$dates = array_values($dates);
-$totalRecords = array_sum_all($methodValues);
-mysql_free_result($result);
-
-}
+    $methods = Array("Direct", "Open", "Select");
+    $dates = Array();
+    $methodValuesP = Array();
+    $methodValues = Array();
+    $maxValue = 0;
+    $query = $conn->prepare($query);
+    $query->execute();
+    databaseError($conn->errorInfo());
+
+    foreach ($query->fetchAll() as $row) {
+        setlocale(LC_MONETARY, 'en_US');
+        if ($row['value'] > $maxValue)
+            $maxValue = $row['value'];
+        $date = date('F ', mktime(0, 0, 0, $row["month"])) . $row["year"];
+        if (array_search($date, $dates) === false) {
+            $dates[$row["year"] * 100 + $row["month"]] = $date;
+            ksort($dates);
+        }
+        $methodValuesP[$row["procurementMethod"]][$date] = $row["value"];
+    }
+    foreach ($methods as $method) {
+        foreach ($dates as $date) {
+            if ($methodValuesP[$method][$date] > 0)
+                $methodValues[$method][] = $methodValuesP[$method][$date];
+            else
+                $methodValues[$method][] = 0;
+        }
+    }
+    $dates = array_values($dates);
+    $totalRecords = array_sum_all($methodValues);
+}
+
 function SuppliersGraph() {
 
-  global $conn;
-  includeFlot();
-$topX = 10;
-$suppliers = Array();
-$values = Array();
-
-
-$query = 'SELECT SUM("value") as value, MAX("supplierName") as supplierName, (
+    global $conn;
+    includeFlot();
+    $topX = 10;
+    $suppliers = Array();
+    $values = Array();
+
+
+    $query = 'SELECT SUM("value") as value, MAX("supplierName") as supplierName, (
  case when "supplierABN" != 0 THEN "supplierABN"::text ELSE "supplierName" END) as supplierID 
 FROM contractnotice
 WHERE "childCN" is null
 GROUP BY supplierID
 ORDER BY value DESC
-LIMIT '.$topX;
-$query = $conn->prepare($query);
-  $query->execute();
-  if (!$query) {
-    databaseError($conn->errorInfo());
-  }
-  foreach ($query->fetchAll() as $row) {
-  setlocale(LC_MONETARY, 'en_US');
- // $value = number_format(doubleval($row["value"]) , 2);
-  $suppliers[] = ucsmart($row[1]);
-  $values[] = doubleval($row["value"]);
-}
-
-$query = 'SELECT sum(a.svalue) as val, suppliercountry from (SELECT sum("value") as svalue,  max("supplierCountry") as suppliercountry
+LIMIT ' . $topX;
+    $query = $conn->prepare($query);
+    $query->execute();
+    databaseError($conn->errorInfo());
+    foreach ($query->fetchAll() as $row) {
+        setlocale(LC_MONETARY, 'en_US');
+        // $value = number_format(doubleval($row["value"]) , 2);
+        $suppliers[] = ucsmart($row[1]);
+        $values[] = doubleval($row["value"]);
+    }
+
+    $query = 'SELECT sum(a.svalue) as val, suppliercountry from (SELECT sum("value") as svalue,  max("supplierCountry") as suppliercountry
 FROM contractnotice WHERE "childCN" is null and "supplierCountry" NOT ILIKE \'Australia\'
 GROUP BY "supplierName" ORDER BY svalue LIMIT 18446744073 OFFSET 10) as a group by suppliercountry order by val DESC limit 10 ';
-$query = $conn->prepare($query);
-  $query->execute();
-  if (!$query) {
-    databaseError($conn->errorInfo());
-  }
-
-  foreach ($query->fetchAll() as $row) {
-  $suppliers[] = "Other suppliers in ".ucsmart($row["suppliercountry"]);
-  $values[] = doubleval($row[0]);
-}
-
-
-$query = 'SELECT sum(a.value) as val, substring(
+    $query = $conn->prepare($query);
+    $query->execute();
+    databaseError($conn->errorInfo());
+
+    foreach ($query->fetchAll() as $row) {
+        $suppliers[] = "Other suppliers in " . ucsmart($row["suppliercountry"]);
+        $values[] = doubleval($row[0]);
+    }
+
+
+    $query = 'SELECT sum(a.value) as val, substring(
 supplierpostcode from 0 for 2) as postcode from (SELECT sum(value) as value, max("supplierPostcode") as supplierpostcode, max("supplierCountry") as suppliercountry
 FROM contractnotice WHERE "childCN" is null 
 GROUP BY "supplierABN" ORDER BY sum(value) LIMIT 1844674 OFFSET 10) as a
@@ -420,86 +442,89 @@
 group by substring(
 supplierpostcode from 0 for 2)
 order by val DESC;';
-$query = $conn->prepare($query);
-  $query->execute();
-  if (!$query) {
-    databaseError($conn->errorInfo());
-  }
-
-  foreach ($query->fetchAll() as $row) {
-    if ($row['postcode'][0] == 2 && $row['postcode'][1] == 6) $ACTvalue += $row[0];
-    else if ($row['postcode'][0] == 2 || $row['postcode'][0] == 1) $NSWvalue += $row[0];
-    else if ($row['postcode'][0] == 3 || $row['postcode'][0] == 8) $Vicvalue += $row[0];
-    else if ($row['postcode'][0] == 4 || $row['postcode'][0] == 9) $QLDvalue += $row[0];
-    else if ($row['postcode'][0] == 5) $SAvalue += $row[0];
-    else if ($row['postcode'][0] == 6) $WAvalue += $row[0];
-    else if ($row['postcode'][0] == 7) $Tasvalue += $row[0];
-    else if ($row['postcode'][0] == 0) $NTvalue += $row[0];
-}
-$suppliers[] = "Other suppliers in Australia - ACT";
-$values[] = doubleval($ACTvalue);
-$suppliers[] = "Other suppliers in Australia - NSW";
-$values[] = doubleval($NSWvalue);
-$suppliers[] = "Other suppliers in Australia - Victoria";
-$values[] = doubleval($Vicvalue);
-$suppliers[] = "Other suppliers in Australia - Queensland";
-$values[] = doubleval($QLDvalue);
-$suppliers[] = "Other suppliers in Australia - NT";
-$values[] = doubleval($NTvalue);
-$suppliers[] = "Other suppliers in Australia - West Australia";
-$values[] = doubleval($WAvalue);
-$suppliers[] = "Other suppliers in Australia - South Australia";
-$values[] = doubleval($SAvalue);
-$suppliers[] = "Other suppliers in Australia - Tasmania";
-$values[] = doubleval($Tasvalue);
-
-
+    $query = $conn->prepare($query);
+    $query->execute();
+    databaseError($conn->errorInfo());
+
+    foreach ($query->fetchAll() as $row) {
+        if ($row['postcode'][0] == 2 && $row['postcode'][1] == 6)
+            $ACTvalue += $row[0];
+        else if ($row['postcode'][0] == 2 || $row['postcode'][0] == 1)
+            $NSWvalue += $row[0];
+        else if ($row['postcode'][0] == 3 || $row['postcode'][0] == 8)
+            $Vicvalue += $row[0];
+        else if ($row['postcode'][0] == 4 || $row['postcode'][0] == 9)
+            $QLDvalue += $row[0];
+        else if ($row['postcode'][0] == 5)
+            $SAvalue += $row[0];
+        else if ($row['postcode'][0] == 6)
+            $WAvalue += $row[0];
+        else if ($row['postcode'][0] == 7)
+            $Tasvalue += $row[0];
+        else if ($row['postcode'][0] == 0)
+            $NTvalue += $row[0];
+    }
+    $suppliers[] = "Other suppliers in Australia - ACT";
+    $values[] = doubleval($ACTvalue);
+    $suppliers[] = "Other suppliers in Australia - NSW";
+    $values[] = doubleval($NSWvalue);
+    $suppliers[] = "Other suppliers in Australia - Victoria";
+    $values[] = doubleval($Vicvalue);
+    $suppliers[] = "Other suppliers in Australia - Queensland";
+    $values[] = doubleval($QLDvalue);
+    $suppliers[] = "Other suppliers in Australia - NT";
+    $values[] = doubleval($NTvalue);
+    $suppliers[] = "Other suppliers in Australia - West Australia";
+    $values[] = doubleval($WAvalue);
+    $suppliers[] = "Other suppliers in Australia - South Australia";
+    $values[] = doubleval($SAvalue);
+    $suppliers[] = "Other suppliers in Australia - Tasmania";
+    $values[] = doubleval($Tasvalue);
+    ?>
+    <script type="text/javascript">
+        $(function () {
+            // data
+            var data = [
+    <?php
+    foreach ($suppliers as $key => $supplier) {
+        echo '{ label: "' . $supplier . '",  data: ' . doubleval($values[$key]) . '},';
+    }
+    ?>
+            ];
+            // GRAPH 7
+            $.plot($("#graph7"), data, 
+            {
+                series: {
+                    pie: { 
+                        show: true,
+                        radius: 1,
+                        tilt: 0.75,
+                        label: {
+                            show: true,
+                            radius: 1,
+                            formatter: function(label, series){
+                                return '<div style="font-size:8pt;text-align:center;padding:2px;color:white;">'+label+': '+Math.round(series.percent)+'%</div>';
+                            },
+                            background: { 
+                                opacity: 0.5,
+                                color: '#000'
+                            }
+                        },
+                        combine: {
+                            color: '#999',
+                            threshold: 0.012
+                        }
+                    }
+                },
+                legend: {
+                    show: false
+                }
+            });
+        });
+    </script>
+    <div id="graph7" style="width:900px;height:550px"></div>
+
+    <?php
+}
 ?>
-<script type="text/javascript">
-$(function () {
-  // data
-  var data = [
-  <?php
-foreach ($suppliers as $key => $supplier) {
-    echo '{ label: "'.$supplier.'",  data: '.doubleval($values[$key]).'},';
-  }
-    ?>
-  ];
-  // GRAPH 7
-  $.plot($("#graph7"), data, 
-  {
-    series: {
-      pie: { 
-        show: true,
-          radius: 1,
-          tilt: 0.75,
-                label: {
-                    show: true,
-                    radius: 1,
-                    formatter: function(label, series){
-                        return '<div style="font-size:8pt;text-align:center;padding:2px;color:white;">'+label+': '+Math.round(series.percent)+'%</div>';
-                    },
-                    background: { 
-                        opacity: 0.5,
-                        color: '#000'
-                    }
-                  },
-        combine: {
-          color: '#999',
-          threshold: 0.012
-        }
-      }
-    },
-    legend: {
-      show: false
-    }
-  });
-});
-</script>
-    <div id="graph7" style="width:900px;height:550px"></div>
-
-<?php
-}
-
-?>
-
+

--- a/search_autosuggest.php
+++ b/search_autosuggest.php
@@ -1,74 +1,71 @@
 <?php
+
 include_once ("./lib/common.inc.php");
 $input = strtolower($_REQUEST['input']);
 $len = strlen($input);
-$limit = isset($_GET['limit']) ? (int)$_GET['limit'] : 0;
+$limit = isset($_GET['limit']) ? (int) $_GET['limit'] : 0;
 $aResults = array();
 $count = 0;
 if ($len) {
-  $query = 'SELECT MAX("supplierName"), MAX("supplierABN"), count(*) as count
+    $query = 'SELECT MAX("supplierName"), MAX("supplierABN"), count(*) as count
 FROM contractnotice
 WHERE "supplierName" ILIKE :supplierName
 GROUP BY "supplierName"
 ORDER BY count(*) DESC
 LIMIT 4;
 ';
-$query = $conn->prepare($query);
-$supplierName = $input.'%';
-$query->bindParam(":supplierName", $supplierName);
-  $query->execute();
-  if (!$query) {
+    $query = $conn->prepare($query);
+    $supplierName = $input . '%';
+    $query->bindParam(":supplierName", $supplierName);
+    $query->execute();
     databaseError($conn->errorInfo());
-  }
-  foreach ($query->fetchAll() as $row) {
-    $count++;
-    $aResults[] = array(
-      "id" => "supplier-".$row[1].'-'.$row[0],
-      "value" => htmlspecialchars($row[0]) ,
-      "info" => htmlspecialchars("Supplier - ". $row['count']." records")
-    );
-  }
-  $query = 'SELECT MAX("agencyName"), count(*) as count
+    foreach ($query->fetchAll() as $row) {
+        $count++;
+        $aResults[] = array(
+            "id" => "supplier-" . $row[1] . '-' . $row[0],
+            "value" => htmlspecialchars($row[0]),
+            "info" => htmlspecialchars("Supplier - " . $row['count'] . " records")
+        );
+    }
+    $query = 'SELECT MAX("agencyName"), count(*) as count
 FROM contractnotice
 WHERE "agencyName" ILIKE :agencyName
 GROUP BY "agencyName"
 ORDER BY count DESC
 LIMIT 4;';
-$query = $conn->prepare($query);
-$agencyName = $input.'%';
-$query->bindParam(":agencyName", $agencyName);
-  $query->execute();
-  if (!$query) {
+    $query = $conn->prepare($query);
+    $agencyName = $input . '%';
+    $query->bindParam(":agencyName", $agencyName);
+    $query->execute();
     databaseError($conn->errorInfo());
-  }
-  foreach ($query->fetchAll() as $row) {
-    $count++;
-    $aResults[] = array(
-      "id" => "agency-".$row[0],
-      "value" => htmlspecialchars($row[0]) ,
-      "info" => htmlspecialchars("Government Agency - ". $row['count']." records")
-    );
-  }
+    foreach ($query->fetchAll() as $row) {
+        $count++;
+        $aResults[] = array(
+            "id" => "agency-" . $row[0],
+            "value" => htmlspecialchars($row[0]),
+            "info" => htmlspecialchars("Government Agency - " . $row['count'] . " records")
+        );
+    }
 }
 header("Expires: Mon, 26 Jul 1997 05:00:00 GMT"); // Date in the past
 header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT"); // always modified
 header("Cache-Control: no-cache, must-revalidate"); // HTTP/1.1
 header("Pragma: no-cache"); // HTTP/1.0
 if (isset($_REQUEST['json'])) {
-  header("Content-Type: application/json");
-  echo "{\"results\": [";
-  $arr = array();
-  for ($i = 0;$i < count($aResults);$i++) {
-    $arr[] = "{\"id\": \"" . $aResults[$i]['id'] . "\", \"value\": \"" . $aResults[$i]['value'] . "\", \"info\": \"\"}";
-  }
-  echo implode(", ", $arr);
-  echo "]}";
+    header("Content-Type: application/json");
+    echo "{\"results\": [";
+    $arr = array();
+    for ($i = 0; $i < count($aResults); $i++) {
+        $arr[] = "{\"id\": \"" . $aResults[$i]['id'] . "\", \"value\": \"" . $aResults[$i]['value'] . "\", \"info\": \"\"}";
+    }
+    echo implode(", ", $arr);
+    echo "]}";
 } else {
-  header("Content-Type: text/xml");
-  echo "<?xml version=\"1.0\" encoding=\"utf-8\" ?><results>";
-  for ($i = 0;$i < count($aResults);$i++) {
-    echo "<rs id=\"" . $aResults[$i]['id'] . "\" info=\"" . $aResults[$i]['info'] . "\">" . $aResults[$i]['value'] . "</rs>";
-  }
-  echo "</results>";
+    header("Content-Type: text/xml");
+    echo "<?xml version=\"1.0\" encoding=\"utf-8\" ?><results>";
+    for ($i = 0; $i < count($aResults); $i++) {
+        echo "<rs id=\"" . $aResults[$i]['id'] . "\" info=\"" . $aResults[$i]['info'] . "\">" . $aResults[$i]['value'] . "</rs>";
+    }
+    echo "</results>";
 }
 ?>