I have a table with a whole bunch of fields and records in it (40+fields).
I use my MySQL result like so:
<?php
$field1 = $row['field1'];
$field2 = $row['field2'];
$field3 = $row['field3'];
?>
As you see, the variable name is the same as the field name.
How can I do this for all fields, without having to type em all out? Would be really awesome for when I add more fields!
I know about the eval
function, how开发者_开发知识库ever I am not sure of how to use it in this case.
Also, how can I generate an array with the results? Like so:
<?php
$arr = array(
'field1'=>$row['field1']
);
?>
You can use extract():
extract($row);
However, take great care you don't pollute your namespace with this function. Say you already have a variable named $car
, and you have a field in your database called car
. You could be unwittingly overwriting your existing variables!
It may be safer, then, to use:
extract($row, EXTR_SKIP); // don't extract variables that already exist in the namespace
EDIT: In regards to your edit, you don't need to create an array for the results... your $row array is the result. If you construct the array as in your edit, $arr['field1'] = $row['field1']
, so why not bypass the construction of this array altogether and just use the original $row
?
The extract()
function does exactly this:
extract($row);
By default it will override any existing variable (e.g. if you already have a field1
variable, it will override it). You can disable this by passing EXTR_SKIP as second parameter:
extract($row, EXTR_SKIP);
Or you can prefix all variables:
extract($riw, EXTR_PREFIX_ALL, 'row');
Also, how can I generate an array with the results?
$arr = $row;
精彩评论