Converting row attributes to variables

When you read a row from your dataset and want to work with it, like building table rows, it can be hard to write, debug and maintain your code using the conventional syntax that requires you to move in and out of a quoted string, inserting elements from the row array like this;

while ($row = mysql_fetch_assoc($result)) {
// work with the data from your row
echo "<tr><td>".row['name']."</td><td>".row['address']."</td></tr>";

It's a lot easier to do this if you convert your row elements to simple variables which can be placed directly in the quoted string, like this;

[sourcecode language="php"]
while ($row = mysql_fetch_assoc($result)) {
// create a variable for each attribute
foreach($row as $var => $value){
$$var = $value;

// now work with the data from your row
echo "

$name $address


Your variables are created with the name of the table attribute, thus $row['address'] becomes $address.

The benefits of this second approach would far outweigh the processing cost of converting the row to simple variables unless you're working with a very high volume site where processor cycles are a significant issue.  In that case, this simplified method would serve you well during the development phase, switching to row elements just before final testing.

About Editor