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
My Answer:
Here is a solution using PHP and PDO to display a random clickable image on your website:
php
// Connect to the database
$dsn = 'mysql:host=localhost;dbname=your_database_name';
$username = 'your_username';
$password = 'your_password';
try {
$pdo = new PDO($dsn, $username, $password);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
// Get a random image from the database
$stmt = $pdo->prepare('SELECT id_image FROM oeuvre ORDER BY RAND() LIMIT 1');
$stmt->execute();
$image = $stmt->fetch();
?>
Make sure to replace 'your_database_name', 'your_username', and 'your_password' with your actual database credentials. This code will fetch a random image ID from your 'oeuvre' table and display the corresponding image in the 'img' folder on your website.
Rate this post
4 of 5 based on 3997 votesComments