-2

How do I select random rows (say 10 from 100) from mysql database and display them with a number in series

Any random rows get selected and give them like

1. XXXXX
2. YYYYY
3. ZZZZZ

but in database they are not in series

Strawberry
  • 33,750
  • 13
  • 40
  • 57
  • What is your mysql version ? Also, think `order by rand()` – Madhur Bhaiya Oct 04 '18 at 10:35
  • Maybe this answer can help https://stackoverflow.com/questions/4329396/mysql-select-10-random-rows-from-600k-rows-fast – Anton Oct 04 '18 at 10:35
  • 1
    Let's pretend instead that you want to select 3 random rows from 10. With that in mind, see: [Why should I provide an MCVE for what seems to me to be a very simple SQL query?](https://meta.stackoverflow.com/questions/333952/why-should-i-provide-an-mcve-for-what-seems-to-me-to-be-a-very-simple-sql-query) – Strawberry Oct 04 '18 at 10:36
  • For an ordered list you can use HTML `
      ` https://developer.mozilla.org/en-US/docs/Web/HTML/Element/ol
      – brombeer Oct 04 '18 at 10:36

    1 Answers1

    0

    You could use the PHP rand() function. Here's the tutorial for it : https://www.w3schools.com/php/func_math_rand.asp
    Also to gave them an ordered list, use <ol>.

    Example

    $iWantThisManyRow = 4;
    $minNumber = 10;
    $maxNumber = 100;
    
    for ($i=0; $i < $iWantThisManyRow; $i++) { 
        $rand = rand($minNumber, $maxNumber);
        $sql = "SELECT * FROM `tables` WHERE `id` = '$rand'";
        $result = mysqli_query($link, $sql);
        if(mysqli_num_rows($result) > 0) {
            $data = mysqli_fetch_assoc($result);
            $data = $data['field'];
            echo "<ol>$data</ol";
        }else{
            // Whatever you wanted to do when nothing was founded.
        }
    }
    

    Please note that you might want to use prepared statement and the example above is assuming $link is the database connection and field is the column name.

    PlanetCloud
    • 314
    • 2
    • 11