如何从 mysql 数据库中选择随机行(比如 100 中的 10)并用数字串联显示它们 [英] How do I select random rows (say 10 from 100) from mysql database and display them with a number in series

查看:71
本文介绍了如何从 mysql 数据库中选择随机行(比如 100 中的 10)并用数字串联显示它们的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

任何随机行都被选中并给它们像

<代码>1.XXXXX2. YYYY3.ZZZZZ

但在数据库中它们不是串联的

解决方案

您可以使用 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.

    这篇关于如何从 mysql 数据库中选择随机行(比如 100 中的 10)并用数字串联显示它们的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆