Define all table/column names as constants in PHP?

Questions about the MySQL, PostgreSQL, and most other databases, as well as using it with PHP can be asked here.

Moderator: General Moderators

Post Reply
ywliu
Forum Newbie
Posts: 2
Joined: Wed Dec 24, 2008 10:45 pm

Define all table/column names as constants in PHP?

Post by ywliu »

Hello,

I know there is a kind of practice to define all table and column names, in addition to DB host, DB user , and DB password, as constants in PHP. For example:

define('TB_MEMBER','member');
define('FLD_MEMBERID','memberid');

$sql='SELECT '. FLD_MEMBERID. ' FROM '. TB_MEMBER;

This is a very tiny example. But as the tables grow, there can easily be hundreds of define()s in the code.

I have been looking around to look for any pros and cons to this practice, to no avail. I've been handled a project with more than two hundred of defined table/column constants, which don't make change easier but result in more ugly and messy code and defines.

I personally seldom or never use this approach. I personally think this makes possible db design change a little easier,but with a high price to pay. I'd like to know how you guys think if this practice is good to you.

Thanks for your attention.

Yen-Wei Liu
User avatar
Apollo
Forum Regular
Posts: 794
Joined: Wed Apr 30, 2008 2:34 am

Re: Define all table/column names as constants in PHP?

Post by Apollo »

I sometimes use an array with table names:

Code: Select all

$tables = array( 'members' => 'MyMemberTable' , 'products' => 'Products', 'otherthings' => 'SomeRandomTable' );
 
$sql = "select * from $tables[members]";
Similarly, you could use a nested array for each table's fields:

Code: Select all

$fields = array( // contains an array with fields for each table
'members' => array( 'id' => 'memberid' , 'name' => 'MyNameField' ),
'products' => array( 'id' => 'productid' , 'price' => 'ProductPrice' )
);
 
$sql = "select $fields[members][id] from $tables[members]";
Post Reply