1

Trying to get the results of one query into the WHERE statement of another:

$query1 = "SELECT DISTINCT company_id FROM location WHERE state = 'XX'";
$result1 = mysql_query($query1) or die(mysql_error());
while($row1 = mysql_fetch_array($result1)) {
    //Collect WHERE STATEMENT HERE
}

I've tried the following:

$q1 = "SELECT company FROM company WHERE id = '16', id = '7' ORDER BY company";
$q1 = "SELECT company FROM company WHERE id = '16' AND id = '7' ORDER BY company";
$q1 = "SELECT company FROM company WHERE id = '16' && id = '7' ORDER BY company";

Along with other variations

Googling has only provided multiple WHERE AND if using different table names, but not the same. Anyone have any pointers?

1
  • the field 'id' cannot be 16 AND 7 at the same time. Use "or" Commented Aug 23, 2012 at 8:00

3 Answers 3

1

for a generalized code :

$ids = array (
[0] => 2
[1] => 4
[2] => 19
[3] => 16
);  

$ids = join(',',$ids);  
$sql = "SELECT * FROM company WHERE id IN ($ids)";

reffer : same example

Sign up to request clarification or add additional context in comments.

1 Comment

I've had the best luck with this one, but for whatever reason, I am only getting 1 result ($query = "SELECT DISTINCT company_id FROM location WHERE state = 'XX'";) in the array when numrows tells me there should be 23. Doing print_r (mysql_fetch_array($result)); Only shows 1 result as well.
1

You could also use IN:

$x = array('16', '7');

$q1 = "SELECT company FROM company WHERE id IN(". implode(',', $x) .") ORDER BY company";

Comments

0

use OR

$q1 = "SELECT company FROM company WHERE (id = '16' OR id = '7') ORDER BY company";

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.