PHP array in foreach loop

Not sure if I even approach this correctly, but I need to grab the coordinates from two different addresses stored in a database. I will need to make an array with the two coordinates to use later to calculate the distance between them.

This is my code so far, I’m able to get the coordinates from one of the two addresses only.

$dbQuery = "SELECT CS.cust_address AS sa, CS.cust_city AS sc, CS.cust_state AS ss, CS.cust_zip AS sz, CR.cust_address AS ra, CR.cust_city AS rc, CR.cust_state AS rs, CR.cust_zip AS rz 
        FROM customers 
          INNER JOIN customers CS ON (CS.cust_id = ".$shipper.") 
          INNER JOIN customers CR ON (CR.cust_id = ".$receiver.")
        LIMIT 1";

$data = getContent($dbQuery);
foreach($data as $row) {

//Make a variable with the full address, city, state and zipcode.
    $shpLocation = $row['sa'] . ' ' . $row['sc'] . ',' . $row['ss'] . ' ' . $row['sz'];
    $rcvLocation = $row['ra'] . ' ' . $row['rc'] . ',' . $row['rs'] . ' ' . $row['rz'];


//Get the latitude and longitude of the above address variables
    $address =
    $prepAddr = str_replace(' ','+',$address);
    $geocode=file_get_contents('https://maps.google.com/maps/api/geocode/json?address='.$prepAddr.'&sensor=false');
    $output= json_decode($geocode);
    $latitude = $output->results[0]->geometry->location->lat;
    $longitude = $output->results[0]->geometry->location->lng;

}

If a two dimensional plane would be accurate enough using the pythagorean theorem should work. It would be a bit more involved if coordinates straddle the prime meridian / equator but still doable. eg.

x1 - x2 = side x
y1 - y2 = side y
side x squared + side y squared = distance squared
square root of distance squared = distance between the two points. (the hypotenuse)

First of all you should not use your statements this way. As long as you do not know where the data comes from, you are vulnerable to SQL injections. Use Prepared Statements instead.

I do not see why you are joining anything, just use WHERE cust_id = ? or cust_id = ? with [$shipper, $receiver]. You can flatten the resulting array and join the data together afterwards.

Are you sure you can get multiple results by the API?

A good idea is to ALWAYS use prepared statements, no matter who/what the source of the data being used with a query comes from so that if you switch the source from one which you have control over to one where you don’t, you wont accidentally open up a security hole

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.