2

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? 

}
2
  • 3
    I think an associative array would work best for you here. Commented Mar 4, 2014 at 14:21
  • 9
    You do NOT want to generate a variable-per-value. That's just insane. Use an array. Commented Mar 4, 2014 at 14:22

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

3 Comments

man are you kidding?! that's a bad practice, just tell him to use an array!
@CodeBird Yeah I did, see the bold
the first example works fine, but i want to learn he proper way of doing things. What should i be doing with the array after?
0
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.

4 Comments

This will do what the OP wanted. But I don't know if it's a good idea ;)
that's a bad practice!
I would rather put unvalidated $_GET parameters into my eval() and exec() instead of using this code ...
I simply answered the question but since everyone is jumping on the bad aspects of this, I've expanded the answer :-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.