将SQL输出存储在数组中

时间:2014-03-10 13:26:08

标签: php mysql arrays

我正在尝试将SQL输出提取到数组中。我有以下代码。

require 'connect.inc.php';

$query = "
SELECT  `OS_NoSpecies`
     ,  `OS_ShWeiner` 
     ,  `OS_NoTropSpec`
     ,  `OS_NoTropGen` 
     ,  `OS_PropDetr` 
     , `OS_PropBenthic`
     ,  `OS_PropEstSpawn` 
  FROM bmoffshore AS b 
     , boundedmetric AS bmc
 WHERE b.BM_Code = bmc.BM_Code
   AND bmc.bm_year =  '2013' 
   AND bmc.bm_season = 'Summer' 
";

if ($query_run = mysql_query($query)) {

while ($query_row = mysql_fetch_assoc($query_run)) {
    $OS_NoSpecies = $query_row['OS_NoSpecies'];
    $OS_ShWeiner = $query_row['OS_ShWeiner'];
    $OS_NoTropSpec = $query_row['OS_NoTropSpec'];
    $OS_NoTropGen = $query_row['OS_NoTropGen'];
    $OS_PropDetr = $query_row['OS_PropDetr'];
    $OS_PropBenthic = $query_row['OS_PropBenthic'];
    $OS_PropEstSpawn = $query_row['OS_PropEstSpawn'];       

echo $OS_NoSpecies. ' '.$OS_ShWeiner. ' '.$OS_NoTropSpec. ' '.$OS_NoTropGen. ' '.$OS_PropDetr. ' '.$OS_PropBenthic.' '.$OS_PropEstSpawn.'<br>';     
}
} else {
    echo mysql_error();
}

基本上,SQL输出如下(4行和7列):

1 2 3 4 5 6 7
2 4 5 2 8 4 6 
6 9 4 9 2 4 5
2 0 9 5 9 6 7

但我实际上想要输出的是每行一个数组:例如:

1st array (array1) containg all row values of  1st row
2nd array (array2) containg all row values of  2nd row
3rd array (array3) containg all row values of  3rd row
4th array (array4) containg all row values of  4th row

我会感谢你的帮助。

1 个答案:

答案 0 :(得分:0)

我刚刚做的是,创建了一个数组变量,并在每次迭代时都将值输入到它中,不确定这是否是您期望的最终结果数组

if ($query_run = mysql_query($query)) {
    $resultArray = array();
    while ($query_row = mysql_fetch_assoc($query_run)) {
        $resultArray[] = $query_row;
    }
}

要检查您应该使用var_dump($query_row);var_dump($resultArray);

的值