1

I have multiple checkboxes with category names and their values. After every form submission an array is generated.

Here is the example:

Array
(
    [user_type] => Array
        (
            [0] => Freelancer
            [1] => Company
        )

    [category] => 19
    [sub_category] => Array
        (
            [0] => Website UI Designing  
            [1] => Website Development 
        )

)

now I want from above array build a mysql query like---

select * from table_name 
    where user_type in ('Freelancer','Comapny') 
    and category in (19) 
    and sub_category in ('Website UI Designing','Website Development')

any help will be appreciated. thanks

2
  • Does category always give one value, and that too integer? Commented Apr 28, 2016 at 20:02
  • Are you using prepared statements? Commented Apr 28, 2016 at 20:26

2 Answers 2

1
$sql = "SELECT * FROM table_name WHERE user_type IN (" .rtrim(str_repeat("?,", count($array["user_type"]), ",")) .") AND category IN (" .rtrim(str_repeat("?,", count($array["category"]), ",")) .") AND sub_category IN (" .rtrim(str_repeat("?,", count($array["sub_category"]), ",")) .")";

$parameters = array_merge($array["user_type"], $array["category"], $array["sub_category"]);

You'd need to prepare the $sql and then execute with the $parameters argument.

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

Comments

0
array_walk_recursive ($array, function (&$i) { 
      if ( ! is_numeric($i)) $i = '"' . $i . '"'; });

$ws = array();

foreach($array as $k=>$v) {
   if (is_array($v)) $v = implode(',', $v);
   $ws[] = $k . ' in (' . $v . ')';
}

echo $where = 'where '. implode(' and ', $ws);
//  where user_type in ("Freelancer","Company") and category in (19) and sub_category in ("Website UI Designing","Website Development")

1 Comment

Glad to help. Good luck!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.