You calculate the median for all the rows, not just the rows in that specific year. Your query needs to be limited by the year that you're currently looking at. So as you loop through $result2 to show the results, you need to execute query 1 with the addition of another part of the WHERE clause stating: year='$row[year]';
Then calculate the median.
Also, you're median calculation is backwards. If it's an even number of units (10) then the median is not 5, but rather 5+6/2. Proof:
NOTE: I did not use 1 - 10, but rather 0-9. So your projected median is 4.
0 1 2 3 4 5 6 7 8 9
You say the number in bold is the median, when in fact it's not. The number in bold has 4 on the left, and 5 on the right. So you need to get the mean of 4 & 5.
0 1 2 3 4 4.5 5 6 7 8 9
0 1 2 3 4 5 6 7 8
With an odd number of units, you just floor the number /2 (floor($num/2)). So 9 = 4, 15 = 7 etc.