The only real solution is practice. Erection duration, normally, should last until after orgasm, or until you've not stimulated it enough. It normally shouldn't go flaccid when you're engaging in sex and haven't orgasmed. The reasons for this can be mental or physical.
Most of the time it's mental... the man is nervous or too eager to please his partner and his penis, under all this mental pressure, fails to perform. Unfortunately, the only way to help this problem is to develop trust and to practice.
If it's a physical problem, and you're convinced it's not a mental thing, you should see a doctor. They can better assess the situation and suggest the proper, safe course of action.