1

FROM array with no key:

$array = array('apple','bee','carrot','dragon','elephant')

To

$newarray = ($apple,$bee,$carrot,$dragon,$elephant)

Why: I want to create flexible function to get fields from a mysql db, like this:

<?php
$query = "SELECT ".$array." FROM table";
$result = mysql_query($query);
while($row = mysql_fetch_array($result)){
        extract($row);
        echo $newarray;
}
?>

So I could:

  • SELECT apple, bee, carrot and echo $apple, $bee and $carrot
  • SELECT bee, carrot, elephant and echo $bee, $carrot, and $elephant
  • or whatever.
2
  • What's wrong with echo $row['apple'], $row['bee'], $row['carrot']? Commented Aug 31, 2012 at 18:11
  • Nothing wrong, but how would I convert $array = array('apple','bee','carrot') to $row['apple'], $row['bee'], $row['carrot'] Commented Aug 31, 2012 at 18:13

2 Answers 2

3

Why don't you just fetch an associative array from the database and then use the key in the associative array like this:

// assume field names are 'apple', 'bee', 'carrot', etc.
while($row = mysql_fetch_assoc($result)){    
    foreach($row as $key => $value) {
        // this will set variables as $apple, $bee, $carrot, etc.
        $$key = $value;
    }
}

Of course this is not all that practical if you get more than one row in your result set, as the variables would just get overwritten.

The key to what you are wanting to do is the use of the variable variable ($$key in this case)

Oh yeah, you should also not be using mysql_* functions but rather mysqli_* or PDO.

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

4 Comments

Will try this. I read about mysqli instead mysql, but I didn't got it right yet! Thanks!
Maybe this $$key and ${$value} are the same?
@Leo The concept of using variable variables is the same. It seemed from the discussion that you wanted the names of the DB fields to be the variable names, in which case you would use the keys. If you really wanted to reference variables with the same name as your database values, then using variable variables on the value names would get you what you want.
Actually I was trying to handle the array typed in a function to call properly the mysql db. Thank you very much, Mike Brant! You were very helpful! Now I'll enforce to learn mysqli!
0
foreach($array as $value){
    $newarray[] = ${$value};
    //Edited: maybe you'll need to reset the array after use it
    unset($newarray);
}

Got it!

Thanks all!

Comments

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.