I am trying to 27 display random images on my website and for that I’ve stored the image source in my database.
$query = "SELECT imgURL from my_db;"; $stmt = $con -> prepare($query); $stmt -> execute(); $imgURL = $stmt->fetchAll(); $img_array = array(); function getImgURL($imgURL,$arr_index,&$img_array){ if(!in_array($arr_index, $img_array)){ array_push($img_array,$arr_index); return strval($imgURL[$arr_index][0]); } else{ getImgURL($imgURL,rand(0,94),$img_array); } } for($i = 0 ; $i<=27; $i++){ echo '<img class="img-fluid" src="'.getImgURL($imgURL,rand(0,94),$img_array).'">'; }
To prevent duplicacy I’ve created an array ($img_array) to which I will push the index of the randomly generated image and then check whether the value is already in the array or not.
The if block works fine but problem occurs in the else block as it returns “unknown
” to the src
attribute.
Advertisement
Answer
I am trying to 27 display random images on my website
Rather than running 27 queries with additional application logic in between, why not simply shuffle in the database?
select imgURL from my_db order by rand() limit 27;
This sibgle query gives you random 27 records from table my_db
, which seems to be just what you are after, without any additional code on application side. All that is left to do is fetch the results and display them in your application.