My guitar/bass cable will sometimes accidentally unplug from my guitar/bass when I am playing at a practice or at a gig. It usually happens when I move around or step on my cable. Is there a way to prevent this from happening?
Yes there is a very simple way to prevent this. Instead of just plugging it in directly to your guitar/bass, you can loop it though your strap(picture coming soon).
By doing this, all the force from stepping on your cable or moving to much will be transferred to your strap and not the input jack. If you do move to far from your amp you could still yank it from the amp or pull the amp so you still do need to be spaciously aware of where you are, but this little trick has saved many performers from embarrassingly having to plug their cable back in to their guitar/bass in the middle of a song.
+1 for looping the cable through your strap.
However if you're really active moving about on on stage, why not consider investing in a decent radio system and do away with the cable altogether? It's by no means a cheap alternative, but the price of reasonable wireless systems have come down such that you only need to have to replace your trodden-on cable a few times to pay for the wireless system.
Wrapping the cable around your strap is also kinder to the cable. If it gets yanked (eg if you step on it), the point where the force is at its most is kind of spread out over the strap, with a bit of give, so the cable will likely survive intact.
If it's just in the plug, it'll either pull it out, or pull sideways and the main 'tug' will be straight on the bit where the cable attaches to the end plug. Quite a good chance of pulling it apart there, resulting in a disposable lead.
I actually don't like the "wrap it round the strap" method, it always looks messy to me, even though it's the "classic solution" to this problem.
If you find your jack comes out very easily, rather than only when you tread on the cable and accidentally give it a good tug (hint: learn not to do this, it's not hard) then it might be that your jack is too loose for your guitar due to small tolerance differences. You can easily tighten your guitar socket as it's a very simple leaf-spring which holds the jack in by pushing on the side... a tiny bend on this can make a big difference. I did this on a guitar I have and it made a huge difference.
You can also get a lead where the jack is at 90 degrees to the cable, then small tugs won't pull it out. But this might look weird depending where your socket is, and could be bad if you tug hard on the cable (again: don't!)