Your sum and count variables are initialised before your loops, so their value will persist outside of all loop iterations. This might not be the behaviour you want.
Edit: Now that you're resetting your variables appropriately, you just have one issue left:
You create a temporary image to work with. However, you both read the values of the neighbouring ...
Just check your database. I guess the data has been imported 4 times because of which each name has been printed 4 times. There is no real problem with any of your code.
Hope this helps you. If it does then please check the tickmark.
You have a problem with is_tie, your check value gets overwritten each time the loop goes. You should just return false when you know it isn't a tie and at the end return true if it it didn't end all ready .