我有一个控制器,它具有来自数据库的显示数据,具体取决于?id=
,它可以正常工作。但是,如果你没有给任何值id获取错误
error 400
Your request is invalid.
我的代码:
public function actionIndex($id)
{
// renders the view file 'protected/views/site/index.php'
// using the default layout 'protected/views/layouts/main.php'
$this->pageTitle = 'Page';
$criteria = new CDbCriteria(
array(
'condition' => 'name = :Name',
'params' => array(':Name' => $id),
//if $id is not defined then error
)
);
}
$ModelPages = Pages::model()->findAll($criteria);
$this->render('index',
array(
'Model' => $ModelPages,
)
);
}
我以这种方式试了这个,但没有用。
public function actionIndex($id)
{
// renders the view file 'protected/views/site/index.php'
// using the default layout 'protected/views/layouts/main.php'
$this->pageTitle = 'Page';
if(empty($id)){
$criteria = new CDbCriteria(
array(
'condition' => 'name = :Name',
'params' => array(':Name' => 'index'),
)
);
}
else {
$criteria = new CDbCriteria(
array(
'condition' => 'name = :Name',
'params' => array(':Name' => $id),
)
);
}
$ModelPages = Pages::model()->findAll($criteria);
$this->render('index',
array(
'Model' => $ModelPages,
)
);
}
在根据网站显示内容时,我的解决方案是否正确(安全)?
答案 0 :(得分:0)
您的解决方案是正确的,但更好地使用getQuery()方法获取GET参数并在没有找到页面时处理错误:
public function actionIndex($id='index') //Notice the default parameter value
{
$id = Yii::app()->request->getQuery('id', 'index') //if id GET parameter does not exist $id will be 'index'
$criteria = new CDbCriteria(
array(
'condition' => 'name = :Name',
'params' => array(':Name' => $id),
)
);
$ModelPages = Pages::model()->findAll($criteria);
if (empty($ModelPages)) {
throw new CHttpExeption(404,'page not found');
}
$this->render('index',
array(
'Model' => $ModelPages,
)
);
}
此外,如果您的操作无法接收id
参数,则应为其设置默认值(actionIndex($id='index')
)
答案 1 :(得分:0)
以这种方式尝试
public function actionIndex($id)
{
if(isset($id) && $id>0)
{
$this->pageTitle = 'Page';
$criteria = new CDbCriteria(
array(
'condition' => 'name = :Name',
'params' => array(':Name' => $id),
)
);
$ModelPages = Pages::model()->findAll($criteria);
$this->render('index',
array(
'Model' => $ModelPages,
)
);
}else
throw new CHttpException(404,'invalid request');
}