0

I have one table with offices that cover a range of postcodes with zipcode lowest and zipcode highest. Another table with zipcodes linked to a city name,

The user searches for a city, and the database returns a array with each postcode linked to that city. Then i want my code to use this array of postcodes to search in the offices table and see if any of the values fits between max and min value.

lets say we searched for a town that returned these zipcodes

 $search_string = 25002,25003,25004,25005,25006,25007,25008,25009,25013,25014,    25015,25018,25019,25022,25023,25024,25025,25053,25054,25100,25101,25106,25107,25108,25109,25110,25111,25112,25113,25114,25181,25183,25184

This was my attempt on a solution, thought it worked but apparently only workout for the first value.

$query = $this->db->prepare("SELECT contacts.id FROM contacts INNER JOIN contacts_postcodes_links ON contacts_postcodes_links.contact = contacts.id WHERE contacts.id != 0 ".$category1." ".$category2." AND :search_string BETWEEN contacts_postcodes_links.minValue AND contacts_postcodes_links.maxValue ORDER BY id DESC ".$limit."");

So the part that i need help with, is it possible to do something like this? If not, how would i solve this problem?

my_array BETWEEN contacts_postcodes_links.minValue AND contacts_postcodes_links.maxValue
2
  • what is type of postcode store in database ? if is int you can find min and max value in your search string and use BETWEEN Commented Oct 20, 2014 at 16:07
  • It is int, but with one value it is not a problem, now i need to check for between on serveral values, that is The problem Commented Oct 20, 2014 at 17:40

1 Answer 1

0

Solved it by doing everything in the same query,

Added inner join on postcodes to the min and max values, and then filtered the postcodes city for the user input city string.

Final result

 $query = $this->db->prepare("SELECT DISTINCT(contacts.id) FROM contacts
                            INNER JOIN contacts_postcodes_links ON contacts_postcodes_links.contact = contacts.id
                            INNER JOIN postcodes ON postcodes.postcode >= contacts_postcodes_links.minValue AND postcodes.postcode <= contacts_postcodes_links.maxValue
                            WHERE contacts.id != 0 AND contacts.category_1 = :category_1 AND contacts.category_2 = :category_2
                            AND postcodes.city LIKE :search_string
                            ORDER BY id DESC LIMIT ".$options['limit']." OFFSET ".$options['start']."");
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.