moonlightinred Posted April 2, 2009 Share Posted April 2, 2009 Let's say there are 100 fields within a table and, instead of manually using $variable = $row['fieldname']; to assign each one, I'd like to dynamically take all of the results and create variables with the same field name. For example, I have this: $id = $_GET['id']; $query = "SELECT * FROM table1 WHERE ID=$id"; $result = mysql_query($query); while($row = mysql_fetch_assoc($result)) { $fname = $row['FNAME']; $lname = $row['LNAME']; $moddate = $row['MODDATE']; } except that it's a lot longer. As you can see, I'm naming the variables as the lowercase equivalents of their field name within the table. I'm sure there's an easy way to have it go through each field and assign the value to a variable, I just don't know what it is. I would assume that, since I'm making the variables lowercase, it would be something like: $strtolower($row['FNAME']) = $row['FNAME']; but that doesn't work. Suggestions? Link to comment https://forums.phpfreaks.com/topic/152261-dynamic-variable-assignment-from-query-results/ Share on other sites More sharing options...
premiso Posted April 2, 2009 Share Posted April 2, 2009 extract is what you are looking for, but why not just use the array? It really is not that much more code and is way faster. Link to comment https://forums.phpfreaks.com/topic/152261-dynamic-variable-assignment-from-query-results/#findComment-799564 Share on other sites More sharing options...
taquitosensei Posted April 2, 2009 Share Posted April 2, 2009 This should work. foreach($row as $key=>$value) { ${strtolower($key)}=$value; } Link to comment https://forums.phpfreaks.com/topic/152261-dynamic-variable-assignment-from-query-results/#findComment-799567 Share on other sites More sharing options...
PFMaBiSmAd Posted April 2, 2009 Share Posted April 2, 2009 Variable variables are 3 times slower than using an array. Link to comment https://forums.phpfreaks.com/topic/152261-dynamic-variable-assignment-from-query-results/#findComment-799630 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.