1

I have 4 PHP variables, each variable consists of dynamic checkboxes, sometimes it can be one variable sometimes more but not more than 4:

$type = 'type_id = 2';
$color = 'color_id = 3';
$man = 'man_id = 5';
$size = 'size_id = 4 or size_id = 5';

I need to form of these variables Mysql query, the problem is how to add WHERE and AND strings before each variable. In front of first variable I need to add WHERE (it can be $type or $color or other). If first variable is active and other is checked I need to add AND to form proper query. e.g

if checked only "type" checkboxes:

WHERE $type

if checked "size" and "type" checkboxes:

WHERE $size AND $type

and so on... Hope you understand my problem, sorry for bad english.

3 Answers 3

2
$parts = array();
if (!empty($type)) {
    $parts[] = '(' . $type . ')';
}
if (!empty($color)) {
    $parts[] = '(' . $color . ')';
}
if (!empty($man)) {
    $parts[] = '(' . $man . ')';
}
if (!empty($size)) {
    $parts[] = '(' . $size. ')';
}
$where = '';
if (!empty($parts)) {
    $where = 'WHERE ' . implode(' AND ', $parts);
}
$select .= $where;
Sign up to request clarification or add additional context in comments.

Comments

2

Put them in an array and join them with implode() like this:

$temp = array( $type, $color, $man, $size);
$string = 'WHERE ' . implode( ' AND ', $temp);

If any of those variables aren't set (i.e. there not submitted from the checkboxes), don't add it to the array:

$temp = array();
if( isset( $_POST['somecheckbox'])) {
    $temp[] = "( something = value )";
}
if( isset( $_POST['someothercheckbox'])) {
    $temp[] = "( somethingelse = value )";
}
...

Comments

1

Assuming your checkboxes are in submitted via POST, you could have an association-array in PHP that is iterated-through and checks-for a corresponding checkbox selection; if selected, it adds it to the string.

A rough sketch could be:

$fields = array(
    'type' => 'type_id = 2',
    'color' => 'color_id = 3',
    'man' => 'man_id = 5',
    'size' => 'size_id = 4 or size_id = 5'
);
$whereClause = '';
foreach ($fields as $field => $value) {
    if (isset($_POST[$field]) && ($_POST['field'] == 1)) {
            // this field is "active"
        if ($whereClause != '') $whereClause .= ' AND ';
        $whereClause .= '(' . $value . ')';
    }
}
if ($whereClause != '') $whereClause = ' WHERE ' . $whereClause;

Note, I have the $value of each field wrapped in parentheses so that and and won't interfere with the or that's in your size variable.

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.