Suggest a feature
×

Welcome to TagMyCode

Please login or create account to add a snippet.
0
0
 
0
Language: PHP
Posted by: Dylan Lopez
Added: Mar 14, 2018 5:33 AM
Views: 19
Tags: random
Get random products from table.
  1. public function random_products($number_of_items = 15,$table_name = NULL){
  2.         if ($table_name == NULL) {return FALSE;}
  3.         $products = array();
  4.         $sql = "SELECT `id` FROM ".$table_name." ORDER BY `id` DESC LIMIT 1";
  5.         $query = $this->db->query($sql);
  6.         $result = $query->row_array(); //return array
  7.         $total_rows = $result['id'];
  8.  
  9.         $products = array();
  10.         $i = 1;
  11.         $succeed_records = 1;
  12.         do {
  13.             $return = $this->db->get_where($table_name, array('id' => rand(1,$total_rows), 'availability_instock' => 1), 1);
  14.             if($return->num_rows() == 1){
  15.                 $result = $return->row_array();
  16.                 array_push($products, $result);
  17.                 $succeed_records++;
  18.                 $i++;
  19.             }
  20.            
  21.         } while ($i < $number_of_items && $succeed_records <= $number_of_items);
  22.         //Console::log($succeed_records);
  23.         return $products;
  24.     }