且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何从 mysql 数据库中选择随机行(比如 100 中的 10)并用数字串联显示它们

更新时间:2023-12-05 11:40:46

您可以使用 PHP rand() 函数.这是它的教程:https://www.w3schools.com/php/func_math_rand.asp
还要给他们一个有序列表,使用

    .

    例子

    $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 "
      $data
    ";}别的{//在什么都没有建立的时候你想做的任何事情.}}

    请注意,您可能想要使用准备好的语句,上面的示例假设 $link 是数据库连接,field 是列名.

    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

    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.