如何从MySQL中检索1个随机行

时间:2014-01-19 00:45:45

标签: php mysql arrays

我正在制作一个随机的post生成器,代码如下:

<?php

$idea_generator = array();

    $ideas_sql = "SELECT * FROM Ideas";
    $query = mysql_query($ideas_sql);



        while($row = mysql_fetch_assoc($query)) {
                $id = $row['id'];
                $name = $row['name'];
                $description = $row['description'];
                $keywords = $row['keywords'];
                //Need to add a link function




            array_push($idea_generator, $name);
                sort($idea_generator);
                $number = count($idea_generator);
                //randomly selects idea
                $winner = $idea_generator[rand(0, $number -1)];
                print strtolower($winner);

                }

?>

我的问题是这段代码以不同的顺序返回测试数据库中的3个项目。此项目旨在从该数据库中仅取出1个项目。我应该坚持使用这种php数组方法,还是有更简单的方法来实现这一目标。

1 个答案:

答案 0 :(得分:3)

将您的查询更改为此选项以随机检索一行:

$ideas_sql = "SELECT * FROM Ideas ORDER BY RAND() LIMIT 1;";

由于此查询仅返回一行,因此您不再需要在PHP代码中选择一个随机行。你的最终代码可能是这样的:

$ideas_sql = "SELECT * FROM Ideas ORDER BY RAND() LIMIT 1;";
$query = mysql_query($ideas_sql);

$row = mysql_fetch_assoc($query);
// This is your 'winning' row

$id = $row['id'];
$name = $row['name'];
$description = $row['description'];
$keywords = $row['keywords'];