in reply to same database problem

Learn to debug!
sprinkle 'print STDERR's through the execution-path and see what data you really have on each step, for a start, to see if it does what you think it's doing, try to isolate the problem in your code, if you wouldn't understand the why and therefore ask why something happens, instead of asking what actually happens, that would be a real progress.

regards,
tomte


Hlade's Law:

If you have a difficult task, give it to a lazy person --
they will find an easier way to do it.