skip to Main Content

I want to filter by query sql.
Which color of blue, type of boy and size :35,36,39 to choose and display.

For Example: SQL Table (PHPMYADMIN)

--------------------------
|id| size | type | color |
--------------------------
|1 | 35   | boy  | blue  |
|2 | 36   | girl | red   |
|3 | 35   | boy  | blue  |
|4 | 37   | girl | red   |
|5 | 38   | boy  | red   |
|6 | 39   | boy  | red   |
--------------------------

Here’s my code: (PHP):

$db = mysqli_connect('localhost','root','root','datab');
$qu="SELECT * FROM table 
    WHERE color='blue' 
    AND size='35' 
    OR size='36' 
    OR size='39' 
    AND type='boy' 
    ORDER BY id ASC 
    LIMIT 10";
$res = mysqli_query($db, $qu); 
while($ro = mysqli_fetch_array($res)) {
    echo $ro["id"].',';
}

Out (HTML):

1,2,3,6,

I need to out(html) the above records to get “1,3,” .

2

Answers


  1. () Around OR conditions

    $db = mysqli_connect('localhost','root','root','datab');
    $qu="SELECT * FROM table 
        WHERE color='blue' 
        AND (size='35' OR size='36' OR size='39' ) 
        AND type='boy' 
        ORDER BY id ASC 
        LIMIT 10";
    $res = mysqli_query($db, $qu); 
    while($ro = mysqli_fetch_array($res)) {
        echo $ro["id"].',';
    }
    
    Login or Signup to reply.
  2. You are filtering the same column for three values, so it makes better sense to use IN(); then you don’t need to worry with parenthetical grouping of conditions.

    $qu="SELECT * FROM table 
        WHERE color='blue' 
        AND size IN ('35','36','39')
        AND type='boy' 
        ORDER BY id ASC 
        LIMIT 10";
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search