php - Yii createCommand not not returning correct results -
i trying random id table specific visiblity=2
clause having issues getting return id, says undefined index: id
.
$space = yii::app()->db->createcommand() ->select('id') ->from('space') ->where('id=rand() , visibility=2') ->limit(1) ->queryall(); //->queryrow(); echo $space['id'];
is not correct way?
i figured out solution using loaded info original version without guest check.
$max = space::model()->count(); $randid = rand(0,$max); $space = space::model()->find(array('offset'=>$randid)); if ($space->attributes['visibility'] == 2) {
you can use order rand()
instead of id = rand()
. can use ->queryscalar()
id directly.
$space = yii::app()->db->createcommand() ->select('id') ->from('space') ->where('visibility = 2') ->order('rand()') ->limit(1) ->queryscalar(); echo $space;
keep in mind rand()
slow solution. check alternatives.
also, if no entries database, have check case:
if (!empty($space)) { // id never 0 // $space } else { throw new chttpexception(404, 'no data found'); }
Comments
Post a Comment