Jump to content

Recommended Posts

i am making two mySQL query's pulling information from two different tables:

$q = "SELECT zip FROM allowed_zip WHERE user_id='$id'";

and

$z = "SELECT zip_code FROM companies WHERE ". $search;

$search is just a selection sting i build before hand ignore that part.

 

What i need to do is to have an if statement is to check if the values pulled in to $z exist in $q. They are both lists of zip codes, the first one is a list of zip code the user has access too and the second one is what the user is searching for. This is meant to deny them access to select records.

Is "zip" in "allowed_zip" contain 1 zip code per row, or does each row contain more than 1 zip code?

 

ex:

user_id | zip

1 | 28542

1 | 28555

 

or,

 

1 | 23542, 28555

 

Hope that makes sense.

 

If it is the first, you could (UN-TESTED)

$sql = "SELECT `companies`.`zip_code` FROM `companies`,`allowed_zip` WHERE (`companies`.`zip_code` = `allowed_zip`.`zip` AND `allowed_zip`.`user_id` = '$id') AND $search";

 

If it is the second, (UN-TESTED)

$sql = "SELECT `companies`.`zip_code` FROM `companies`,`allowed_zip` WHERE (`companies`.`zip_code` IN(`allowed_zip`.`zip`) AND `allowed_zip`.`user_id` = '$id') AND $search";

How about letting the DB do the work by using a sub-select:

 

$q = "SELECT zip_code FROM companies WHERE ". $search." AND zip_code IN (SELECT zip FROM allowed_zip WHERE user_id='$id')";

 

Alternatively, you can rewrite the above query as an INNER JOIN or INTERSECT.

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.