I just got a new guitar, an Ibanez rg320fm, pre-owned. When I first plugged it into my amp the sound kept cutting out, the slightest movement of the cable would cause the sound to cut out.

I tried using the same cable on my old guitar, and had no problems, so the cable or amp wasn't at fault, it was definitely the input jack on the guitar.

I unscrewed the cover for the jack, had a look at the connections, they were fine, so I screwed it back in. To my surprise I couldn't get the sound to cut out after that, as much as I wiggled the cable around, or shook the guitar, the sound was fine.

How could this have fixed the problem? What should I do if it starts happening again?

there was probably a loose connection somewhere in the circuitry that was loose or so slightly loose you didn't realize you bumped it back into place. happens sometimes especially on cheaper guitars.
the output jack itself was loose. happens to me all the time.
Quote by Anthropocentric
Your balls. You lost the right to them. Hand them over.

Quote by T00DEEPBLUE
What kind of person needs to have a Flying V shoved up their vagina?

Join The 7-String Legion! Now!
What Necronomicon said. You should get in there and resolder all the connections at some point.
Spin 'round carousel when your horse isn't screwed in.

My band:
Fractured Instinct
(For fans of Death/Groove/Prog Metal)

Ibanez RGA42E
Ibanez S420
LTD H-301
Ibanez RG520
Peavey Predator USA
Douglas Grendel 725
Line 6 Pod HD500X