简体   繁体   English

将MySQL结果存储在关联数组中

[英]Store MySQL result in associative array

Hi I am trying to store MySQL result into a global array 嗨,我正在尝试将MySQL结果存储到全局数组中

class db
{
 function CustomLoad($table_name,$Fields)
  {
     global $_MYSQL_DATA;

     $_MYSQL_DATA=array();

     $qry = mysql_query("SELECT * FROM $table_name") or die(mysql_error());
     while($row = mysql_fetch_assoc($qry))
     {
       foreach($Fields as $r=>$key)
       {

        $_MYSQL_DATA[$r] = $row[$r];
       }

     }

   }
}

I am calling like this 我这样打

$dbObj = new db();
$fields = array("FIELD_1"=>"FIELD 1","FIELD_2"=>"FIELD 2","FIELD_3"=>"FIELD  3","FIELD_4"=>"FIELD 4");
$dbObj->CustomLoad("registrations",$fields);

print_r($_MYSQL_DATA);

The problem is I am getting the last result only. 问题是我只能得到最后的结果。 like Array ( [FIELD_1] => A [FIELD_2] => B [FIELD_3] => C [FIELD_4]=> D ) Array ( [FIELD_1] => A [FIELD_2] => B [FIELD_3] => C [FIELD_4]=> D )

Just use the following: 只需使用以下内容:

 $_MYSQL_DATA = array(); // you should declare your variables, even if it's not mandatory
 while($row = mysql_fetch_assoc($qry)) // USE PDO or MySQLi !!!!!
 {
    $_MYSQL_DATA[] = $row;
 }

Note 注意

The [] operator generates the smallest, positive, numeric key that is not used in your array. []运算符生成数组中未使用的最小的正数字键。

Examples: 例子:

$array = array(0 => 'b', 1 => 'a');
$array[] = 'c'; // will place it in $array[2]

$array = array();
$array[] = 'a'; // will place in $array[0]

And now ... the rant about PDO / MySQLi (because I have to say it :P). 现在 ...关于PDO / MySQLi的咆哮(因为我必须说:P)。

MySQL is officially deprecated since PHP 5.5, and it will no longer be maintained. 自PHP 5.5起正式弃用MySQL,它将不再维护。 You should consider porting your code to either MySQLi or PDO. 您应该考虑将代码移植到MySQLi或PDO。

in foreach there should be $row not $Field. 在foreach中应该有$ row而不是$ Field。 Also run a counter 还跑柜台

$i=0;       
while($row = mysql_fetch_assoc($qry))
{
    foreach($row as $r=>$key)
    {
        $_MYSQL_DATA[$i][$r] = $key;
    }
    $i++;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM