Page 1 of 1

Define all table/column names as constants in PHP?

Posted: Wed Dec 24, 2008 10:53 pm
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

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

Posted: Thu Dec 25, 2008 2:17 am
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]";