Port DB calls to PHP PDO
Port DB calls to PHP PDO

--- a/include/common-db.inc.php
+++ b/include/common-db.inc.php
@@ -1,21 +1,23 @@
 <?php
-  if (php_uname('n') == "actbus-www") {
-    $conn = pg_connect("dbname=transitdata user=transitdata password=transitdata host=bus-main.lambdacomplex.org");
-  } else if (isDebugServer()) {
-    $conn = pg_connect("dbname=transitdata user=postgres password=snmc");
-  } else {
-    $conn = pg_connect("dbname=transitdata user=transitdata password=transitdata ");
-  }
-  if (!$conn) {
-      die("A database error occurred.\n");
-  }
-  
-  function databaseError($errMsg) {
-    die($errMsg);
-  }
- 
-  include('db/route-dao.inc.php');
-  include('db/trip-dao.inc.php');
-  include('db/stop-dao.inc.php');  
-  ?>
+if (php_uname('n') == "actbus-www") {
+	$conn = new PDO("pgsql:dbname=transitdata;user=transitdata;password=transitdata;host=bus-main.lambdacomplex.org");
+}
+else if (isDebugServer()) {
+	$conn = new PDO("pgsql:dbname=transitdata;user=postgres;password=snmc;host=localhost");
+}
+else {
+	$conn = new PDO("pgsql:dbname=transitdata;user=transitdata;password=transitdata;host=localhost");
+}
+if (!$conn) {
+	die("A database error occurred.\n");
+}
+function databaseError($errMsg)
+{
+	die($errMsg);
+}
+include ('db/route-dao.inc.php');
+include ('db/trip-dao.inc.php');
+include ('db/stop-dao.inc.php');
+include ('db/servicealert-dao.inc.php');
+?>
 

--- /dev/null
+++ b/include/common-request.inc.php
@@ -1,1 +1,45 @@
-
+<?php
+if (isset($_REQUEST['firstLetter'])) {
+	$firstLetter = filter_var($_REQUEST['firstLetter'], FILTER_SANITIZE_STRING);
+}
+if (isset($_REQUEST['bysuburbs'])) {
+	$bysuburbs = true;
+}
+if (isset($_REQUEST['bynumber'])) {
+	$bynumber = true;
+}
+if (isset($_REQUEST['allstops'])) {
+	$allstops = true;
+}
+if (isset($_REQUEST['nearby'])) {
+	$nearby = true;
+}
+if (isset($_REQUEST['suburb'])) {
+	$suburb = filter_var($_REQUEST['suburb'], FILTER_SANITIZE_STRING);
+}
+$pageKey = filter_var($_REQUEST['pageKey'], FILTER_SANITIZE_NUMBER_INT);
+$lat = filter_var($_REQUEST['lat'], FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION);
+$lon = filter_var($_REQUEST['lon'], FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION);
+$max_distance = filter_var($_REQUEST['radius'], FILTER_SANITIZE_NUMBER_INT);
+if (isset($_REQUEST['numberSeries'])) {
+	$numberSeries = filter_var($_REQUEST['numberSeries'], FILTER_SANITIZE_NUMBER_INT);
+}
+if (isset($_REQUEST['routeDestination'])) {
+	$routeDestination = urldecode(filter_var($_REQUEST['routeDestination'], FILTER_SANITIZE_ENCODED));
+}
+if (isset($_REQUEST['stopcode'])) {
+	$stopcode = filter_var($_REQUEST['stopcode'], FILTER_SANITIZE_STRING);
+}
+if (isset($_REQUEST['stopids'])) {
+	$stopids = explode(",", filter_var($_REQUEST['stopids'], FILTER_SANITIZE_STRING));
+}
+if (isset($_REQUEST['tripid'])) {
+	$tripid = filter_var($_REQUEST['tripid'], FILTER_SANITIZE_NUMBER_INT);
+}
+if (isset($_REQUEST['stopid'])) {
+	$stopid = filter_var($_REQUEST['stopid'], FILTER_SANITIZE_NUMBER_INT);
+}
+if (isset($_REQUEST['routeid'])) {
+	$routeid = filter_var($_REQUEST['routeid'], FILTER_SANITIZE_NUMBER_INT);
+}
+?>

--- a/include/common-transit.inc.php
+++ b/include/common-transit.inc.php
@@ -4,17 +4,7 @@
 	'saturday',
 	'weekday'
 );
-function getServiceOverride() {
-	global $conn;
-	$query = "Select * from calendar_dates where date = '".date("Ymd")."' and exception_type = '1'";
-	 debug($query,"database");
-	$result = pg_query($conn, $query);
-	if (!$result) {
-		databaseError(pg_result_error($result));
-		return Array();
-	}
-	return pg_fetch_assoc($result);
-}
+
 function service_period()
 {
 	

--- a/include/db/route-dao.inc.php
+++ b/include/db/route-dao.inc.php
@@ -1,160 +1,211 @@
 <?php
+function getRoute($routeID)
+{
+	global $conn;
+	$query = "Select * from routes where route_id = :routeID LIMIT 1";
+	debug($query, "database");
+	$query = $conn->prepare($query);
+	$query->bindParam(":routeID", $routeID);
+	$query->execute();
+	if (!$query) {
+		databaseError($conn->errorInfo());
+		return Array();
+	}
+	return $query->fetch(PDO::FETCH_ASSOC);
+}
+function getRoutes()
+{
+	global $conn;
+	$query = "Select * from routes order by route_short_name;";
+	debug($query, "database");
+	$query = $conn->prepare($query);
+	$query->execute();
+	if (!$query) {
+		databaseError($conn->errorInfo());
+		return Array();
+	}
+	return $query->fetchAll();
+}
+function getRoutesByNumber($routeNumber = "")
+{
+	global $conn;
+	if ($routeNumber != "") {
+		$query = "Select distinct routes.route_id,routes.route_short_name,routes.route_long_name,service_id from routes  join trips on trips.route_id =
+routes.route_id join stop_times on stop_times.trip_id = trips.trip_id where route_short_name = :routeNumber order by route_short_name;";
+	}
+	else {
+		$query = "SELECT DISTINCT route_short_name from routes order by route_short_name";
+	}
+	debug($query, "database");
+	$query = $conn->prepare($query);
+	if ($routeNumber != "") {
+		$query->bindParam(":routeNumber", $routeNumber);
+	}
+	$query->execute();
+	if (!$query) {
+		databaseError($conn->errorInfo());
+		return Array();
+	}
+	return $query->fetchAll();
+}
+function getRoutesByNumberSeries($routeNumberSeries = "")
+{
+	global $conn;
+	if (strlen($routeNumberSeries) == 1) {
+		return getRoutesByNumber($routeNumberSeries);
+	}
+	$seriesMin = substr($routeNumberSeries, 0, -1) . "0";
+	$seriesMax = substr($routeNumberSeries, 0, -1) . "9";
+	$query = "Select distinct routes.route_id,routes.route_short_name,routes.route_long_name,service_id from routes  join trips on trips.route_id =
+routes.route_id join stop_times on stop_times.trip_id = trips.trip_id where to_number(route_short_name, 'FM999') between :seriesMin and :seriesMax OR route_short_name LIKE :routeNumberSeries order by route_short_name;";
+	debug($query, "database");
+	$query = $conn->prepare($query);
+	$query->bindParam(":seriesMin", $seriesMin);
+	$query->bindParam(":seriesMax", $seriesMax);
+        $routeNumberSeries = "% ".substr($routeNumberSeries, 0, -1)."%";
+        $query->bindParam(":routeNumberSeries", $routeNumberSeries);
+	$query->execute();
+	if (!$query) {
+		databaseError($conn->errorInfo());
+		return Array();
+	}
+	return $query->fetchAll();
+}
+function getRouteNextTrip($routeID)
+{
+	global $conn;
+	$query = "select * from routes join trips on trips.route_id = routes.route_id
+join stop_times on stop_times.trip_id = trips.trip_id where
+arrival_time > :currentTime and routes.route_id = :routeID order by
+arrival_time limit 1";
+	debug($query, "database");
+	$query = $conn->prepare($query);
+	$query->bindParam(":currentTime", current_time());
+	$query->bindParam(":routeID", $routeID);
+	$query->execute();
+	if (!$query) {
+		databaseError($conn->errorInfo());
+		return Array();
+	}
+	$r = $query->fetch(PDO::FETCH_ASSOC);
 
-function getRoute($routeID) {
-		global $conn;
-        $query = "Select * from routes where route_id = '$routeID' LIMIT 1";
-        debug($query,"database");
-	$result = pg_query($conn, $query);
-	if (!$result) {
-		databaseError(pg_result_error($result));
-		return Array();
-	}
-	return pg_fetch_assoc($result);   
-}
-function getRoutes() {
-    	global $conn;
-	$query = "Select * from routes order by route_short_name;";
-        debug($query,"database");
-	$result = pg_query($conn, $query);
-	if (!$result) {
-		databaseError(pg_result_error($result));
-		return Array();
-	}
-	return pg_fetch_all($result);    
-}
-
-function getRoutesByNumber($routeNumber = "") {
-  	global $conn;
-        if ($routeNumber != "") {
-       	$query = "Select distinct routes.route_id,routes.route_short_name,routes.route_long_name,service_id from routes  join trips on trips.route_id =
-routes.route_id join stop_times on stop_times.trip_id = trips.trip_id where route_short_name = '$routeNumber' order by route_short_name;";
-        } else {
-            $query = "SELECT DISTINCT route_short_name from routes order by route_short_name";
-        }
-        debug($query,"database");
-	$result = pg_query($conn, $query);
-	if (!$result) {
-		databaseError(pg_result_error($result));
-		return Array();
-	}
-	return pg_fetch_all($result);    
-}
-
-function getRouteNextTrip($routeID) {
-     global $conn;
-    $query = "select * from routes join trips on trips.route_id = routes.route_id
-join stop_times on stop_times.trip_id = trips.trip_id where
-arrival_time > '".current_time()."' and routes.route_id = '$routeID' order by
-arrival_time limit 1";
-        debug($query,"database");
-	$result = pg_query($conn, $query);
-	if (!$result) {   
-		databaseError(pg_result_error($result));
-		return Array();
-	}
-        $r = pg_fetch_assoc($result);   
-        // past last trip of the day special case
-       if (sizeof($r) == 0) {
-            $query = "select * from routes join trips on trips.route_id = routes.route_id
-join stop_times on stop_times.trip_id = trips.trip_id where routes.route_id = '$routeID' order by
+	// past last trip of the day special case
+	if (sizeof($r) < 16) {
+		$query = "select * from routes join trips on trips.route_id = routes.route_id
+join stop_times on stop_times.trip_id = trips.trip_id where routes.route_id = :routeID order by
 arrival_time DESC limit 1";
-        debug($query,"database");
-	$result = pg_query($conn, $query);
-	if (!$result) {   
-		databaseError(pg_result_error($result));
-		return Array();
-	}
-        $r = pg_fetch_assoc($result); 
-       }
-	return $r;       
-  }
-  
-  function getTimeInterpolatedRouteAtStop($routeID, $stop_id)
-{
-    $nextTrip = getRouteNextTrip($routeID);
-    if ($nextTrip['trip_id']){
-    	foreach (getTimeInterpolatedTrip($nextTrip['trip_id']) as $tripStop) {
-		if ($tripStop['stop_id'] == $stop_id) return $tripStop;
-	}
-    }
+		debug($query, "database");
+		$query = $conn->prepare($query);
+		$query->bindParam(":routeID", $routeID);
+		$query->execute();
+		if (!$query) {
+			databaseError($conn->errorInfo());
+			return Array();
+		}
+            
+		$r = $query->fetch(PDO::FETCH_ASSOC);
+	}
+	return $r;
+}
+function getTimeInterpolatedRouteAtStop($routeID, $stop_id)
+{
+	$nextTrip = getRouteNextTrip($routeID);
+	if ($nextTrip['trip_id']) {
+		foreach (getTimeInterpolatedTrip($nextTrip['trip_id']) as $tripStop) {
+			if ($tripStop['stop_id'] == $stop_id) return $tripStop;
+		}
+	}
 	return Array();
 }
-  
-function getRouteTrips($routeID) {
-        global $conn;
-    $query = "select routes.route_id,trips.trip_id,service_id,arrival_time, stop_id, stop_sequence from routes join trips on trips.route_id = routes.route_id
-join stop_times on stop_times.trip_id = trips.trip_id where routes.route_id = '$routeID' and stop_sequence = '1' order by
+function getRouteTrips($routeID)
+{
+	global $conn;
+	$query = "select routes.route_id,trips.trip_id,service_id,arrival_time, stop_id, stop_sequence from routes join trips on trips.route_id = routes.route_id
+join stop_times on stop_times.trip_id = trips.trip_id where routes.route_id = :routeID and stop_sequence = '1' order by
 arrival_time ";
-        debug($query,"database");
-	$result = pg_query($conn, $query);
-	if (!$result) {
-		databaseError(pg_result_error($result));
-		return Array();
-	}
-	return pg_fetch_all($result);       
-  }
-function getRoutesByDestination($destination = "", $service_period = "") {
-    global $conn;
-         if ($service_period == "") $service_period = service_period();
-         if ($destination != "")  {
-             $query = "SELECT DISTINCT trips.route_id,route_short_name,route_long_name, service_id
+	debug($query, "database");
+	$query = $conn->prepare($query);
+	$query->bindParam(":routeID", $routeID);
+	$query->execute();
+	if (!$query) {
+		databaseError($conn->errorInfo());
+		return Array();
+	}
+	return $query->fetchAll();
+}
+function getRoutesByDestination($destination = "", $service_period = "")
+{
+	global $conn;
+	if ($service_period == "") $service_period = service_period();
+	if ($destination != "") {
+		$query = "SELECT DISTINCT trips.route_id,route_short_name,route_long_name, service_id
 FROM stop_times join trips on trips.trip_id =
 stop_times.trip_id join routes on trips.route_id = routes.route_id
-WHERE route_long_name = '$destination' AND  service_id='$service_period' order by route_short_name";
-         } else {
-        $query = "SELECT DISTINCT route_long_name
+WHERE route_long_name = :destination AND  service_id=:service_period order by route_short_name";
+	}
+	else {
+		$query = "SELECT DISTINCT route_long_name
 FROM stop_times join trips on trips.trip_id =
 stop_times.trip_id join routes on trips.route_id = routes.route_id
-WHERE service_id='$service_period' order by route_long_name";
-    }
-        debug($query,"database");
-	$result = pg_query($conn, $query);
-	if (!$result) {
-		databaseError(pg_result_error($result));
-		return Array();
-	}
-	return pg_fetch_all($result);
-}
-
-function getRoutesBySuburb($suburb, $service_period = "") {
-         if ($service_period == "") $service_period = service_period();
-    global $conn;
-        $query = "SELECT DISTINCT service_id,trips.route_id,route_short_name,route_long_name
+WHERE service_id= :service_period order by route_long_name";
+	}
+	debug($query, "database");
+	$query = $conn->prepare($query);
+	$query->bindParam(":service_period", $service_period);
+	if ($destination != "") $query->bindParam(":destination", $destination);
+	$query->execute();
+	if (!$query) {
+		databaseError($conn->errorInfo());
+		return Array();
+	}
+	return $query->fetchAll();
+}
+function getRoutesBySuburb($suburb, $service_period = "")
+{
+	if ($service_period == "") $service_period = service_period();
+	global $conn;
+	$query = "SELECT DISTINCT service_id,trips.route_id,route_short_name,route_long_name
 FROM stop_times join trips on trips.trip_id = stop_times.trip_id
 join routes on trips.route_id = routes.route_id
 join stops on stops.stop_id = stop_times.stop_id
-WHERE zone_id LIKE '%$suburb;%' AND service_id='$service_period' ORDER BY route_short_name";
-        debug($query,"database");
-	$result = pg_query($conn, $query);
-	if (!$result) {
-		databaseError(pg_result_error($result));
-		return Array();
-	}
-	return pg_fetch_all($result);
-}
-
-function getRoutesNearby($lat, $lng, $limit = "", $distance = 500) {
-
-        
-                 if ($service_period == "") $service_period = service_period();
-                  if ($limit != "") $limit = " LIMIT $limit "; 
-    global $conn;
-        $query = "SELECT service_id,trips.route_id,route_short_name,route_long_name,min(stops.stop_id) as stop_id,
+WHERE zone_id LIKE ':suburb AND service_id=:service_period ORDER BY route_short_name";
+	debug($query, "database");
+	$query = $conn->prepare($query);
+	$query->bindParam(":service_period", $service_period);
+        $suburb = "%" . $suburb . ";%";
+	$query->bindParam(":suburb", $suburb);
+	$query->execute();
+	if (!$query) {
+		databaseError($conn->errorInfo());
+		return Array();
+	}
+	return $query->fetchAll();
+}
+function getRoutesNearby($lat, $lng, $limit = "", $distance = 500)
+{
+	if ($service_period == "") $service_period = service_period();
+	if ($limit != "") $limitSQL = " LIMIT :limit ";
+	global $conn;
+	$query = "SELECT service_id,trips.route_id,route_short_name,route_long_name,min(stops.stop_id) as stop_id,
         min(ST_Distance(position, ST_GeographyFromText('SRID=4326;POINT($lng $lat)'), FALSE)) as distance
 FROM stop_times
 join trips on trips.trip_id = stop_times.trip_id
 join routes on trips.route_id = routes.route_id
 join stops on stops.stop_id = stop_times.stop_id
-WHERE service_id='$service_period'
-AND ST_DWithin(position, ST_GeographyFromText('SRID=4326;POINT($lng $lat)'), $distance, FALSE)
+WHERE service_id=:service_period
+AND ST_DWithin(position, ST_GeographyFromText('SRID=4326;POINT($lng $lat)'), :distance, FALSE)
         group by service_id,trips.route_id,route_short_name,route_long_name
-        order by distance $limit";
-        debug($query,"database");
-	$result = pg_query($conn, $query);
-	if (!$result) {
-		databaseError(pg_result_error($result));
-		return Array();
-	}
-	return pg_fetch_all($result);
+        order by distance $limitSQL";
+	debug($query, "database");
+	$query = $conn->prepare($query);
+	$query->bindParam(":service_period", $service_period);
+	$query->bindParam(":distance", $distance);
+	$query->bindParam(":limit", $limit);
+	$query->execute();
+	if (!$query) {
+		databaseError($conn->errorInfo());
+		return Array();
+	}
+	return $query->fetchAll();
 }
 ?>

--- /dev/null
+++ b/include/db/servicealert-dao.inc.php
@@ -1,1 +1,15 @@
-
+<?php
+function getServiceOverride() {
+	global $conn;
+	$query = "Select * from calendar_dates where date = :date and exception_type = '1' LIMIT 1";
+	 debug($query,"database");
+	$query = $conn->prepare($query); // Create a prepared statement
+	$query->bindParam(":date", date("Ymd"));
+	$query->execute();
+	if (!$query) {
+		databaseError($conn->errorInfo());
+		return Array();
+	}
+	return $query->fetch(PDO::FETCH_ASSOC);
+}
+?>

--- a/include/db/stop-dao.inc.php
+++ b/include/db/stop-dao.inc.php
@@ -2,21 +2,23 @@
 function getStop($stopID)
 {
 	global $conn;
-	$query = "Select * from stops where stop_id = '$stopID' LIMIT 1";
+	$query = "Select * from stops where stop_id = :stopID LIMIT 1";
 	debug($query, "database");
-	$result = pg_query($conn, $query);
-	if (!$result) {
-		databaseError(pg_result_error($result));
+	$query = $conn->prepare($query);
+	$query->bindParam(":stopID", $stopID);
+	$query->execute();
+	if (!$query) {
+		databaseError($conn->errorInfo());
 		return Array();
 	}
-	return pg_fetch_assoc($result);
+	return $query->fetch(PDO::FETCH_ASSOC);
 }
 function getStops($timingPointsOnly = false, $firstLetter = "")
 {
 	global $conn;
 	$conditions = Array();
 	if ($timingPointsOnly) $conditions[] = "substr(stop_code,1,2) != 'Wj'";
-	if ($firstLetter != "") $conditions[] = "substr(stop_name,1,1) = '$firstLetter'";
+	if ($firstLetter != "") $conditions[] = "substr(stop_name,1,1) = :firstLetter";
 	$query = "Select * from stops";
 	if (sizeof($conditions) > 0) {
 		if (sizeof($conditions) > 1) {
@@ -27,41 +29,48 @@
 		}
 	}
 	$query.= " order by stop_name;";
-	debug($query, "database");
-	$result = pg_query($conn, $query);
-	if (!$result) {
-		databaseError(pg_result_error($result));
+	$query = $conn->prepare($query);
+        $query->bindParam(":firstLetter", $firstLetter);
+	$query->execute();
+	if (!$query) {
+		databaseError($conn->errorInfo());
 		return Array();
 	}
-	return pg_fetch_all($result);
+	return $query->fetchAll();
 }
 function getNearbyStops($lat, $lng, $limit = "", $distance = 1000)
 {
 	if ($lat == null || $lng == null) return Array();
-	if ($limit != "") $limit = " LIMIT $limit ";
+	if ($limit != "") $limitSQL = " LIMIT :limit ";
 	global $conn;
 	$query = "Select *, ST_Distance(position, ST_GeographyFromText('SRID=4326;POINT($lng $lat)'), FALSE) as distance
-        from stops WHERE ST_DWithin(position, ST_GeographyFromText('SRID=4326;POINT($lng $lat)'), $distance, FALSE)
-        order by distance $limit;";
+        from stops WHERE ST_DWithin(position, ST_GeographyFromText('SRID=4326;POINT($lng $lat)'), :distance, FALSE)
+        order by distance $limitSQL;";
 	debug($query, "database");
-	$result = pg_query($conn, $query);
-	if (!$result) {
-		databaseError(pg_result_error($result));
+        $query = $conn->prepare($query);
+	$query->bindParam(":distance", $distance);
+	$query->bindParam(":limit", $limit);
+	$query->execute();
+	if (!$query) {
+		databaseError($conn->errorInfo());
 		return Array();
 	}
-	return pg_fetch_all($result);
+	return $query->fetchAll();
 }
 function getStopsBySuburb($suburb)
 {
 	global $conn;
-	$query = "Select * from stops where zone_id LIKE '%$suburb;%' order by stop_name;";
+	$query = "Select * from stops where zone_id LIKE :suburb order by stop_name;";
 	debug($query, "database");
-	$result = pg_query($conn, $query);
-	if (!$result) {
-		databaseError(pg_result_error($result));
+	$query = $conn->prepare($query);
+        $suburb = "%" . $suburb . ";%";
+	$query->bindParam(":suburb", $suburb);
+	$query->execute();
+	if (!$query) {
+		databaseError($conn->errorInfo());
 		return Array();
 	}
-	return pg_fetch_all($result);
+	return $query->fetchAll();
 }
 function getStopRoutes($stopID, $service_period)
 {
@@ -69,19 +78,21 @@
 	global $conn;
 	$query = "SELECT service_id,trips.route_id,route_short_name,route_long_name
 FROM stop_times join trips on trips.trip_id =
-stop_times.trip_id join routes on trips.route_id = routes.route_id WHERE stop_id = '$stopID' AND service_id='$service_period'";
+stop_times.trip_id join routes on trips.route_id = routes.route_id WHERE stop_id = :stopID AND service_id=:service_period";
 	debug($query, "database");
-	$result = pg_query($conn, $query);
-	if (!$result) {
-		databaseError(pg_result_error($result));
+	$query = $conn->prepare($query);
+	$query->bindParam(":service_period", $service_period);
+	$query->bindParam(":stopID", $stopID);
+	$query->execute();
+	if (!$query) {
+		databaseError($conn->errorInfo());
 		return Array();
 	}
-	return pg_fetch_all($result);
+	return $query->fetchAll();
 }
 function getStopTrips($stopID, $service_period = "", $afterTime = "")
 {
 	if ($service_period == "") $service_period = service_period();
-	$afterCondition = "AND arrival_time > '$afterTime'";
 	global $conn;
 	if ($afterTime != "") {
 		$query = " SELECT stop_times.trip_id,stop_times.arrival_time,stop_times.stop_id,stop_sequence,service_id,trips.route_id,route_short_name,route_long_name, end_times.arrival_time as end_time
@@ -90,10 +101,10 @@
 stop_times.trip_id
 join routes on trips.route_id = routes.route_id , (SELECT trip_id,max(arrival_time) as arrival_time from stop_times
 	WHERE stop_times.arrival_time IS NOT NULL group by trip_id) as end_times 
-WHERE stop_times.stop_id = '$stopID'
+WHERE stop_times.stop_id = :stopID
 AND stop_times.trip_id = end_times.trip_id
-AND service_id='$service_period'
-AND end_times.arrival_time > '$afterTime'
+AND service_id=:service_period
+AND end_times.arrival_time > :afterTime
 ORDER BY end_time";
 	}
 	else {
@@ -102,17 +113,21 @@
 join trips on trips.trip_id =
 stop_times.trip_id
 join routes on trips.route_id = routes.route_id
-WHERE stop_times.stop_id = '$stopID'
-AND service_id='$service_period'
+WHERE stop_times.stop_id = :stopID
+AND service_id=:service_period
 ORDER BY arrival_time";
 	}
 	debug($query, "database");
-	$result = pg_query($conn, $query);
-	if (!$result) {
-		databaseError(pg_result_error($result));
+	$query = $conn->prepare($query);
+	$query->bindParam(":service_period", $service_period);
+	$query->bindParam(":stopID", $stopID);
+        if ($afterTime != "") $query->bindParam(":afterTime", $afterTime);
+	$query->execute();
+	if (!$query) {
+		databaseError($conn->errorInfo());
 		return Array();
 	}
-	return pg_fetch_all($result);
+	return $query->fetchAll();
 }
 function getStopTripsWithTimes($stopID, $time = "", $service_period = "", $time_range = "", $limit = "")
 {

--- a/include/db/trip-dao.inc.php
+++ b/include/db/trip-dao.inc.php
@@ -4,15 +4,17 @@
 	global $conn;
 	$query = "Select * from trips
 	join routes on trips.route_id = routes.route_id
-	where trip_id = '$tripID'
+	where trip_id =	:tripID
 	LIMIT 1";
 	debug($query, "database");
-	$result = pg_query($conn, $query);
-	if (!$result) {
-		databaseError(pg_result_error($result));
-		return Array();
-	}
-	return pg_fetch_assoc($result);
+	$query = $conn->prepare($query);
+	$query->bindParam(":tripID", $tripID);
+	$query->execute();
+	if (!$query) {
+		databaseError($conn->errorInfo());
+		return Array();
+	}
+	return $query->fetch(PDO::FETCH_ASSOC);
 }
 function getTripShape()
 {
@@ -58,14 +60,16 @@
 join trips on trips.trip_id = stop_times.trip_id
 join routes on trips.route_id = routes.route_id
 join stops on stops.stop_id = stop_times.stop_id
-WHERE trips.trip_id = '$tripID' $range ORDER BY stop_sequence";
-	debug($query, "database");
-	$result = pg_query($conn, $query);
-	if (!$result) {
-		databaseError(pg_result_error($result));
-		return Array();
-	}
-	$stopTimes = pg_fetch_all($result);
+WHERE trips.trip_id = :tripID $range ORDER BY stop_sequence";
+	debug($query, "database");
+	$query = $conn->prepare($query);
+	$query->bindParam(":tripID", $tripID);
+	$query->execute();
+	if (!$query) {
+		databaseError($conn->errorInfo());
+		return Array();
+	}
+	$stopTimes = $query->fetchAll();
 	$cur_timepoint = Array();
 	$next_timepoint = Array();
 	$distance_between_timepoints = 0.0;
@@ -73,114 +77,158 @@
 	$rv = Array();
 	foreach ($stopTimes as $i => $stopTime) {
 		if ($stopTime['arrival_time'] != "") {
-		    // is timepoint
+			// is timepoint
 			$cur_timepoint = $stopTime;
 			$distance_between_timepoints = 0.0;
 			$distance_traveled_between_timepoints = 0.0;
 			if ($i + 1 < sizeof($stopTimes)) {
 				$k = $i + 1;
-				$distance_between_timepoints += distance($stopTimes[$k - 1]["stop_lat"], $stopTimes[$k - 1]["stop_lon"], $stopTimes[$k]["stop_lat"], $stopTimes[$k]["stop_lon"]);
+				$distance_between_timepoints+= distance($stopTimes[$k - 1]["stop_lat"], $stopTimes[$k - 1]["stop_lon"], $stopTimes[$k]["stop_lat"], $stopTimes[$k]["stop_lon"]);
 				while ($stopTimes[$k]["arrival_time"] == "" && $k + 1 < sizeof($stopTimes)) {
-					$k += 1;
+					$k+= 1;
 					//echo "k".$k;
-					$distance_between_timepoints += distance($stopTimes[$k - 1]["stop_lat"], $stopTimes[$k - 1]["stop_lon"], $stopTimes[$k]["stop_lat"], $stopTimes[$k]["stop_lon"]);
+					$distance_between_timepoints+= distance($stopTimes[$k - 1]["stop_lat"], $stopTimes[$k - 1]["stop_lon"], $stopTimes[$k]["stop_lat"], $stopTimes[$k]["stop_lon"]);
 				}
 				$next_timepoint = $stopTimes[$k];
 				$rv[] = $stopTime;
 			}
 		}
 		else {
-		    // is untimed point
-		    //echo "i".$i;
-			$distance_traveled_between_timepoints += distance($stopTimes[$i - 1]["stop_lat"], $stopTimes[$i - 1]["stop_lon"], $stopTimes[$i]["stop_lat"], $stopTimes[$i]["stop_lon"]);
+			// is untimed point
+			//echo "i".$i;
+			$distance_traveled_between_timepoints+= distance($stopTimes[$i - 1]["stop_lat"], $stopTimes[$i - 1]["stop_lon"], $stopTimes[$i]["stop_lat"], $stopTimes[$i]["stop_lon"]);
 			//echo "$distance_traveled_between_timepoints / $distance_between_timepoints<br>";
 			$distance_percent = $distance_traveled_between_timepoints / $distance_between_timepoints;
 			if ($next_timepoint["arrival_time"] != "") {
-			$total_time = strtotime($next_timepoint["arrival_time"]) - strtotime($cur_timepoint["arrival_time"]);
-			//echo strtotime($next_timepoint["arrival_time"])." - ".strtotime($cur_timepoint["arrival_time"])."<br>";
-			$time_estimate = ($distance_percent * $total_time) + strtotime($cur_timepoint["arrival_time"]);
-			$stopTime["arrival_time"] = date("H:i:s", $time_estimate);
-			} else {
-			    $stopTime["arrival_time"] = $cur_timepoint["arrival_time"];
+				$total_time = strtotime($next_timepoint["arrival_time"]) - strtotime($cur_timepoint["arrival_time"]);
+				//echo strtotime($next_timepoint["arrival_time"])." - ".strtotime($cur_timepoint["arrival_time"])."<br>";
+				$time_estimate = ($distance_percent * $total_time) + strtotime($cur_timepoint["arrival_time"]);
+				$stopTime["arrival_time"] = date("H:i:s", $time_estimate);
+			}
+			else {
+				$stopTime["arrival_time"] = $cur_timepoint["arrival_time"];
 			}
 			$rv[] = $stopTime;
 			//var_dump($rv);
+			
 		}
 	}
 	return $rv;
 }
-function getTimeInterpolatedTripAtStop($tripID, $stop_sequence)
-{
-    global $conn;
-    // limit interpolation to between nearest actual points.
-    $prevTimePoint = pg_fetch_assoc(pg_query($conn," SELECT trip_id,stop_id,
+function getTripPreviousTimePoint($tripID, $stop_sequence)
+{
+	global $conn;
+	$query = " SELECT trip_id,stop_id,
 	stop_sequence
 FROM stop_times
-WHERE trip_id = '$tripID' and stop_sequence < $stop_sequence and stop_times.arrival_time IS NOT NULL ORDER BY stop_sequence DESC LIMIT 1"));
-    $nextTimePoint = pg_fetch_assoc(pg_query($conn," SELECT trip_id,stop_id,
+WHERE trip_id = :tripID and stop_sequence < :stop_sequence
+and stop_times.arrival_time IS NOT NULL ORDER BY stop_sequence DESC LIMIT 1";
+	debug($query, "database");
+	$query = $conn->prepare($query);
+	$query->bindParam(":tripID", $tripID);
+	$query->bindParam(":stop_sequence", $stop_sequence);
+	$query->execute();
+	if (!$query) {
+		databaseError($conn->errorInfo());
+		return Array();
+	}
+	return $query->fetch(PDO::FETCH_ASSOC);
+}
+function getTripNextTimePoint($tripID, $stop_sequence)
+{
+	global $conn;
+	$query = " SELECT trip_id,stop_id,
 	stop_sequence
 FROM stop_times
-WHERE trip_id = '$tripID' and stop_sequence > $stop_sequence and stop_times.arrival_time IS NOT NULL ORDER BY stop_sequence LIMIT 1"));
-    $range = "AND stop_sequence >= '{$prevTimePoint['stop_sequence']}' AND stop_sequence <= '{$nextTimePoint['stop_sequence']}'";
-    	foreach (getTimeInterpolatedTrip($tripID,$range) as $tripStop) {
+WHERE trip_id = :tripID and stop_sequence > :stop_sequence
+and stop_times.arrival_time IS NOT NULL ORDER BY stop_sequence LIMIT 1";
+	debug($query, "database");
+	$query = $conn->prepare($query);
+	$query->bindParam(":tripID", $tripID);
+	$query->bindParam(":stop_sequence", $stop_sequence);
+	$query->execute();
+	if (!$query) {
+		databaseError($conn->errorInfo());
+		return Array();
+	}
+	return $query->fetch(PDO::FETCH_ASSOC);
+}
+function getTimeInterpolatedTripAtStop($tripID, $stop_sequence)
+{
+	global $conn;
+	// limit interpolation to between nearest actual points.
+	$prevTimePoint = getTripPreviousTimePoint($tripID, $stop_sequence);
+	$nextTimePoint = getTripNextTimePoint($tripID, $stop_sequence);
+	$range = "AND stop_sequence >= '{$prevTi