I have a lot of queries with a bit different from each other for example the first query is same to second query except I add a single line of where statement to it.
Since the query is same, is there a possibility to put it on a function and when I call it I will add the where statement as a parameter?
For example. I put the query to function.
then if the user is not admin I will add this line of code
This is the code what I've done so far.
The else code doesn't work. What is my mistake? By the way I am using Yii framework. please help! THanks in advance
Code:
if($ut=='Admin'){ // if the user is Admin the query should not have a filter
$queryCustomer = Yii::app()->db->createCommand()
->select('cust.mobile_number as customer,sum(trans.price) as sales,trans.datetime')
->from('customers cust')
->join('transactions trans', 'cust.id=trans.customer_id')
->where('transaction_type_id=:id', array(':id'=>1))
->group('customer_id')
->order('trans.datetime DESC')
->queryAll();
$per_customer=$this->renderTableCustomer($queryCustomer);
} else { // if the user is not Admin the query should have a filter
$queryCustomer = Yii::app()->db->createCommand()
->select('cust.mobile_number as customer,sum(trans.price) as sales,trans.datetime')
->from('customers cust')
->join('transactions trans', 'cust.id=trans.customer_id')
->where('transaction_type_id=:id', array(':id'=>1))
->andWhere('user_id=:userID',array(':userID'=>$filter))
->group('customer_id')
->order('trans.datetime DESC')
->queryAll();
$per_customer=$this->renderTableCustomer($queryCustomer);
}
For example. I put the query to function.
Code:
public function actionSample($queryCustomer){
$queryCustomer = Yii::app()->db->createCommand()
->select('cust.mobile_number as customer,sum(trans.price) as sales,trans.datetime')
->from('customers cust')
->join('transactions trans', 'cust.id=trans.customer_id')
->where('transaction_type_id=:id', array(':id'=>1))
->group('customer_id')
->order('trans.datetime DESC')
->queryAll();
return $queryCustomer;
}
Code:
->andWhere('user_id=:userID',array(':userID'=>$filter))
Code:
if($ut=='Admin'){ // if the user is Admin the query should not have a filter
$results=$this->actionSample($queryCustomer);
$per_day="$this->renderTable($results);
else{
$addWhere="->andWhere('user_id=:userID',array(':userID'=>$filter))";
$results=$this->actionSample($queryCustomer,$addWhere);
$per_day="$this->renderTable($results);
}