Insert different strings before and after variable in PHP

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.

Upvotes: 1

Views: 186

Answers (3)

newfurniturey
newfurniturey

Reputation: 38436

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.

Upvotes: 1

Sergey Eremin
Sergey Eremin

Reputation: 11080

$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;

Upvotes: 2

nickb
nickb

Reputation: 59699

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 )";
}
...

Upvotes: 2

Related Questions