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
Define all table/column names as constants in PHP?
Moderator: General Moderators
Re: Define all table/column names as constants in PHP?
I sometimes use an array with table names:
Similarly, you could use a nested array for each table's fields:
Code: Select all
$tables = array( 'members' => 'MyMemberTable' , 'products' => 'Products', 'otherthings' => 'SomeRandomTable' );
$sql = "select * from $tables[members]";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]";