user1955915
user1955915

Reputation: 39

How to add values from checkboxes to 'select' query?

I have some checkbox like this

<form action="tt.php" method="post">
<input type="checkbox" name="lvl[]" value="0">0&nbsp
<input type="checkbox" name="lvl[]" value="1">1&nbsp
<input type="checkbox" name="lvl[]" value="2">2&nbsp
<input type="checkbox" name="lvl[]" value="3">3&nbsp
<input type="checkbox" name="lvl[]" value="4">4&nbsp
<input type="submit" value="Ok">

How to add values from checked ones to SQL query like this?:

If checked 2 and 4 then
select name,lvl,team from $table where lvl=2 or lvl=4
If checked 2 and 4 AND 0 then
select name,lvl,team from $table where lvl=2 or lvl=4 or team='abc' (if 0 checked then 'select' must contains strings where team='abc', if not - don't)
If none is selected then
select name,lvl,team from $table

Upvotes: 1

Views: 833

Answers (1)

hohner
hohner

Reputation: 11588

$where = '';

if (isset($_POST['lvl']) && $vals = $_POST['lvl']) {

   // Begin WHERE string
   $where = 'WHERE '; 

   // Remove '0' from array
   if ($key = array_search('0', $vals)) {
      $where .= 'team = "abc" ';
      unset($vals[$key]);
   } 

   // Append `WHERE lvl IN (2,4)`
   $where .= 'AND lvl IN (' . implode(',', $vals) . ')';

   // Final statement

}

$sql = "select name,lvl,team from $table $where";

Edit

What happens if you replace this:

if ($key = array_search('0', $vals)) {
   $where .= 'team = "abc" ';
   unset($vals[$key]);
} 

With:

if ($vals[0] === '0') {
   $where .= 'team = "abc" ';
   unset($vals[0]);
} 

Change your code to this:

$first = false;
if ($vals[0] === '0') {
    $where .= 'team = "neutral"';
    unset($vals[0]);
    $first = true;
}
if (count($vals)) {
    if ($first) $where .= ' OR ';
    $where .= 'lvl IN (' . implode(',', $vals) . ')';
}

Upvotes: 2

Related Questions