0

I have the following code in the header.php file for my website:

<?php
mysql_select_db($database_ecsdb, $ecsdb);
$query_getCat = "SELECT DISTINCT category FROM food ORDER BY category DESC";
$getCat = mysql_query($query_getCat, $ecsdb) or die(mysql_error());
$row_getCat = mysql_fetch_assoc($getCat);
$totalRows_getCat = mysql_num_rows($getCat);

mysql_select_db($database_ecsdb, $ecsdb);
$query_getZip = "SELECT * FROM food ORDER BY zip DESC";
$getZip = mysql_query($query_getZip, $ecsdb) or die(mysql_error());
$row_getZip = mysql_fetch_assoc($getZip);
$totalRows_getZip = mysql_num_rows($getZip);
?>

<div id="header" >
<div id="search">
<h2> Search for Organizations</h2>
<br>

<form action="../spsucares2/search.php" method="get">

<label name="title">
    Category:
        <select name="category">      
          <?php
    do {  
    ?>
              <option value="<?php echo $row_getCat['category']?>"><?php echo $row_getCat['category']?></option>
              <?php
    } while ($row_getCat = mysql_fetch_assoc($getCat));
      $rows = mysql_num_rows($getCat);
      if($rows > 0) {
          mysql_data_seek($getCat, 0);
          $row_getCat = mysql_fetch_assoc($getCat);
      }
    ?>
    </select>
    </label>

  <label>Enter your ZIP Code:
     <input maxlength="5" name="zipcode" size="6" type="text" /></label> </br>

  <label>Select a distance:</label>
        <select name="distance">
          <option>5</option>
          <option>10</option>
          <option>25</option>
          <option>50</option>
          <option>100</option>
        </select>

  <input name="submit" type="submit" value="search" />


</form>

<?php
        if(isset($_POST['submit'])) {
            if(!preg_match('/^[0-9]{5}$/', $_POST['zipcode'])) {
                echo "<p><strong>You did not enter a properly formatted ZIP Code.</strong> Please try again.</p>\n";
            }
            elseif(!preg_match('/^[0-9]{1,3}$/', $_POST['distance'])) {
                echo "<p><strong>You did not enter a properly formatted distance.</strong> Please try again.</p>\n";
            }
            else {
                //connect to db server; select database
                $link = mysql_connect('localhost', 'root', 'fisher36') or die('Cannot connect to database server');
                mysql_select_db('cares') or die('Cannot select database');

                //query for coordinates of provided ZIP Code
                if(!$rs = mysql_query("SELECT * FROM zip WHERE zip_code = '$_POST[zipcode]'")) {
                    echo "<p><strong>There was a database error attempting to retrieve your ZIP Code.</strong> Please try again.</p>\n";
                }
                else {
                    if(mysql_num_rows($rs) == 0) {
                        echo "<p><strong>No database match for provided ZIP Code.</strong> Please enter a new ZIP Code.</p>\n"; 
                    }
                    else {
                        //if found, set variables
                        $row = mysql_fetch_array($rs);
                        $lat1 = $row['latitude'];
                        $lon1 = $row['longitude'];
                        $d = $_POST['distance'];
                        $r = 3959;

                        //compute max and min latitudes / longitudes for search square
                        $latN = rad2deg(asin(sin(deg2rad($lat1)) * cos($d / $r) + cos(deg2rad($lat1)) * sin($d / $r) * cos(deg2rad(0))));
                        $latS = rad2deg(asin(sin(deg2rad($lat1)) * cos($d / $r) + cos(deg2rad($lat1)) * sin($d / $r) * cos(deg2rad(180))));
                        $lonE = rad2deg(deg2rad($lon1) + atan2(sin(deg2rad(90)) * sin($d / $r) * cos(deg2rad($lat1)), cos($d / $r) - sin(deg2rad($lat1)) * sin(deg2rad($latN))));
                        $lonW = rad2deg(deg2rad($lon1) + atan2(sin(deg2rad(270)) * sin($d / $r) * cos(deg2rad($lat1)), cos($d / $r) - sin(deg2rad($lat1)) * sin(deg2rad($latN))));

                        //display information about starting point
                        //provide max and min latitudes / longitudes
                        echo "<table class=\"bordered\" cellspacing=\"0\">\n";
                        //echo "<tr><th>City</th><th>State</th><th>Lat</th><th>Lon</th><th>Max Lat (N)</th><th>Min Lat (S)</th><th>Max Lon (E)</th><th>Min Lon (W)</th></tr>\n";
                        //echo "<tr><td>$row[city]</td><td>$row[state]</td><td>$lat1</td><td>$lon1</td><td>$latN</td><td>$latS</td><td>$lonE</td><td>$lonW</td></tr>\n";
                        echo "</table>\n<br />\n";

                        //find all coordinates within the search square's area
                        //exclude the starting point and any empty city values
                        $query = "SELECT * FROM zip WHERE (latitude <= $latN AND latitude >= $latS AND longitude <= $lonE AND longitude >= $lonW) AND (latitude != $lat1 AND longitude != $lon1) AND city != '' ORDER BY state, city, latitude, longitude";
                        if(!$rs = mysql_query($query)) {
                            echo "<p><strong>There was an error selecting nearby ZIP Codes from the database.</strong></p>\n";
                        }
                        elseif(mysql_num_rows($rs) == 0) {
                            echo "<p><strong>No nearby ZIP Codes located within the distance specified.</strong> Please try a different distance.</p>\n";                               
                        }
                        else {
                            //output all matches to screen
                            echo "<table class=\"bordered\" cellspacing=\"0\">\n";
                            echo "<tr><th>City</th><th>State</th><th>ZIP Code</th><th>Latitude</th><th>Longitude</th><th>Miles, Point A To B</th></tr>\n";
                            while($row = mysql_fetch_array($rs)) {
                                echo "<tr><td>$row[city]</td><td>$row[state]</td><td>$row[zip_code]</td><td>$row[latitude]</td><td>$row[longitude]</td><td>";
                                echo acos(sin(deg2rad($lat1)) * sin(deg2rad($row['latitude'])) + cos(deg2rad($lat1)) * cos(deg2rad($row['latitude'])) * cos(deg2rad($row['longitude']) - deg2rad($lon1))) * $r;
                                echo "</td>  </tr>\n";  
                            }
                            echo "</table>\n<br />\n";
                        }
                    }
                }
            }
        }
    ?>


</div>


</div>
<br clear="all" />

It allows a user to search for an organization within a selected radius. However, my search functionality is not working properly in that it does not filter the results but rather returns all of the results. Also, if both categories are selected it does not work to search both but only one. How can I fix this please?

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
  • That's because you don't specify any limits. If the `zips` table has `lat` and `long` columns, you can do it with the [Haversine formula](http://en.wikipedia.org/wiki/Haversine_formula) within your SQL. – Jon Apr 02 '13 at 18:32
  • Are you sure your calculations for `$latN' , `$latS`, `$lonE`, '$lonW` are correct? Otherwise you'll be searching beyond your radius instead of inside. – xpy Apr 02 '13 at 18:35
  • 1
    Please, before you do *anything* else, read up on [proper SQL escaping](http://bobby-tables.com/php) to avoid serious career damaging [SQL injection bugs](http://bobby-tables.com/). Do not use `mysql_query` in new code, it's dangerous, deprecated, and will be removed from future versions of PHP. [PDO](http://net.tutsplus.com/tutorials/php/why-you-should-be-using-phps-pdo-for-database-access/) takes only half an hour [to learn](http://net.tutsplus.com/tutorials/php/why-you-should-be-using-phps-pdo-for-database-access/), so unless you're saddled with some legacy project, use that instead. – tadman Apr 02 '13 at 18:36
  • Hi Jon, thanks for your response. THe table does have lat and long columns, where exactly in the code would I specify the limit? I am new to php sorry for the newbie questions. – jane Brown Apr 02 '13 at 18:36
  • This code will not be used on a live site, it is only for learning purposes...but thanks for your feedback and in the future I will definitely not use mysql_query. – jane Brown Apr 02 '13 at 18:38
  • @janeBrown look [at this answer](http://stackoverflow.com/a/574736/1745573) for how to do it within the SQL statement. =] – Jon Apr 02 '13 at 18:45

0 Answers0