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"
    – Nanne
    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

1
  • 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.
    – Go3Team
    Aug 23, 2012 at 8:48
1

You could also use IN:

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

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

use OR

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

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.