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?

Mihai Iorga
  • 39,330
  • 16
  • 106
  • 107
Go3Team
  • 145
  • 1
  • 3
  • 11

3 Answers3

1

You could also use IN:

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

$q1 = "SELECT company FROM company WHERE id IN(". implode(',', $x) .") ORDER BY company";
Arion
  • 31,011
  • 10
  • 70
  • 88
Mihai Stancu
  • 15,848
  • 2
  • 33
  • 51
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

Community
  • 1
  • 1
Nishant Jani
  • 1,965
  • 8
  • 30
  • 41
  • 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 '12 at 08:48
0

use OR

$q1 = "SELECT company FROM company WHERE (id = '16' OR id = '7') ORDER BY company";
Mihai Iorga
  • 39,330
  • 16
  • 106
  • 107