$mainquery = "SELECT id FROM record_choices"; //grab all record ids $mainresult = mysql_query($mainquery) or die('Error : ' . mysql_error()); $row = mysql_fetch_array($mainresult, MYSQL_ASSOC); $all_ids = $row['id']; foreach($_data as $value) { //loop through all the ids $query = "SELECT SUM(points) points FROM year_end_votes WHERE record_id = '$value'"; //add up all scores for all occurences of id $result = mysql_query($query) or die('Error : ' . mysql_error()); if($result && mysql_num_rows($result) == 1) { $row = mysql_fetch_assoc($result); $all_points = $row['points']; echo "Total score for record $value = {$all_points}
"; //print total score for record id } }