user1286499
user1286499

Reputation: 227

How do I combine two statement will be one query?

Here an example queries to get two type of icons..

$fetchIcon = array();
$queryIcon = $db->query("SELECT * FROM icon_code WHERE icon_type = 'icon'");
while ($fIcon = $db->fetch_assoc($queryIcon)) {
    $fetchIcon[] = $fIcon;
}

$fetchOther = array();
$queryOther = $db->query("SELECT * FROM icon_code WHERE icon_type = 'other'");
while ($fOther = $db->fetch_assoc($queryOther)) {
    $fetchOther[] = $fOther;
}

Then I use foreach to show an ouput on the same page.

foreach ($fetchIcon as $Icon) {
  echo $Icon['IconName']; // select option for Icon
}

foreach ($fetchOther as $Other) {
  echo $Other['IconName']; // select option for other icon
}

Question : How do I combine the two statement will be one query?

Upvotes: 0

Views: 50

Answers (3)

juergen d
juergen d

Reputation: 204746

SELECT * FROM icon_code 
WHERE icon_type = 'icon' 
or icon_type = 'other' 
ORDER BY icon_type

or

SELECT * FROM icon_code 
WHERE icon_type in ('icon', 'other')
ORDER BY icon_type

The order byis optional to get the order by type.

Upvotes: 5

Marc B
Marc B

Reputation: 360592

SELECT *
FROM icon_code
WHERE icon_type IN ('icon', 'other')

and then

$fetchIcon = array();
$fetchOther = array();

while($row = mysql_fetch_assoc($result)) {
    switch($row['icon_type']) {
       case 'icon':
           $fetchIcon[] = $row;
           break;
       case 'other':
       default:
           $fetchOther[] = $row;
    }
}

Upvotes: 3

Mike Purcell
Mike Purcell

Reputation: 19979

I would suggest using the IN function:

$queryOther = $db->query("SELECT * FROM icon_code WHERE icon_type IN ('other', 'icon'");

Upvotes: 2

Related Questions