Lovelock
Lovelock

Reputation: 8075

Setting PHP variables in this foreach loop

i have a database table that is set up like so::

ID | NAME  | VALUE
1  | item1 | item1value
1  | item2 | item2value

and so on...

what i want to do, is on a sql query, loop through all the rows and set a variable which is:

$name = $value

This should then set e.g. 2 variables of:

$item1 = item1value
$item2 = item2value

How can i do this in a foreach loop?

CONNECTION DETAILS ETC

$dsn        = "mysql:host=$server;dbname=$database";

$db = new PDO($dsn, $username, $password);
$db->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );

$query = "SELECT * FROM `values`";

try
{ 
    $stmt = $db->prepare($query); 
    $stmt->execute(); 
} 
catch(PDOException $ex) 
{ 
    die("Failed to run query: " . $ex->getMessage()); 
} 

$rows = $stmt->fetchAll(); 

foreach($rows as $row){

   // WHAT TO PUT HERE? 

}

Upvotes: 2

Views: 558

Answers (2)

vogomatix
vogomatix

Reputation: 5041

foreach($rows as $row){
   list( $var, $value) = each( $row);
   $$var = $value;
}

As others have stated, this is incredibly bad practice and I have only provided this response under duress and to directly answer the question!!

It is bad because it has the potential to overwrite existing variables and you have no guarantee that some numpty has not damaged your database table of name => value associations in some way.

Upvotes: 0

Pattle
Pattle

Reputation: 6016

You could do

foreach($rows as $row){
   $$row['name'] = $row['value']
}

Or you could use an associative array which is a BETTER WAY TO DO IT and do

$aResults = array();
foreach($rows as $row){
   $aResults[$row['name']] = $row['value']
}

This first way is bad practice because the variable names will change depending on the values in the database. Someone might change something in the database which could break your code

Upvotes: 2

Related Questions