Advertisement
Guest User

Untitled

a guest
Oct 18th, 2016
194
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.30 KB | None | 0 0
  1. <?PHP
  2.     function get_random_ids_from_table(&$link, $table, $where = null, $length = -1)
  3.     {
  4.         $count_r = mysqli_query($link, 'select count(*) `c` from `' . $table . '`' . ($where ? ' where ' . $where : ''));
  5.         if(!$count_r)
  6.         {
  7.             return array();
  8.         }
  9.        
  10.         $count = mysqli_fetch_assoc($count_r);
  11.         mysqli_free_result($count_r);
  12.         $count = $count['c'];
  13.         unset($count_sql, $count_r);
  14.        
  15.         if(!$count)
  16.         {
  17.             return array();
  18.         }
  19.        
  20.         $ids = array();
  21.         if($length < 1 || $length > $count)
  22.         {
  23.             $ids_r = mysqli_query($link, 'select id from `' . $table . '`' . ($where ? ' where ' . $where : ''));
  24.             while($id = mysqli_fetch_assoc($ids_r))
  25.             {
  26.                 $ids[] = $id['id'];
  27.             }
  28.             mysqli_free_result($ids_r);
  29.             shuffle($ids);
  30.         }
  31.         else
  32.         {
  33.             $id_stmt = mysqli_prepare($link, 'select id from `' . $table . '`' . ($where ? ' where ' . $where : '') . ' order by id limit 1 offset ?');
  34.             while(count($ids) < $length)
  35.             {
  36.                 $offset = mt_rand(0, $count - 1);
  37.                 if(!isset($ids[$offset]))
  38.                 {
  39.                     mysqli_stmt_bind_param($id_stmt, 'd', $offset);
  40.                     mysqli_stmt_execute($id_stmt);
  41.                     mysqli_stmt_bind_result($id_stmt, $id);
  42.                     mysqli_stmt_fetch($id_stmt);
  43.                     $ids[$offset] = $id;
  44.                 }
  45.             }
  46.             mysqli_stmt_close($id_stmt);
  47.             $ids = array_values($ids);
  48.         }
  49.        
  50.         return $ids;
  51.     }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement