So I am trying to do a radius type search with multiple variables, I have the Lat/Long stored for each city in my database, but I have noticed that most solutions to what I want to do require me to query the whole database (which could eventually be 50,000+ rows) to use the value of the stored lat/long in a function.
Is there anyway to use this stored database value without getting it from the query first and just use it during my query.
This is how I do it right now, but it requires so much I think, specially once the database reaches 100,000 + rows it might take some time to go through each row, it would be better if I could check the distance during the query I think so I could filter results better as well without having to check every single row.
function getLocation($address) {
    if (!empty($address)) {
        //Formatted address
        $formattedAddr = str_replace(' ', '+', $address);
        //Send request and receive json data by address
        $geocodeFromAddr = file_get_contents('http://maps.googleapis.com/maps/api/geocode/json?address=' . $formattedAddr . '&sensor=true_or_false');
        $output1 = json_decode($geocodeFromAddr);
        //Get latitude and longitute from json data
        $latitude = $output1->results[0]->geometry->location->lat;
        $longitude = $output1->results[0]->geometry->location->lng;
        return "$latitude,$longitude";
    } 
    else {
        return false;
    }
}
function GetDrivingDistance($lat1, $lat2, $long1, $long2) {
    $url = "https://maps.googleapis.com/maps/api/distancematrix/json?origins=" . $lat1 . "," . $long1 . "&destinations=" . $lat2 . "," . $long2 . "&mode=driving&units=imperial";
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_PROXYPORT, 3128);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
    $response = curl_exec($ch);
    curl_close($ch);
    $response_a = json_decode($response, true);
    $dist = $response_a['rows'][0]['elements'][0]['distance']['text'];
    $time = $response_a['rows'][0]['elements'][0]['duration']['text'];
    return $dist;
    //return array('distance' => $dist, 'time' => $time);
}
$sql = "SELECT * FROM mytable WHERE `date` >= '$selected_date'";
if ($length && !empty($length)) {
    $sql.= " AND `length`<='$length'";
}
$sql.= " ORDER BY date_created DESC";
$CITY = "DALLAS, TX";
 // FOR TESTING
$SLAT = getLocation($CITY);
$oparr = split("\,", $SLAT);
$FLAT = $oparr[0];
$FLONG = $oparr[1];
while ($row = $result->fetch_assoc()) {
    $id = $row['id'];
    $city = $row['city'];
    $state = $row['state'];
    $lat = $row['lats'];
    $long = $row['longs'];
    $distance = GetDrivingDistance($FLAT, $lat, $FLONG, $long);
    if ($distance <= 200) {
        // SHOW TABLE RESULTS
    } 
    else {
        echo "No results";
    }
}
 
     
     
     
    