Web Analytics Made Easy -
StatCounter Database values as $Variables - CodingForum

Announcement

Collapse
No announcement yet.

Database values as $Variables

Collapse
X
 
  • Filter
  • Time
  • Show
Clear All
new posts

  • Database values as $Variables

    I have a Database Table called test_config with 2 colums, called Name & Value.
    I would like to loop through each row and create $Variable's from the name and value
    e.g $Name = "Value";
    Tried various examples from web but cant get them to work.

    Code:
    try {
        $conn = new PDO("mysql:host=".DB_HOST.";dbname=".DB_NAME."", DB_USERNAME, DB_PASSWORD);
        // set the PDO error mode to exception
        $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        echo "Connected successfully";
    	
    	$stmt = $conn->prepare("SELECT * FROM test_config");
        $stmt->execute();
    
        // set the resulting array to associative
        $result = $stmt->setFetchMode(PDO::FETCH_ASSOC);
    
    	foreach($stmt->fetchAll() as $key => $value) {
            //extract($value, EXTR_OVERWRITE);
    		var_dump($value);
    		//$$key = $value; 
    
    		
        }
    
        }
    catch(PDOException $e)
        {
        echo "Connection failed: " . $e->getMessage();
        }
    $conn = null;

  • #2
    It seems you have asked a similar question before - http://www.codingforum.net/php/33543...e-entries.html

    The reason why the first reply stated creating discrete variables is a bad idea is because you must now insure that the name values stored in the database table are never one of your existing program variables to avoid overwriting data and causing unexplained program bugs.

    You would instead store the data in an array. If these are settings or configuration data, store it into an array named $settings, $config, or a similar named array to distinguish it and keep is separate from all other program variables.

    See the second reply in that thread for a PDO fetch mode that will create such an array for you.
    Finding out HOW to do something is called research, i.e. keep searching until you find the answer. After you attempt to do something and cannot solve a problem with it yourself, would be when you ask others for help.

    Comment


    • #3
      Thanks for replying, I'v no memory of making that previous post.

      Thanks.

      Comment

      Working...
      X