Search code examples
phprandom

how to use order_by RAND with my code below in codeigniter


i have this code :

$select = ['account_access_token','account_config_id'];       
$where = ['where'=>['enable_marketing' => '1', 'account_config_id.id!=' => $account_table_id]]; 
$join
=['account_user_info'=>'account_config_id.account_user_info_id=account_user_info.id,left'];       
$pages_info = $this->basic->get_data('account_config_id',$where,$select,$join);

so as you see i want to load an account into my target page

my question is : how to load the $pages_info results randomly ?

i tried to add : RAND(), $order_by='RAND()' but its dosen't work
every time the account id=$id is loaded with no change thanks a lot in Advanced

no luck with search


Solution

  • Codeigniter's query builder's orderBy accepts RANDOM as order direction and will then ignore the first parameter (usually the field name), unless the first parameter is numeric, in which case it will be used to seed RAND().

    $builder->orderBy('account_config_id', 'DESC');
    // Produces: ORDER BY `account_config_id` DESC
    
    $builder->orderBy('account_config_id', 'ASC');
    // Produces: ORDER BY `account_config_id` ASC
    
    $builder->orderBy('account_config_id', 'RANDOM');
    // Produces: ORDER BY RAND()
    
    $builder->orderBy(12, 'RANDOM');
    // Produces: ORDER BY RAND(12)