Making a [gallery] in a loop with attachment IDs?

First get all of the feature thumbnail ids, and then populate the gallery. Code –

<?php
global $wpdb;
$featured_ids = $wpdb->get_col("SELECT meta_value FROM $wpdb->postmeta WHERE meta_key='_thumbnail_id'");
$featured_ids = array_map('intval', $featured_ids);
$featured_ids = array_unique($featured_ids);

echo do_shortcode('');
?>