PHP constant from database

0 Benny Lindwall · June 14, 2015
Hi

Is there a way to get the info from a database to be a php constant
like the $q['value'] in the example below will be turned in to a constant from the array.

ex. ( yes, I know you shouldn't use mysql_query() etc functions but it's only for an example )


$query = mysql_query("SELECT `value` FROM `data`")
while($q = mysql_fetch_array($query))
{
echo $q['value'];
}

Post a Reply

Replies

Oldest  Newest  Rating
0 Alan Johnson · June 14, 2015
Yes, instead of echoing it:
define('CONSTANT_NAME', $q['value']);

If by constant you actually just mean variable then it's even simpler:
$variable_name = $q['value'];


Keep in mind that your code is running in a loop so every iteration your variable will be over-written. 
Similarly, if you have already defined CONSTANT_NAME in a previous iteration, you'll get an error.
0 Benny Lindwall · June 23, 2015
the constant is what I want from the database result, if at all possible, cuz it will be defined in a language file so the constant will be different in every iteration and not over-written. I know how I wanna get it but don't know how to perfectly explain it.
0 Benny Lindwall · June 25, 2015
to illuminate what I'm after the table can look like this:

idnamevaluedescription
1somethingCONSTANTWhat this constant shows or stands for
2something_elseANOTHER_CONSTANTWhat this constant shows or stands for that is absolutly not like the other constants

If this help or if I'm trying to do something that is currently impossible, plz, let me know.

Cheers.
+1 Sachin Kumar · July 8, 2015
Try

$query = mysql_query("SELECT `value` FROM `data`")
$loop_num = '1';
while($q = mysql_fetch_array($query))
{
$constant_var = 'constant_'.$loop_num; // to give our dynamic var a name
$constant = $constant_var; // to make our constant var dynamic

/* to finally give our dynamic var a value
(NOTE :" $$ " is used for variable variables.. which is super cool ;))
*/

$$constant = $q['value'];

$loop_num++;
}

then set you constant accordingly!
like


define('CONSTANT_1', 'php');
define('CONSTANT_2', 'asp');
define('CONSTANT_3', 'python');
define('CONSTANT_4', 'ruby');
0 Benny Lindwall · July 9, 2015
thanks, I'll give it a try :)
0 Sachin Kumar · July 9, 2015
welcome :)
  • 1

PHP

107,033 followers
About

Server-side, HTML embedded scripting language used to create dynamic Web pages.

Links
Moderators