Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
238 views
in Technique[技术] by (71.8m points)

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

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...