1

I would like to display a random clickable image on the front page of my website but I can't figure out how to do it.

I have a table named "oeuvre" with the columns "id_image" and "id_oeuvre" (PK) both as int(11) I also have a img folder which is in the same folder as my index.php

I can use html, php and js but I have to use PDO for my requests to the database. I tried this

<a href="">
    <img class="xx" src="'img/'+'<?php echo($pdo->query('SELECT id_image FROM oeuvre ORDER BY RAND() LIMIT 1'));?>'+'.jpg'" alt="Random Image">
</a>

But this doesn't work, it makes me have an empty <a></a>

So I tried this also to make "sure" I wasn't on a bad request

<a href="">
    <img class="xx" src="'img/'+'<?php echo($db->query('SELECT id_image FROM oeuvre ORDER BY RAND() LIMIT 1', PDO::FETCH_ASSOC ));?>'+'.jpg'" alt="Random Image">
</a>

But it didn't worked as well, so I tried to search for something else and tried js (which I found on web), which got me this

<script type="text/javascript">

    var random_images_array = ['451732624.jpg', 'bg.jpg', 'calendar.png'];  

    function getRandomImage(imgAr, path) {
    path = path || 'img/'; // default path here
    var num = Math.floor( Math.random() * imgAr.length );
    var img = imgAr[ num ];
    var imgStr = '<img src="' + path + img + '" alt = "">';
    document.write(imgStr); document.close();

}
</script>

with this 

<a href=""><script type="text/javascript">getRandomImage(random_images_array, '/img');</script></a>

which still doesn't work

Does anyone has an idea I could try or maybe could find a mistake I made which makes it all doesn't work ? Thank you for your future help and hope you all have a good day

Kinra
  • 11
  • 1
  • For starters, is `Random Image` being handled inside Javascript somewhere? Because I don't see the need for `+` otherwise. In plain HTML, this would place a literal `+` into the image path. – El_Vanja Jun 02 '21 at 08:50
  • No this isn't handled in Javascript, should it looks like this : ```Random Image``` ? – Kinra Jun 02 '21 at 08:56
  • You don't need the single quotes around `img` or `jpg`, you're not in PHP there. As I said, the safest way to see what your code generated is to check the page source and view the generated HTML. This should give you a hint what you need to tweak in the image source. – El_Vanja Jun 02 '21 at 09:01
  • how would it look like ? Tried with and without and still doesn't work – Kinra Jun 02 '21 at 13:13
  • I've just noticed another problem... do you have [error displaying](https://stackoverflow.com/questions/1053424/how-do-i-get-php-errors-to-display) turned on? Because PHP should be complaining about you trying to turn a `PDOStatement` object into a string (if your query succeeded). You need to fetch data before you can print it. I would suggest that you don't do it inline like now. Do the fetching, assign it to a variable and then just echo the variable inside the source: `src="img/.jpg"` – El_Vanja Jun 02 '21 at 13:40

0 Answers0