比这更快更有效的代码? (抓住9个独特的随机行)

时间:2012-08-11 21:37:13

标签: php mysql pdo

注意:我是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);

虽然它可能有效但我很确定使用较少的查询可以获得相同的结果。希望能够更快地加载页面。

有什么建议吗?


这是更好的代码。感谢Amber!

$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);

2 个答案:

答案 0 :(得分:3)

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

答案 1 :(得分:1)

您可以通过随机数订购并每次获得其他结果。 这样,您只需要一个查询!

SELECT picName, picType FROM approved ORDER BY rand() LIMIT 0, 9;