You are needlessly accessing the database way too much. Like Psycho said, you can do mostly everything with just sessions. The sessions aren't going to change, so they are perfectly reliable.
User authentication is risky business. It's easy to get wrong, easy to inadvertently create security holes. If you don't know what you are doing, it is best to use someone elses library that has already been under extreme scrutiny. Maybe take a look at how some of the popular frameworks do authentication. Here is an example to get you started: Ion Auth Ion auth is pretty simple, so it shouldn't be too hard to pickup the logic.