-1

Input of filter

Using Filter option to get products by their sizes.

This is the product database structure:

id | size
------------
 1 | S,M
 2 | S,M,L
 3 | S
 4 | M,L

This is the Shirtsize database structure:

id | size
------------
 1 | S
 2 | M
 3 | L

This is the code of input value get for filter

<div class="list-group">
  <h3>Size</h3>
    <?php
       $query = "SELECT DISTINCT(shirtsize) FROM shirtsize ORDER BY id DESC";
       $statement = $connect->prepare($query);
       $statement->execute();
       $result = $statement->fetchAll();
       foreach($result as $row)
       {
        ?>
       <div class="list-group-item checkbox">
        <label>
          <input type="checkbox" class="common_selector size" value="<?php echo $row['shirtsize']; ?>"> 
           <?php echo $row['shirtsize']; ?>
        </label>
       </div>
    <?php
      }
     ?>  
</div>

This code to get the values from database:

if(isset($_POST["size"]))
{
    $size_filter = implode("','", $_POST["size"]);

    if (is_array($size_filter))
    {
        foreach ($size_filter as $value)
        {
           $query .= "AND size like('%".$value."%')";
        }
    }
    else{
    $query .= "AND size like('%".$size_filter."%')";
    }
}

In here i have database like s,m,l like this and post data also look like this s,m i tried this way to get values but the result is null.. I am not good in english so if any inconvinient sorry for that guys.

Krish
  • 79
  • 6

3 Answers3

1

To handle your current data model directly from MySQL would probably require some SQL olympics. Instead, I will offer a better normalized data structure:

id | size
------------
 1 | S
 1 | M
 2 | S
 2 | M
 2 | L
 3 | S
 4 | M
 4 | L

Now if you want to get the distinct sizes, you only need:

SELECT DISTINCT(size) FROM shirtsize;

If you want to get a count of sizes per id, just use:

SELECT id, COUNT(*) AS cnt FROM shirtsize GROUP BY id;

In general, never store CSV data in a SQL table.

Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
1

First of all, I double @Tim Biegeleisen to recommend you to normilize your data.
However, you can achieve the result by using FIND_IN_SET() function instead of LIKE.

SELECT * 
FROM `shirtsize` 
WHERE FIND_IN_SET('S', `size`)

The function returns 1-based position of the string in the string list. Or NULL if string not found.

https://dev.mysql.com/doc/refman/8.0/en/string-functions.html#function_find-in-set

artoodetoo
  • 918
  • 10
  • 55
0

Thanks guys i got an answer

SELECT * FROM products WHERE status = '1' AND size like('%L%') OR size like('%M%')

or

SELECT size from `products` WHERE size rlike "L|M"
Krish
  • 79
  • 6
  • What if you have size equal to 'L,XXL' and looking for 'XL'. I guess it would false positive result with LIKE operation. Use FIND_IN_SET() instead, it's safe. – artoodetoo Mar 11 '20 at 13:48