/* This is assuming your DB tables are setup similar to this: //Image Caption Table image_id caption //Image Title Table image_id title // image_id must be the same value in both tables per image */ while( $imageRow = mysql_fetch_assoc($imgResult) ) { $data[$imageRow['image_id']]['caption'] = $imageRow['caption']; } while( $row = mysql_fetch_assoc($result) ) { $data[$row['image_id']]['title'] = $row['title']; } foreach( $data as $singleElement ) { echo $singleElement['title'] . "
"; echo $singleElement['caption'] . "
"; }