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?

1
  • 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) Commented Apr 19, 2017 at 14:05

4 Answers 4

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

Sign up to request clarification or add additional context in comments.

1 Comment

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.
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
}

Comments

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

1 Comment

could be a comment
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']).')'

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.