php function get two optional argument and write where class
i have one function which calculate total number of records in table and get two arguments and both are optional.
function getTotal($id=0,$id1=0)
{
($id==0?$addQuery="":$addQuery=" where art_id=".$id);
if($id1<>0 && $id==0)
{
$addQuery=" where up_type=".$id1
}
if($id1<>0 && $id<>0)
{
$addQuery=" and up_type=".$id1
}
mysql_set_charset('utf8');
$query="SELECT COUNT(id) FROM tbl_up ".$addQuery;
$result=$this->query($query,1);
return $result;
}
if you see i write if id is passed then i put the where class in one line
but if 2nd argument id1 is passed or not i need to add text to where class, but here is if id is passed then it should start from and and if id i开发者_高级运维s not passed it should start with where
i try to write if but these lines are too much, i need some thing like first line
($id==0?$addQuery="":$addQuery=" where art_id=".$id);
for 2nd agrument.
Thanks
function getTotal($id=0,$id1=0)
{
$where = array();
if ($id) $where[]='`art_id`="'.$id.'"';
if ($id1) $where[] = '`up_type`="'.$id1.'"';
$where = (!count($where) ? '' : 'WHERE '.implode(' AND ', $where));
$query="SELECT COUNT(id) FROM tbl_up ".$where;
mysql_set_charset('utf8');
$result=$this->query($query,1);
return $result;
}
try:
function getTotal($id = 0,$id1 = 0) {
// sorry, I rewrite the first expression to this, easier to read IMHO
$addQuery = $id == 0 ? "" : " where art_id='".mysql_real_escape_string($id)."'";
if ($id1 <> 0)
$addQuery .= ($id == 0 ? " where" : " and") . " up_type='".mysql_real_escape_string($id1)."'";
mysql_set_charset('utf8');
$query="SELECT COUNT(id) FROM tbl_up ".$addQuery;
$result=$this->query($query,1);
return $result;
}
function getTotal($id=0,$id1=0)
{
$addQuery="where 1=1"
if($id <>0) $addQuery.=" and art_id =".$id
if($id1<>0) $addQuery.=" and up_type=".$id1
mysql_set_charset('utf8');
$query="SELECT COUNT(id) FROM tbl_up ".$addQuery;
$result=$this->query($query,1);
return $result;
}
this is a generic way to have multiple cases tested
精彩评论