Question:

PHP: Defining globals from a database?

by  |  earlier

0 LIKES UnLike

I have a settings file in the site I am developing which contains global site settings using this structure:

define("DB_SERVER", "localhost");

What I'd like to do instead, is create a table in the database which contains the globals and call them like:

---------------------

// Connect to the database

$conn = mysql_connect("localhost", "user", "password") or die(mysql_error());

// Grab global variables from the Site Preferences table

$query = "SELECT field, value FROM prefs ORDER BY id ASC";

$getGlobals = mysql_query($query, $conn);

while($global = mysql_fetch_array($getGlobals)){

   $field = stripslashes($global['field']);

   $value = stripslashes($global['value']);

   define($field, $value);

}

// Close the connection

mysql_close($conn);

---------------------

I can't seem to get this working though...When I call any of the defined globals they aren't recognized as defined. Anyone have suggestions on how I can get this to work?

 Tags:

   Report

3 ANSWERS


  1. Hey Chris,

    I dug up some code that I am positive works.  I used it in a lot of my CMS systems.  I define this in the settings file that is included on every page.  Also, I am using ezsql class.

    <?php

    //////////////////////////////////////...

    // DEFAULT VALUES FOR THE CMS SYSTEM

    //////////////////////////////////////...

    $get_defaults = $db->get_results("SELECT * FROM system_defaults");

    foreach($get_defaults as $tmp_default)

    {

       $tmp_name = $tmp_default->default_field;

       $tmp_value = $tmp_default->default_value;

       // Set the default field and value

       if(!define("$tmp_name",$tmp_value))

       {

          echo "Not defined!";

       }

    }

    ?>

    Maybe that will help,

    Chad


  2. $global is ok, only $globals is reserved. Beware to the case: constants are case sensitive (or use define($field, $value, true);).

    Otherwise, if $field can be a valid identifier, there's nothing wrong with your code...

  3. From first glance, it seems like it should work...the only thing I can think of is that you may not be using the "global" keyword to import the variables to a local scope before using them?

Question Stats

Latest activity: earlier.
This question has 3 answers.

BECOME A GUIDE

Share your knowledge and help people by answering questions.
Unanswered Questions