在PHP中使用MySQL查询生成数组

时间:2013-01-22 21:04:47

标签: php mysql arrays

很抱歉Q略有重复,但我认为以前的答案现在已经过折旧了(我在PHP 5.3中看到你需要使用MySQLi_fetch_array())

我正在使用jpgraph并尝试从MySQL数据库中提取数据。我有以下代码,它可以提取我需要的数据,当我回显结果时,它会逐个吐出答案,没有问题,但它不会把它放到数组中。

我试图更换一行

$ydata = array(1,2,3,4,5,6,7);


//query
$sql = "SELECT CONCAT( 'Week ', WEEK( TimeofCompletion ) , ' ', YEAR( TimeofCompletion ) ) AS Week, Count( * ) AS VolumeOfAnswers
FROM table01
GROUP BY WEEK( TimeofCompletion ) , YEAR( TimeofCompletion ) 
ORDER BY TimeofCompletion";

$ydata = array();

while($row = mysql_fetch_array($sql)){
// Create a temporary array
 $temp = array();

 $temp[] = "".$row['VolumeOfAnswers']."";
$ydata = '['. implode(', ', $temp) . ']';   
}

有关如何按行将输出输入数组的任何建议吗?

此致 Maudise

1 个答案:

答案 0 :(得分:0)

 $temp[] = "".$row['VolumeOfAnswers'].""; //what this suppose to do?

我假设你想要引用我会在

中添加单引号
 $temp[] = "'".$row['VolumeOfAnswers']."'";

否则你根本不需要双引号,所以我会删除它们。之后,您的数组将保存数据库中的值。

根据documentation mysql_fetch_array 已弃用,您应该使用PDO或MySQLi。但如果您仍想使用它,我建议使用 mysql_fetch_assoc

关于这个问题:

 while($row = mysql_fetch_array($sql)){
  // Create a temporary array
  $temp = array();

  $temp[] = "".$row['VolumeOfAnswers']."";
  //why is this here? should be outside of while loop shouldnt it?
  $ydata = '['. implode(', ', $temp) . ']';   
 }

你的$ ydata总是会被覆盖,只保留 $ temp 数组的最后一个元素。在while循环之外移动$ ydata或使用array_merge($ydata, $temp);