Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to define constants dynamically based on database values?

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?

like image 258
Undefined Variable Avatar asked Sep 01 '25 16:09

Undefined Variable


1 Answers

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...;
}
like image 168
Geoffrey Burdett Avatar answered Sep 05 '25 01:09

Geoffrey Burdett