每次页面刷新时都不会检索来自 mysql 的数据

我试图从 mysql 数据库中获取随机数据,但它只在页面刷新时获取同一行


我尝试运行查询以从 mysql 获取随机单行数据并使用 php 在网页上显示,但它每次只检索同一行 $sql = "SELECT * FROM identity_explorer_demographics ORDER BY RAND() LIMIT 1


<?php




$link = mysqli_connect("host", "username", "password", "db_name");


if($link === false){

    die("ERROR: Could not connect. " . mysqli_connect_error());

}



$sql = "SELECT * FROM identity_explorer_demographics ORDER BY RAND() LIMIT 1";



if($result = mysqli_query($link, $sql)){

    if(mysqli_num_rows($result) > 0){

        echo "<table>";

            echo "<tr>";

                echo "<th>email_md5</th>";

                echo "<th>age_group </th>";

                echo "<th>age</th>";

                echo "<th>income</th>";

                echo "<th>Income_group </th>";

                echo "<th>gender</th>";

            echo "</tr>";

        while($row = mysqli_fetch_array($result)){

            echo "<tr>";

                echo "<td>" . $row['email_md5'] . "</td>";

                echo "<td>" . $row['age_group'] . "</td>";

                echo "<td>" . $row['age'] . "</td>";

                echo "<td>" . $row['income'] . "</td>";

                 echo "<td>" . $row['Income_group'] . "</td>";

                echo "<td>" . $row['gender'] . "</td>";

            echo "</tr>";

        }

        echo "</table>";

        // Free result set

        mysqli_free_result($result);

    } else{

        echo "No records matching your query were found.";

    }

} else{

    echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);

}


// Close connection

mysqli_close($link);

?>



每次刷新页面时,我都需要显示随机行数据。如果有人可以建议是最佳解决方案,那真的会很有帮助。


有只小跳蛙
浏览 164回答 2
2回答

白衣染霜花

你把它和 PHP 混在一起$sql = 'SELECT * FROM `identity_explorer_demographics`';//Perform query and parse result, E.G $sql = db::query($sql);function getRandomRow($sql) {&nbsp; &nbsp;$random_row = count(0, count($sql));&nbsp; &nbsp;foreach($sql as $row => $result) {&nbsp; &nbsp; &nbsp; if ($row == $random_row) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;return $row;&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp;}}

吃鸡游戏

$sql = "SELECT * FROM identity_explorer_demographics ORDER BY RAND() LIMIT 1";将行更改为$ randomv = rand (min, max);$sql = "SELECT * FROM identity_explorer_demographics ORDER BY $randomv LIMIT 1";这是我在另一种情况下的实现,我必须从可用的随机 id 中进行选择 - Yii 2 Framework&nbsp; &nbsp;$prodcutids= \app\models\TblProduct::find()->all();&nbsp; &nbsp; $targetproduct=&nbsp; ArrayHelper::map($prodcutids, 'id','id');&nbsp; &nbsp; $productdetails= \app\models\TblProduct::findOne(['id'=>array_rand($targetproduct)]);&nbsp; &nbsp; $productseriesname= \app\models\TblSeries::findOne(['id'=>$productdetails['Serie']]);或者,如果您有一个 id 列$sql = "SELECT * FROM identity_explorer_demographics WHERE id=$randomv LIMIT 1";rand(min,max) min 指定将返回的最小值。max 指定要返回的最大值。
打开App,查看更多内容
随时随地看视频慕课网APP