Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?PHP
- function get_random_ids_from_table(&$link, $table, $where = null, $length = -1)
- {
- $count_r = mysqli_query($link, 'select count(*) `c` from `' . $table . '`' . ($where ? ' where ' . $where : ''));
- if(!$count_r)
- {
- return array();
- }
- $count = mysqli_fetch_assoc($count_r);
- mysqli_free_result($count_r);
- $count = $count['c'];
- unset($count_sql, $count_r);
- if(!$count)
- {
- return array();
- }
- $ids = array();
- if($length < 1 || $length > $count)
- {
- $ids_r = mysqli_query($link, 'select id from `' . $table . '`' . ($where ? ' where ' . $where : ''));
- while($id = mysqli_fetch_assoc($ids_r))
- {
- $ids[] = $id['id'];
- }
- mysqli_free_result($ids_r);
- shuffle($ids);
- }
- else
- {
- $id_stmt = mysqli_prepare($link, 'select id from `' . $table . '`' . ($where ? ' where ' . $where : '') . ' order by id limit 1 offset ?');
- while(count($ids) < $length)
- {
- $offset = mt_rand(0, $count - 1);
- if(!isset($ids[$offset]))
- {
- mysqli_stmt_bind_param($id_stmt, 'd', $offset);
- mysqli_stmt_execute($id_stmt);
- mysqli_stmt_bind_result($id_stmt, $id);
- mysqli_stmt_fetch($id_stmt);
- $ids[$offset] = $id;
- }
- }
- mysqli_stmt_close($id_stmt);
- $ids = array_values($ids);
- }
- return $ids;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement