3

注意:我是 PHP 初学者,这就是为什么下面的代码可能不好的原因。

你好。我目前正在使用此代码来选择 9 个唯一的随机行,它工作正常。

$quCountRows = $database->query("SELECT * FROM approved")->rowCount();
$arrRandomPictures = array();
while (count($arrRandomPictures) < 9) {
    $randNumber = mt_rand(1, $quCountRows);
    if (!in_array($randNumber, $arrRandomPictures)) {
        $arrRandomPictures[] = $randNumber;
    }
}
$quRandomPicture1 = $database->query("SELECT picName,picType FROM approved WHERE id='".$arrRandomPictures[0]."'")->fetch(PDO::FETCH_ASSOC);
$quRandomPicture2 = $database->query("SELECT picName,picType FROM approved WHERE id='".$arrRandomPictures[1]."'")->fetch(PDO::FETCH_ASSOC);
$quRandomPicture3 = $database->query("SELECT picName,picType FROM approved WHERE id='".$arrRandomPictures[2]."'")->fetch(PDO::FETCH_ASSOC);
$quRandomPicture4 = $database->query("SELECT picName,picType FROM approved WHERE id='".$arrRandomPictures[3]."'")->fetch(PDO::FETCH_ASSOC);
$quRandomPicture5 = $database->query("SELECT picName,picType FROM approved WHERE id='".$arrRandomPictures[4]."'")->fetch(PDO::FETCH_ASSOC);
$quRandomPicture6 = $database->query("SELECT picName,picType FROM approved WHERE id='".$arrRandomPictures[5]."'")->fetch(PDO::FETCH_ASSOC);
$quRandomPicture7 = $database->query("SELECT picName,picType FROM approved WHERE id='".$arrRandomPictures[6]."'")->fetch(PDO::FETCH_ASSOC);
$quRandomPicture8 = $database->query("SELECT picName,picType FROM approved WHERE id='".$arrRandomPictures[7]."'")->fetch(PDO::FETCH_ASSOC);
$quRandomPicture9 = $database->query("SELECT picName,picType FROM approved WHERE id='".$arrRandomPictures[8]."'")->fetch(PDO::FETCH_ASSOC);

虽然它可能有效,但我很确定用更少的查询可以获得相同的结果。希望这会导致页面加载更快。

有什么建议么?


这是更好的代码。感谢琥珀!

$quCountRows = $database->query("SELECT * FROM approved")->rowCount();
$arrRandomPictures = array();
while (count($arrRandomPictures) < 9) {
    $randNumber = mt_rand(1, $quCountRows);
    if (!in_array($randNumber, $arrRandomPictures)) {
        $arrRandomPictures[] = $randNumber;
    }
}
$quRandomPicture = $database->query("SELECT picName,picType FROM approved WHERE id IN (".implode(', ', $arrRandomPictures).")")->fetchAll(PDO::FETCH_ASSOC);
4

2 回答 2

3

使用in代替==并传递 ID 列表。这样您就可以从一个查询而不是 9 个查询中获得所有结果。

于 2012-08-11T21:39:56.773 回答
1

您可以按随机数排序,每次都可以得到其他结果。这样,您只需要一个查询!

SELECT picName, picType FROM approved ORDER BY rand() LIMIT 0, 9;
于 2012-08-11T21:42:05.447 回答