Using variable variables with PHP "list" function

Hi there,

Have spent hours trying to figure this out. The closest I’ve come to finding something close to what I want to do is the post in this forum at http://www.sitepoint.com/forums/showthread.php?t=25948 . However, that wasn’t quite it, and the thread died unresolved anyway.

The situation is that I have a small script that calls a few fields from a database and then prints them out. (I’m simplifying this. The script is obviously more useful than that.) I want to try and make this script as generic as possible, so that I can edit mainly variables and reuse it with minor changes.

Here is code that works:


$query = "select a, b, c from database.table where id=1;";
$result = mysql_query($query);
list($a, $b, $c) = mysql_fetch_row($result);

Pretty straightforward. However, I want to assign the list of fields to a variable, because when I come and reuse this script in the future, the list of variables will change. This still works:


$fields = "a, b, c";
$query = "select $fields from database.table where id=1;";
$result = mysql_query($query);
list($a, $b, $c) = mysql_fetch_row($result);

The problem arises when I try to use a variable for the list of fields inside the “list” function:


$fields = "a, b, c";
$fields_var = "\\$a, \\$b, \\$c";
$query = "select $fields from database.table where id=1;";
$result = mysql_query($query);
list($fields_var) = mysql_fetch_row($result);

Now, I pretty much understand why that doesn’t work, but I haven’t figured out how I can accomplish this. The idea is that I just want to edit the “fields_var” variable when I reuse this script, rather than go trawling through the script to edit code.

I have tried using “eval”. The number of variations of what I’ve tried is really not worth posting, especially as I may even be barking up the wrong tree anyway. Similarly I doubt that posting a stream of PHP errors based on what I’ve done will be helpful. I figure that someone will recognise what I’m trying to achieve and know the answer. I can’t be the first person who has gone down this road. :slight_smile:

Thanks very much.

Craig

Anthony, thank-you. That does the trick, and far more elegantly.

Craig

Check out [fphp]extract/fphp. :slight_smile:


<?php
$fields = 'a, b, c'

$res = mysql_query(sprintf(
    'SELECT &#37;s FROM table',
    $fields
));

extract((array)mysql_fetch_assoc($res));
// you now have $a, $b & $c to work with

?>