0

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.

Here's a screenshot of the console window

0

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

What if the images repeat ?
@SAMUEL: the query cannot return the same record twice. You get 27 different records, randomly chosen.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.