0

I'm trying to fetch random no. of entries from a database by using

SELECT QNO FROM TABLE  ORDER BY RAND() LIMIT 10

it returns a column of database.

If I want to save all the entries in a array, then which php function do I have to use to save the column.

5 Answers 5

2

Something along the lines of this?

$result = mysql_query("SELECT QNO FROM TABLE ORDER BY RAND() LIMIT 10");
$rows = array();
while ($row = mysql_fetch_row($result)) {
    $rows[] = $row[0];
}

Updated to not use the $i variable as pointed out in the first post and the comment.

Sign up to request clarification or add additional context in comments.

1 Comment

you don't actually need the counter ($i) here. if you just assign to $rows[] it'll automatically create a new "slot" at the end of the array.
1

Look at some examples for how to run a query and get a result set.

http://www.php.net/mysqli

Once you have the result in a variable, do this:

$myarray = array();
while($row = mysqli_fetch_row($result))
   $myarray[] = $row[0];

Comments

1

With PDO:

$qryStmt = $dbc->query('SELECT QNO FROM TABLE ORDER BY RAND() LIMIT 10');
$a = $qryStmt->fetchAll( PDO::FETCH_COLUMN );

1 Comment

I think you want PDO::FETCH_COLUMN rather than PDO::FETCH_ASSOC
0

BTW: If you just want to get one row by random, this is much faster esp. for large tables:

select * from table limit 12345,1;

where 12345 is just a random number calculated from the count() of rows.

see here, which is more for rails, but have a look at the comments too.

But be careful: in limit 12345,2 - the second row is not random but just the next row after the random row. And be careful: When I remember right (eg. SQLServer) rand() could be optimized by databases other than mysql resulting in the same random number for all rows which makes the result not random. This is important, when your code should be database agnostic.

Comments

0

a last one: do not mix up "random" with "hard to predict", which is not the same. So the order by example "select top 10 ... order by rand()" on SQLServer results in two different result sets when run twice, BUT: if you look at the 10 records, they lie close to each other in the db, which means, they are not random.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.