php - MYSQL: where colunm IN(Any_value) -
i trying make dynamic clause. getting array of check boxes in php
following code
$brand = array(); if(isset($_get['brand']) && !empty($_get['brand'])) $brand=$_get['brand']; $brand_str = implode("' , '",$brand); }
my sql query is
$sql="select distinct * products brand in('$brand_str')";
if brand not defined gives error or no row fetched simple problem can solved using following approach.
my approach:
i use variable 'flag_for_filter_brand' inside if statement if flag_for_filter_brand=1 query
$brand = array(); $flag_for_filter_brand=false; if(isset($_get['brand']) && !empty($_get['brand'])) $brand=$_get['brand']; $brand_str = implode("' , '",$brand); $flag_for_filter_brand=true; } if(flag_for_filter_brand); $sql="select distinct * products brand in('$brand_str')"; else $sql="select distinct * products;
problem: big problem because code become large because there 2 3 clauses below
$sql="select distinct * products brand in('$brand_str') , quantity in ($var2) , type in($var3)";
how solve in optimal way?
any suggestion or appreciated
put each of where
conditions in array. test whether array contains anything.
$wheres = array(); if(isset($_get['brand']) && !empty($_get['brand'])) $brand=$_get['brand']; $brand_str = implode("' , '",$brand); $wheres[] = "brand in ('$brand_str')"; } if(isset($_get['quantity']) && !empty($_get['quantity'])) $quant=$_get['quantity']; $quant_str = implode("' , '",$quant); $wheres[] = "quantity in ('$quant_str')"; } // repeat other conditions if (!empty($wheres)) { $where_str = "where " . implode(' , ', $wheres); } else { $where_str = ""; } $sql = "select distinct * products $where_str";
if have lots of conditions, can put names of fields in array, , make first part of answer loop:
$fields = array('brand', 'quantity', 'type', ...); foreach ($fields $field) { if (!empty($_get[$field])) { $field_str = implode("' , '", $_get[$field]); $wheres[] = "$field in ('$field_str')"; } }
Comments
Post a Comment