I’m just learning PHP and I’m trying to figure out how I could store my database queries in a separate file either as part of a class, method or just as simple variables.
For example: I have a query that looks like this:
$checkuser = mysql_query("SELECT UserName, Email FROM users
WHERE UserName = '$username4db' OR EMAIL = '$email4db'")
or die($checkuser_error);
Instead of writing it inline within the file, I’d like to move this to a central place and then use them from there.
I tried using an include file and simply calling the variable in place but it doesn’t work.
You should look at the MVC design pattern, the whole purpose is to provide a clean way of organizing code based on function.
The models are where your database interaction code goes. Depending on the MVC implementation this is sometimes a direct representation of the database table, or it could be a collection of functions you write yourself to deal with the problem at hand.
The views are for display code. As a general rule when writing views only HTML and basic PHP (echoing variables, a foreach loop to build a table) should go in the view.
The controller is where the program logic is placed. From the controller you call models to do the data processing necessary to build the data that is then passed into the view.
That’s a very basic explanation, and always wikipedia has more to say on the topic: http://en.wikipedia.org/wiki/Model-view-controller.
There are many MVC frameworks out there in PHP that you can use to have a good starting point for building sites. I use and recommend CodeIgniter as it’s very easy to use and flexible in its implementation.