SQL Statements in Include files

Hello,

I have a beginner question.

I have several php pages which reference a common sql.php page, via include, for connection to my MySQL database and querying tables for values. I would like to keep all my sql code in one place, however, I believe that anytime one of these pages includes the sql.php file all of the sql statements in this file are executed.

Could someone please let me know what is the best way to keep your sql statements in one file and only have the ones I need for a particular page be executed. I am thinking of dropping every sql statement into a separate function, but that seems like a hack to me.

Thank You in Advance,
-Chris

I am thinking of dropping every sql statement into a separate function, but that seems like a hack to me.

I don’t think of coding this way as a hack. Using functions is a good way to code and helps solve problems like the one you are running into. For my projects I have created a dataAccessor class which contains all of my sql functions. The connection functions will always stay the same, and you can just write new query functions for each project you work on.

Inserting code into a page by using an include function can be useful in some situations, but this is not good style for the most part (in my opinion). It can lead to messy code and can be hard to debug for large projects.

Better get used to making functions ;) Believe me (and Waylon999) when I say they’ll make your life a LOT easier if you plan to use PHP on a regular basis. What Waylon999 speaks of, is called Object Oriented Programming, and is a quite logical way of programming things. It makes the code easier to maintain and reusable. I basically do the same thing: I have a SQLConnector class (it’s up for download in the Code Snippets section of the forum) in which a definition for a class that deals with the connections to a MySQL database is available.

Sponsor our Newsletter | Privacy Policy | Terms of Service