0

I have a 2-fields form to select both category and supplier of some products:

<input type="checkbox" name="category[]" value="<?php echo $categories_id?>"/>
<input type="checkbox" name="supplier[]" value="<?php echo $produttori_id?>"/>

Many categories and suppliers are available in a WHILE loop.

In the submitted page, I've created those two loops to get all the selected category and supplier:

if(!empty($_POST['category'])) {
foreach($_POST['category'] as $check) {
        echo $check; 
        echo "<br>";
}
}

and:

if(!empty($_POST['supplier'])) {
foreach($_POST['supplier'] as $check) {
        echo $check; 
        echo "<br>";
}
}

Now I have to do a query to selects only records that are included in both arrays:

SELECT * FROM PRODUCTS WHERE supplier [is in the supplier array] AND category [is in the category array]

How can I achieve this?

Carmine
  • 25
  • 5
  • Why don't you do it prior to the query. If (in array supplier) AND (in array catagory) then do this selecting using supplier = and category =, PHP function in_array(item,array) – clearshot66 Apr 19 '17 at 14:05

4 Answers4

2

You can do this by using SQL operator IN and PHP functions implode, array_map and intval. The intval is for prevention of sql injection attacks.

if(!empty($_POST['category']) && !empty($_POST['supplier'])) {
    $categories = implode(",", array_map('intval', $_POST['category']));
    $suppliers = implode(",", array_map('intval', $_POST['supplier']));
    $sql = "SELECT * FROM PRODUCTS WHERE supplier IN (" + $suppliers + ") AND category IN (" + $categories + ")";
    //use the sql
    //show results
}
Adder
  • 5,708
  • 1
  • 28
  • 56
2

You can use php function implode

'SELECT * FROM PRODUCTS WHERE supplier in ('.implode(',', $_POST["supplier"]).' ) AND category in ('.implode(',', $_POST["category"]).')

But first validate the input to prevent sql injection

Nerea
  • 2,107
  • 2
  • 15
  • 14
  • 1
    Don't do this, it's prone to injection even if you validate it, you should be using prepared statements with bound parameters then only using the bound parameters for the query. Never directly insert like that. – clearshot66 Apr 19 '17 at 14:14
1

You can achive this with native mysql function IN(). With that You can query things like

WHERE supplier IN('supplier1','supplier2','supplier3')

So, in your example it can look like this:

'SELECT * FROM PRODUCTS WHERE supplier IN('.implode(',', $_POST['supplier']).')'
jiGL
  • 175
  • 8
1

Please take a look at this post. I guess you are trying to find out something like this one Mysql where id is in array

Community
  • 1
  • 1