I am fairly new to php and mysql, the php code below calculates the distance between two given postcode and returns the distance as output.
What I am trying to achieve is to be able to get distance values for all postcodes within the database table that have the same value as $secondPC, although their latitude and longitude values maybe different.
Any help will be most appreciated thanks.
$dbName=" ";
$dbUsername=" ";
$dbPassword=" ";
$fromPC=$_POST['fromPC'];
$toPC=$_POST['toPC'];
function getDistance($lat1, $long1, $lat2, $long2, $unit)
{
if($unit=="miles"){
$earth = 3960;
}else{
$earth = 6371;
}
$lat1 = deg2rad($lat1);
$long1= deg2rad($long1);
$lat2 = deg2rad($lat2);
$long2= deg2rad($long2);
$dlong=$long2-$long1;
$dlat=$lat2-$lat1;
$sinlat=sin($dlat/2);
$sinlong=sin($dlong/2);
$a=($sinlat*$sinlat)+cos($lat1)*cos($lat2)*($sinlong*$sinlong);
$c=2*asin(min(1,sqrt($a)));
$d=round($earth*$c);
return $d;
}
if( (!empty($fromPC)) && (!empty($toPC)) )
{
mysql_connect(localhost,$dbUsername,$dbPassword);
@mysql_select_db($dbName) or die( "Unable to select database");
$firstPC = strtoupper(preg_replace("/[^a-zA-Z0-9]/","",$fromPC ));
$secondPC = strtoupper(preg_replace("/[^a-zA-Z0-9]/","",$toPC ));
$query = 'SELECT `latitude`, `longitude` FROM `uk_postcodes` WHERE `postcode`="'.$firstPC.'";';
$result = mysql_query($query);
$first = mysql_fetch_row($result);
$checkFirst=mysql_num_rows($result);
$query = 'SELECT `latitude`, `longitude` FROM `uk_postcodes` WHERE `part_type` LIKE "'.$secondPC.'";';
$result = mysql_query($query);
$second = mysql_fetch_row($result);
$checkSecond=mysql_num_rows($result);
if( ($checkFirst<1) || ($checkSecond<1) ){
$outputResults="Unrecognised postcode entered.";
}else{
$distance = getDistance($first[0], $first[1], $second[0], $second[1], "miles");
$outputResults = "Nearest Store is: ".$distance." miles from you";
$term = "$toPC";
$qry = ("SELECT $first[0],$first[1],$second[0],$second[1], id FROM uk_postcodes WHERE part_type LIKE '%$term%'");
$res = mysql_query($qry);
function mysql_fetch_all($res) {
while($row=mysql_fetch_array($res)) {
$return[] = $row;
}
return $return;
}
function create_table($dataArr) {
echo "";
for($j = 0; $j < count($dataArr); $j++) {
echo "".$dataArr[$j]."";
}
echo "";
}
$all = mysql_fetch_all($res);
echo "";
for($i = 0; $i < count($all); $i++) {
create_table($all[$i]);
echo $all[$i];
echo $all[$i];
}
echo "
";
$dist = getDistance($first[0], $first[1], $all[$i][0], $all[$i][1], "miles");
echo $dist;
}