Search for city state zip - php
So i already have a database of locations of every city, state, zip.
I am currently working on how to do a search and get results of surrounding zip codes x miles away, and have run into some trouble.
I successfully have the search working for you to type in the zip code, since it is a predefined value. But am having trouble with results of a city, state. Currently it only works if you type in just the city name ex "Chicago"... But Does not work if you type in "Chicago, IL".
Here is the code for the $_GET of the search form, searchval
Please Help!
$searchval = $mysql->escape_data($_GET['searchval']);
if (!empty($searchval))
{
if(preg_match("~\d{5}~", $searchval)) {
$zip = $searchval;
}
else {
$city = $searchval;
}
} else
{
$error .= "<div id='Error'>Please enter zip</div>";
$zip = false;
}
Below is the code that actually takes the $zip or $city and gets the surrounding zip codes. if you enter a zip code, it works successfully. If you enter just a city name, it works successfully. If you enter "Chicago, IL" it does not work.
<?php
//if user entered a city ex. "Chicago"
if(isset($city)) {
$q = 'SELECT City, State, ZipCode FROM zipcodes WHERE City like "'. $city .'%" ORDER BY ZipCode ASC Limit 0,10';
$result = $mysql->query($q);
$row = mysqli_fetch_array($result);
$zip = $row[2];
if(mysqli_num_rows($result) != 1) {
echo"Did you mean...<br />";
while($row = mysqli_fetch_array($result)) {
echo "<a href='" .$_SERVER['PHP_SELF'] . "?searchval=".$row[2]."&miles=".$miles."'>" . $row[0] . " " . $row[1] . " " . $row[2] . "</a><br />";
}
}
}
$zcr = new ZipCodesRange($mysql,$zip,$miles);
$zcr->setNewOrigin($zip);
//if user entered a zip code ex. "08026"
if($zcr->validateZipCode($zip)) {
$citystate=$zcr->getCityState($zip);
echo "Zip Codes Within " . $miles ." miles of " . $citystate[0] . ", " . $citystate[1] . " " . $zip;
}
$zcr->setZipCodesInRange();
$zipArray = $zcr->getZipCodesInRange();
asort($zipArray);
$z = implode(",", array_keys($zipArray));
$q = "SELECT * FROM " . TBL_PUBS . " WHERE zip IN ($z) AND( status = 'Pending' OR status = 'Active' )";
$result = $mysql->query($q);
while ($row = $result->fetch_object()) {
$lonlat=$zcr->getLonLat($row->zip);
$distance = $zcr->calculateDistance($lonlat[1], $lonlat[0], $zip);
?>
Was able to solve it using this function...
returns an array of $arr[city] $arr[state] $arr[zip]
function retcszarr($loc){
$usstatenames=array('ALABAMA','ALASKA','AMERICAN SAMOA','ARIZONA','ARKANSAS','CALIFORNIA','COLORADO','CONNECTICUT','DELAWARE','DISTRICT OF COLUMBIA','FEDERATED STATES OF MICRONESIA','FLORIDA','GEORGIA','GUAM','HAWAII','IDAHO','ILLINOIS','INDIANA','IOWA','KANSAS','KENTUCKY','LOUISIANA','MAINE','MARSHALL ISLANDS','MARYLAND','MASSACHUSETTS','MICHIGAN','MINNESOTA','MISSISSIPPI','MISSOURI','MONTANA','NEBRASKA','NEVADA','NEW HAMPSHIRE','NEW JERSEY','NEW MEXICO','NEW YORK','NORTH CAROLINA','NORTH DAKOTA','NORTHERN MARIANA ISLANDS','OHIO','OKLAHOMA','OREGON','PALAU','PENNSYLVANIA','PUERTO RICO','RHODE ISLAND','SOUTH CAROLINA','SOUTH DAKOTA','TENNESSEE','TEXAS','UTAH','VERMONT','VIRGIN ISLANDS','VIRGINIA','WASHINGTON','WEST VIRGINIA','WISCONSIN','WYOMING');
$usstateabbrs=array('AL','AK','AS','AZ','AR','CA','CO','CT','DE','DC','FM','FL','GA','GU','HI','ID','IL','IN','IA','KS','KY','LA','ME','MH','MD','MA','MI','MN','MS','MO','MT','NE','NV','NH','NJ','NM','NY','NC','ND','MP','OH','OK','OR','PW','PA','PR','RI','SC','SD','TN','TX','UT','VT','VI','VA','WA','WV','WI','WY');
if(strpos($loc,',')!==false){
$parts=array_map('trim',explode(',',$loc));
$location['city']=strtoupper($parts[0]);
preg_match('/([^ ]*)(?: +([^ ]+))?/',$parts[1],$statezip);
if(isset($statezip[1])){
$location['state']=strtoupper($statezip[1]);
}
if(isset($statezip[2])){
$location['zip']=$statezip[2];
}
} else {
$parts=array_map('trim',explode(' ',$loc));
while(count($parts)>0){
$part=strtoupper(array_pop($parts));
if(in_array($part,$usstateabbrs)){
$location['state']=$part;
} elseif (in_array($part,$usstatenames)){
$location['state']=$usstateabbrs[array_search($part,$usstatenames)];
} elseif (preg_match('/\d+(?:-\d+)?/',$part,$zip)){
$location['zip']=$zip[0];
} else {
$location['city']=strtoupper(implode(' ',$parts)."$part");
break;
}
}
}
ksort($location);
return $location;
}
Related
Need to keep blank field with the data on the table
So I'm trying to have the user update this table, but if the field is left blank i'd like the data to be left alone, not change it to a blank field or null, any ideas? <? elseif ($Code == "U") { $sql = "UPDATE movieDATA SET Name = '$Name', Genre = '$Genre', Starring = '$Starring', Year = '$Year', BoxOffice = '$BoxOffice' where IDNO = '$idno'"; $result= mysqli_query($link,$sql) or die(mysqli_error($link)); $showresult = mysqli_query($link,"SELECT * from movieDATA") or die("Invalid query: " . mysqli_error($link)); while ($row = mysqli_fetch_array($showresult)) { echo ("<br> ID = ". $row["IDNO"] . "<br> NAME = " . $row["Name"] . "<br>"); echo("Genre = " . $row["Genre"] . "<br> Starring = " . $row["Starring"] . "<br>"); echo("Year = " . $row["Year"] . "<br> Box Office = " . $row["BoxOffice"] . "<br>"); } } ?>
$fields = array(); // Take a blank array of fields and values. $Name = trim($Name); // Trim the variable, user may add only spaces $Genre = trim($Genre); // Do this for all variables. $Starring = trim($Starring); $Year = trim($Year); $BoxOffice = trim($BoxOffice); if (! empty($Name)) { // If user has filled the field, append to array. $fields[] = "Name = '$Name'"; } if (! empty($Genre)) { $fields[] = "Name = '$Genre'"; } if (! empty($Starring)) { $fields[] = "Name = '$Starring'"; } if (! empty($Year)) { $fields[] = "Name = '$Year'"; } if (! empty($BoxOffice)) { $fields[] = "Name = '$BoxOffice'"; } if (! empty($fields)) { // If the array is not empty, go for Query. $sql = "UPDATE movieDATA SET "; // If user has not added any field value, $sql .= implode(', ', $fields); // no SQL Query will be fired. $sql .= " WHERE IDNO = '$idno'"; } Your requirement: Not to update the fields which user has left blank. Solution: Add if condition to check if every field is filled up.
One way to do this: $q_set = []; if (!empty($Name)) { $q_set []= "Name = '$Name'"; } if (!empty($Genre)) { $q_set []= "Genre = '$Genre'"; } /* ... */ if (!empty($q_set)) { $sql = "UPDATE movieDATA SET " . implode(',', $q_set) . " WHERE IDNO = '$idno'"; } Note, that the variables passed into SQL should be escaped
PHP array implode keys and values to function
I'm not too familiar with PHP arrays, I have the following code that generates query to output the results needed. $allstore = $_POST['store']; function createSelect($allstore) { if (empty($allstore)) return ""; $querySelect = ""; $queryJoin = ""; $baseTable = ""; foreach ($allstore as $store => $value) { if (!$querySelect) { $baseTable = $store; $querySelect = "SELECT " . $store . ".item_no, " . $store . ".actual_price, " . $store . ".selling_price, " . $store . ".qty as " . $store; } else { $querySelect .= ", " . $store . ".qty as " . $store; $queryJoin .= " INNER JOIN " . $store . " ON " . $baseTable . ".item_no = " . $store . ".item_no"; } } $querySelect .= " FROM " . $baseTable; $query = $querySelect . $queryJoin; return $query; } //Stores to be shown $allstore = ['s_M9' =>0 , 's_M10' =>1]; $query = (createSelect($allstore)); $result = mysql_query($query); //rest of code... As you can see above, at the very top there is $allstore = $_POST['store']; Which collects values based from previous form POST method that has checkbox with the name=store[] . Now According to the function shown, if I create my own keys and values like this $allstore = ['s_M9' =>0 , 's_M10' =>1]; the output shows exactly what i'm looking for. But the problem goes on how to let $allstore implode those stores s_M9, s_M10 based on what the user has selected on the previous page ( checkbox )? I mean, the user can select either one of the stores or Both stores . How can I implode the checked results between those brackets without inserting them manually? Thank You Edit : <?php echo "<form action='somewhere.php' method='POST'>"; $query = "SELECT * from stores_list ORDER BY short Asc"; $result = mysql_query($query); if(mysql_num_rows($result)>0){ $num = mysql_num_rows($result); for($i=0;$i<$num;$i++){ $row = mysql_fetch_assoc($result); echo "<input type=checkbox name=store[] value={$row['short']} style='width:20px; height:20px;'>{$row['short']}"; } } else{ //No Stores Available echo "No Stores Found !"; } echo "</td><input type='submit' value='Search'/></form>";
$allstore = []; if (!empty($_POST['store'])) { foreach ($_POST['store'] as $value) { $allstore[$value] = 1; // or 0, it doesn't matter because your function adds all the keys } } $query = (createSelect($allstore)); $result = mysql_query($query); And of course you have to take care of your createSelect function to avoid SQL Injections, please read here
Getting table doesnt exist with php and mysql
This code down here should search database. but I am getting error that my table doesnt exists. And also I want to ask why if I push second time submit button it just jumps to else so it echo choose at least.... and also all data from database. Thanks! Here is php if (isset($_POST['submit'])) { $query = 'SELECT * FROM station_tab'; if (!empty($_POST['station_name']) && !empty($_POST['city']) && !empty($_POST['zone'])) { $query .= 'WHERE station_name' .mysql_real_escape_string($_POST['station_name']) . 'AND city' . mysql_real_escape_string($_POST['city']) . 'AND zone' . mysql_real_escape_string($_POST['zone']); } elseif (!empty($_POST['station_name'])) { $query .= 'WHERE station_name' . mysql_real_escape_string($_POST['station_name']); } elseif (!empty($_POST['city'])) { $query .= 'WHERE city' . mysql_real_escape_string($_POST['city']); } elseif (!empty($_POST['zone'])) { $query .= 'WHERE zone' . mysql_real_escape_string($_POST['zone']); } else { echo "Choose at least one option for search"; } $result = mysql_query($query, $db) or die(mysql_error($db)); if (mysql_num_rows($result) > 0) { while ($row = mysql_fetch_array($result)){ echo '<br/><em>' .$row['station_name'] . '</em>'; echo '<br/>city: '. $row['city']; echo '<br/> zone: ' .$row['zone']; echo '<br/> Long: ' .$row['lon']; echo '<br/> Lat: ' . $row['lat']; } } } here is error message when I add name of the city to city. Table 'stanice_tab.station_tabwhere' doesn't exist
Here is your corrected code: $query = 'SELECT * FROM station_tab '; // note the space at the end if (!empty($_POST['station_name']) && !empty($_POST['city']) && !empty($_POST['zone'])) { $query .= ' WHERE station_name = "' .mysql_real_escape_string($_POST['station_name']) . '" AND city = "' . mysql_real_escape_string($_POST['city']) . '" AND zone = "' . mysql_real_escape_string($_POST['zone']).'"'; // note the = signs and the space before each AND } elseif (!empty($_POST['station_name'])) { $query .= ' WHERE station_name = "' . mysql_real_escape_string($_POST['station_name']).'"'; // note the = sign and the space at the beginning } elseif (!empty($_POST['city'])) { $query .= ' WHERE city = "' . mysql_real_escape_string($_POST['city']).'"'; // note the = sign and the space at the beginning } elseif (!empty($_POST['zone'])) { $query .= ' WHERE zone = "' . mysql_real_escape_string($_POST['zone']).'"'; // note the = sign and the space at the beginning } else { echo "Choose at least one option for search"; } Take the habit of echoing your $query variable so concatenation does not add any typo mistakes.
in phpmyadmin select the database and then select your table and in menu above there is a sql menu. you can use this functionality to construct sql queries or debug when there are errors like this
Display message if odbc_num_rows == empty
I have an advanced search query which queries a database. The search works fine and prints the desired results when a user searches something that is IN the database. I've set up a condition when if a user searches something and that something couldn't be found in the database, it displays a message that the record could not be found. But it's not displaying the message I need it to. Instead, if it can't find the record, it prints an empty table with headings. This table is only supposed to be printed if something is found. No if I swop the condition from >= -1 to just == -1 it displays the message I need it to when something couldn't be found even if that something is in the database. I hope this makes sense. Please see my code below. <table class="table table-bordered table-striped" style="width: 100%;"> <?php $dbName = "F:/Domains/autodeal/autodeal.co.za/wwwroot/newsite/db/savvyautoweb.mdb"; // Throws an error if the database cannot be found if (!file_exists($dbName)) { die("Could not find database file."); } // Connects to the database // Assumes there is no username or password $conn = odbc_connect("Driver={Microsoft Access Driver (*.mdb)};Dbq=$dbName", '', ''); $searchMake = addslashes($_POST['makeSelection']); $searchModel = addslashes($_POST['modelSelection']); $searchBranch = addslashes($_POST['branchSelection']); $searchYear = addslashes($_POST['yearSelection']); $minPrice = addslashes($_POST['minPriceSelection']); $maxPrice = addslashes($_POST['maxPriceSelection']); $sql = "SELECT Id, Make, Model, Year, Price, SpecialPrice, Branch, StockNO FROM Vehicle "; if ($searchMake || $searchModel || $searchBranch || $searchYear || $minPrice || $maxPrice) { $sql .= "WHERE "; } $combine = ''; if ($minPrice) { $sql .="{$combine}Price BETWEEN $minPrice "; $combine = 'BETWEEN '; } if ($maxPrice) { $sql .="AND $maxPrice "; $combine = 'AND '; } if ($searchMake) { $sql .="{$combine}Make LIKE '%$searchMake%' "; $combine = 'AND '; } if ($searchModel) { $sql .="{$combine}Model LIKE '%$searchModel%' "; $combine = 'AND '; } if ($searchBranch) { $sql .="{$combine}Branch LIKE '%$searchBranch%' "; $combine = 'AND '; } if ($searchYear) { $sql .="{$combine}Year LIKE '%$searchYear%' "; $combine = 'AND '; } $rs = odbc_exec($conn, $sql); if (odbc_num_rows($rs) >= -1) { echo "\t" . "<tr>\n"; echo "\t" . "<th>Make</th><th>Model</th><th>Year</th><th>Price</th><th>Special Price</th><th>Location</th><th>Stock Number</th>" . "\n"; while (odbc_fetch_row($rs)) { $id = odbc_result($rs, Id); $make = odbc_result($rs, Make); $model = odbc_result($rs, Model); $year = odbc_result($rs, Year); $price = odbc_result($rs, Price); $specialPrice = odbc_result($rs, SpecialPrice); $branch = odbc_result($rs, Branch); $stockNo = odbc_result($rs, StockNO); echo "\t" . "<tr>\n"; echo "\t\t" . "<td><a href=/newsite/selected-vehicles?Id=$id>" . $make . "</td><td><a href=/newsite/selected-vehicles?Id=$id>" . $model . "</a></td><td>" . $year . "</td><td>" . $price . "</td><td>" . $specialPrice . "</td><td>" . $branch . "</td><td>" . $stockNo . "</td>\n"; echo "\t" . "</tr>\n"; } } else { echo "We don’t have the vehicle you are looking for right now, but send us your vehicle requirements and we will be sure to find you one!"; } odbc_free_result($rs); odbc_close($conn); // This message is displayed if the query has an error in it if (!$rs) { exit("There is an error in the SQL!"); } ?> </table>
As a general rule, odbc_num_rows() is not a reliable way to determine the number of rows returned by a SELECT query. As mentioned in the "Notes" section of the PHP documentation: Note: Using odbc_num_rows() to determine the number of rows available after a SELECT will return -1 with many drivers. That is indeed the case with the Access ODBC driver. Instead of using odbc_num_rows() you could check the result of the first odbc_fetch_row() to see if it is TRUE and, if so, proceed with dumping the data to the HTML table. If the first call to odbc_fetch_row() returns FALSE then no rows were retrieved and you can display your message.
making a better search query in php and mysql
I'm trying to create a search query: I'm giving 6 options to search. Bedrooms Type Postcode Location Min price Max price I have these fields in a form. I searched a lot but couldn't find the answer I was searching. I tried queries using LIKE and % too. But that didn't worked out too. If a user selects only 'Type' then all of the data with that type should be displayed. And the same goes to other fields. And again, if a user selects 2 or 3 options and searches then the results which match the options selected should be displayed. How can I create a search like this? Should I do?: if(){ }else if(){ }
You can build your sql query on the fly. If search value is not empty (or something else that does not count as a search value) then do not add search. Do not forget to add mysql_real_escape_string to a params or bad people will exploit your software. exampe in php: <?php $params = array('type' => 'aaa', 'max_price'=>100); // parameters that a user gave. Example from $_POST or $_GET $querySearch = array(); if(isset($params['type'])) { $querySearch[] = "type LIKE '%".mysql_real_escape_string($params['type'])."%'"; } if(isset($params['max_price'])) { $querySearch[] = "price <= ".mysql_real_escape_string($params['max_price']); } if(isset($params['min_price'])) { $querySearch[] = "price >= ".mysql_real_escape_string($params['min_price']); } // and etc. $q = 'select * FROM hotel WHERE ' . implode(' AND ' , $querySearch); echo $q; ?> then you can use query $q to do db select.
dynamically build the query $useAnd = false; $ query = " select * from table"; if (isset($bedrooms) == true or isset($type) == true or isset($postcode)==true or ...) { $query = $query. " where "; if (isset($bedroomsIsset) = true) { $query = $query . "bedrooms >=". $bedrooms; $useAnd=true; } if (isset($type) = true) { if ($useAnd=true) {$query = $query . " and " ;} $query = $query . "type =". $type; $useAnd=true; } if (isset($postcode)==true) { if (isset($poscode) = true) { if ($useAnd=true) {$query = $query . " and " ;} $query = $query . "postcode =". $postcode; $useAnd=true; } if (...) }
if(!empty($some_option)) $search_options["option_name"] = $some_option; $query = "some query"; $where = ""; if(!empty($search_options)){ $first_option = array_shift($search_types); $where = " " . key($first_option) . " = " . $first_option; foreach($search_options as $key => $option){ $where .= " AND $key = $option"; } } $query .= $where;