Monday, 18 July 2016

Yii params condition ( PHP Framework )



I am a complete newbie in the world of yii and doing my best to learn the framework as best as I can, while reading the book on Yii - 'Web Application Development Using Yii and PHP' by Jeffrey Winesett,



I came across :



'params'=>array(':projectId'=>$this->_project->id)


If anyone has read the book, can someone explain why do we use :projectId why not directly projectId? What does the ':' stand for? Is it the specific syntax or is it something php specific.




This was the exact code :



public function actionIndex()
{

$dataProvider=new CActiveDataProvider('Issue', array(
'criteria'=>array(
'condition'=>'project_id=:projectId',
'params'=>array(':projectId'=>$this->_project->id),

),
));
$this->render('index',array(
'dataProvider'=>$dataProvider,
));
}


Any answer would be highly appreciated.
Regards.



Answer



The ":" id there to identify param within the condition string. It's a way to safely bind params to an sql statement.



In your case, when you specify this condition



project_id=:projectId


In your db schema, Yii know that project_id is an integer, then when you bind the param with :




'params'=>array(':projectId'=>$this->_project->id),


Yii will make sure you bind an integer and write the SQL statement for it and generate SQL statement like this : project_id=26



This is the same thing for string ex.:



        'criteria'=>array(
'condition'=>'name=:myname',
'params'=>array(':myname' => 'Ronald McDonald'),

),


then your sql statement for this condition will be name='Ronald McDonald'


No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...