How can PHP be used to dynamically handle image URLs in a classified ads marketplace?
In a classified ads marketplace, images are often stored in a database or on a server with dynamic URLs. To handle these image URLs dynamically in PHP, you can create a script that retrieves the image URL from the database based on the ad listing and displays the image on the webpage.
<?php
// Assuming $ad_id is the ID of the ad listing
// Connect to the database
$conn = new mysqli("localhost", "username", "password", "database");
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Query to retrieve image URL based on ad ID
$sql = "SELECT image_url FROM ads WHERE id = $ad_id";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// Output image tag with dynamic image URL
$row = $result->fetch_assoc();
echo '<img src="' . $row["image_url"] . '" alt="Ad Image">';
} else {
echo "Image not found";
}
$conn->close();
?>