Note: I’m a PHP beginner which is why the code below might be bad.
Hi. I’m using this code at the moment to select 9 unique random rows and it works fine.
$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);
Although it may work I’m pretty sure the same results can be obtained with less queries. Which would hopefully result in the page loading quicker.
Any suggestions?
Here’s the better code. Thanks to 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);
Use
ininstead of==and pass a list of IDs. That way you can get all of the results from one query rather than 9.