提取行的MySQL的领域到PHP变量和数组 [英] Extract MySQL fields of row into PHP variables and array

查看:168
本文介绍了提取行的MySQL的领域到PHP变量和数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在它(40 +字段)一大堆字段和记录表。

我要用我的MySQL结果像这样:

 < PHP
 $ FIELD1 = $行[field1的'];
 $域2 = $行['字段2'];
 $ FIELD3 = $行['FIELD3'];
?>

正如你所见,变量名是相同的字段名。

我怎么能做到这一点的所有领域,而不必键入他们所有了呢?会当我添加更多的字段真正真棒!

我知道关于评估的功能,但我不知道如何在这种情况下使用它。

另外,我怎么能生成结果的阵列?像这样:

 < PHP
  $ ARR =阵列(
           字段1'=> $行['字段1']
               );
?>


解决方案

您可以使用的提取物()

 提取物($行);

然而,采取非常谨慎,你不污染具有这种功能的命名空间。假设你已经有一个名为 $汽车变量,你在你的数据库名为有一个字段。你可能会不知不觉地覆盖现有的变数!

有可能会更安全,那么,使用方法:

 提取物($行,EXTR_SKIP); //不提取已在命名空间中的变量

编辑:在问候你的编辑,你并不需要为结果...您的$ row数组的结果创建一个数组。如果您构建阵列作为您的编辑, $改编['字段1'] = $行['字段1'] ,那么为什么不绕过此阵的建设完全与只需使用原始的 $行

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, however 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?

这篇关于提取行的MySQL的领域到PHP变量和数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆