Reputation: 135
When retrieving values from a MySQL table using PHP, how can I efficiently define a set of variables based on the names of the fields in the MySQL table?
In the past I have been able to do something along the following lines:
while ($row = mysql_fetch_array ($result, MYSQL_ASSOC)) {
explode ($row);
...
}
And this has defined a load of variables with the same names as the field names in my table.
I cannot for the life of me remember what the explode ($row)
bit was though. Thanks.
Upvotes: 0
Views: 754
Reputation: 270609
You're probably thinking of the list()
function.
while ($row = mysql_fetch_array ($result, MYSQL_ASSOC)) {
list($col1, $col2, $col3) = $row;
...
}
// Or more concise:
while (list($col1, $col2, $col3) = mysql_fetch_array ($result, MYSQL_ASSOC)) {
echo $col1;
echo $col2;
...
}
However, I would probably not use list()
. I'd much prefer to access the columns directly from the associative array as $row['col1'], $row['col2'], $row['col3']
so as not to litter the global namespace with short-lived variables.
Upvotes: 1
Reputation: 168655
The results of a mysql_fetch_array
are delivered into an associative array.
There are a couple of ways to convert the variables in an associative array into simple variables. The most common way is to use the list()
function. Another is the extract()
function.
However, I would urge you to rather just stick with using the associative array that you are given intially.
If you read the manual page for extract()
, you'll note that they make a point of warning about it being a potential security risk. Its use is generally discouraged (although it isn't formally deprecated at this point).
Using list()
is more common, and does not represent the same risk as extract()
, but is still unnecessary in most cases.
Hope that helps.
Upvotes: 2