I am trying to get a random ID from a table with a specific visiblity=2
clause but I am having issues getting it to return the ID, it says Undefined index: id
.
$space = Yii::app()->db->createCommand()
->select('id')
->from('space')
->where('id=rand() AND visibility=2')
->limit(1)
->queryAll();
//->queryRow();
echo $space['id'];
Is his not the correct way?
I figured out another solution using the already loaded info from my 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 are using the random id in where clause, therefore $space
maybe an empty array based on condition. For example if you don't have a record with id == 3
and random generated id is 3, then $space
is an empty value. So $space['id']
cause Undefined index
error. You need to make sure the array is not empty and then echo id of array:
if($space != null)
echo $space['id'];
queryAll method gives you an array with database objects. For your purpose you can use simpler and more understandable code:
$spaceId = Yii::app()->db->createCommand()
->select('id')
->from('space')
->where('visibility=2')
->orderBy(RAND())
->limit(1)
->queryScalar();
echo $spaceId;
You can use ORDER BY RAND()
instead of id = rand()
. Also you can use ->queryScalar()
to get only ID directly.
$space = Yii::app()->db->createCommand()
->select('id')
->from('space')
->where('visibility = 2')
->order('RAND()')
->limit(1)
->queryScalar();
echo $space;
Keep in mind that RAND()
is slow solution. Check alternatives .
Also, if you get no entries from database, you have to check that case:
if (!empty($space)) { // id will never be 0
// Do something with $space
} else {
throw new CHttpException(404, 'No data found');
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.