How can a PHP script randomly select and display a banner image from a database on an HTML page?
To randomly select and display a banner image from a database on an HTML page using PHP, you can first query the database to fetch all banner images, then use the rand() function to select a random image from the result set. Finally, display the selected banner image on the HTML page using an <img> tag with the src attribute set to the image URL.
<?php
// Connect to the database
$pdo = new PDO('mysql:host=localhost;dbname=your_database', 'username', 'password');
// Fetch all banner images from the database
$statement = $pdo->query("SELECT * FROM banners");
$banners = $statement->fetchAll();
// Select a random banner image
$randomBanner = $banners[array_rand($banners)];
// Display the selected banner image on the HTML page
echo '<img src="' . $randomBanner['image_url'] . '" alt="Banner Image">';
?>
Keywords
Related Questions
- Where should the LIMIT clause be placed in a MySQL query when retrieving paginated data in PHP?
- Are there any potential pitfalls when trying to access msql functions in PHP while using a MySQL database?
- How can you access Request data in a Factory class in PHP, specifically in the context of Zendframework 2?