# Selecting random records: PHP

**URL:** <https://forum.kirupa.com/t/selecting-random-records-php/164581>\
**Category:** programming\
**Created:** [October 3, 2005, 3:51am UTC](https://forum.kirupa.com/t/selecting-random-records-php/164581 "2005-10-03T03:51:19Z")\
**Posts on this page:** 4\
**Page:** 1

<div class="post-metadata">

**Author:** ![dinkumrocks](https://avatars.discourse-cdn.com/v4/letter/d/7feea3/32.png) [@dinkumrocks](https://forum.kirupa.com/u/dinkumrocks)\
**Post date:** [October 3, 2005, 3:51am UTC](https://forum.kirupa.com/t/selecting-random-records-php/164581/1 "2005-10-03T03:51:19Z")

</div>

Hey guys. Im just learning php. i know asp, and decided to learn php. anyway.

I need to select random records from a database. As all of you know, records can be deleted and whatnot, leaving gaps. I’m drawing somewhat of a blank on this, and I’m also new to all of php’s awsome functions.

any help would be awsome.

-Naaman

---

<div class="post-metadata">

**Author:** ![WishAngel](https://avatars.discourse-cdn.com/v4/letter/w/45deac/32.png) [@WishAngel](https://forum.kirupa.com/u/WishAngel)\
**Post date:** [May 22, 2008, 7:15pm UTC](https://forum.kirupa.com/t/selecting-random-records-php/164581/2 "2008-05-22T19:15:59Z")

</div>

Hello people! I`m also new in php...and I have a problem :-s...so I beg you to help me if you can... I`ve created a quiz with an mysql database …the quiz has 20 questions…and I want…everytime a user enters to take the quiz, all 20 questions to be showed random…not in the same order… If you can help me with a little piece of code…you will make me a happy man :-s… please help and sorry for my bad english ☹

---

<div class="post-metadata">

**Author:** ![WishAngel](https://avatars.discourse-cdn.com/v4/letter/w/45deac/32.png) [@WishAngel](https://forum.kirupa.com/u/WishAngel)\
**Post date:** [May 23, 2008, 11:34pm UTC](https://forum.kirupa.com/t/selecting-random-records-php/164581/3 "2008-05-23T23:34:23Z")

</div>

🙂 Thank you! I resolve it! the code adapted to my situation looks like:

```auto
$cerereSQL = "SELECT DISTINCT * FROM `intrebari` WHERE nrsecuritate='$nrsecuritate' ORDER BY rand() LIMIT 20";
   $rezultat = mysql_query($cerereSQL);

```

Thank you!

---

<div class="post-metadata">

**Author:** ![kdd](https://avatars.discourse-cdn.com/v4/letter/k/ecb155/32.png) [@kdd](https://forum.kirupa.com/u/kdd)\
**Post date:** [May 24, 2008, 12:43am UTC](https://forum.kirupa.com/t/selecting-random-records-php/164581/4 "2008-05-24T00:43:24Z")

</div>

I should point out that using rand() in query is very slow. I tested it out this just a couple of days ago with 2+ million records, and it took 30+ seconds. A better way is to use php’s mt\_rand ( min , max ) function, and then generate 5-10 random numbers, and then select those rows. Much much faster, especially if you have primary\_key\_id = ‘rand\_num’ !
