What I want to do is to display 5 random images with text out of a certain number without repeating. The links to images and the texts are to be stored in the database. The issue I’ve run into is I need to put every ID value into the single PHP array in order to shuffle the IDs and pick random 5, yet I keep failing in combining them into a single array, if I have 3 rows I end up with 3 arrays.
This is an example of a failing code with 3 rows with ID 1,2,4:
function getAll () {
$query = mysql_query("SELECT * FROM ads") or die(mysql_error());
$myarray = array();
while ($numbers = mysql_fetch_array($query)){
$arr = $numbers['ID'].",";
print_r (explode(",", $arr));
}
};
This is the output:
Array ( [0] => 1 [1] => ) Array ( [0] => 2 [1] => ) Array ( [0] => 4 [1] => )
This is the desired output:
Array ( [0] => 1 [1] => 2 [2] => 4)
Guess it’s a noob question but I’ve done my best in trying to find the solution and failed.
Easy solution: Shuffle the result directly by using
ORDER BY RAND()in your MySQL query: