I am using PHP
& MySQL
, but this question is language-agnostic. I have an application in which there is a db table called categories which has category_id
and category_name
.
|---------------------|
| Cat ID | Cat Name |
| --------------------|
| 1 | Desktop |
| 2 | Laptop |
| 3 | Tablet |
| 4 | Smart Phone|
|---------------------|
In the code I need to make comparisons for these IDs in many places, so I defined them as constants so I know what I am comparing:
define("DESKTOP",1);
define("LAPTOP",2);
define("TABLET",3);
define("SMARTPHONE",4);
So now I use them like:
if($user_device == SMARTPHONE)
{
// do something..
}
As categories increase, I am having to define()
them manually. Is this how it is usually done? Can I dynamically query the table and create a list of constants based on category name and id? What is the best way to do this?
Of course, just loop through the database object/array and define the constants.
$categories = mysql_fetch_array( $data );
foreach($categories AS $category)
{
define($category['category_name'],$category['category_id']);
}
But that's not really how a constant was intended to be used. A constant is something that is ALWAYS constant, regardless of the database, or even the application. For instance, PI is a constant. The number of inches in a mile is a constant. The way you are using it should be a variable...
if($user_device == $category['smartphone'])
{
// do something...;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With