What are some best practices for handling image paths and descriptions in PHP when creating a gallery?

When creating a gallery in PHP, it's important to properly handle image paths and descriptions to ensure a smooth user experience. One best practice is to store image paths in a separate database table along with corresponding descriptions. This allows for easy retrieval and management of images. When displaying images in the gallery, always sanitize user input to prevent any security vulnerabilities.

// Connect to database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "gallery";
$conn = new mysqli($servername, $username, $password, $dbname);

// Fetch image paths and descriptions from database
$sql = "SELECT path, description FROM images";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
    // Output images with descriptions
    while($row = $result->fetch_assoc()) {
        echo '<img src="' . $row["path"] . '" alt="' . $row["description"] . '">';
    }
} else {
    echo "0 results";
}

// Close database connection
$conn->close();