将MySQL查询保存到两个数组
I'm sure this is simple for someone else, but it escapes me. I have a function that generates a .csv file based on a query input from an internal website. The problem is, for speed purposes, I want to run 1 query to save to two different arrays. One of which I can pass to a function, the other to use for printing a table. I've tried to pass the same $result var to the function. It seems to strip the data once sent through function? I need some help.
code for function:
function save_to_csv($result1, $filename, $attachment = false, $headers = true) {
if($attachment) {
// send response headers to the browser
header( 'Content-Type: text/csv' );
header( 'Content-Disposition: attachment;filename='.$filename);
$fp = fopen('php://output', 'w');
} else {
$fp = fopen($filename, 'w');
}
$result1 = mysql_query($query1) or die( mysql_error() );
if($headers) {
// output header row (if at least one row exists)
$row = mysql_fetch_assoc($result1);
if($row) {
fputcsv($fp, array_keys($row));
// reset pointer back to beginning
mysql_data_seek($result1, 0);
}
}
while($row = mysql_fetch_assoc($result1)) {
fputcsv($fp, $row);
}
fclose($fp);
}
I've tried setting second array like so
$csv_result = array();
also tried
$csv_result = $result = mysql_query($query);
I'm assuming it's something here, but I just cant see it.
我确信这对其他人来说很简单,但它逃脱了我。 我有一个函数可以根据内部网站的查询输入生成.csv文件。 问题是,出于速度目的,我想运行1个查询以保存到两个不同的数组。 其中一个我可以传递给一个函数,另一个用于打印一个表。 我试图将相同的$ result var传递给函数。 它似乎通过函数发送数据? 我需要一些帮助。 p>
函数代码: p>
function save_to_csv($ result1,$ filename,$ attachment = false,$ headers = true){\ n if($ attachment){
//将响应头发送到浏览器
标题('Content-Type:text / csv');
标题('Content-Disposition:attachment; filename ='。$ filename) ;
$ fp = fopen('php:// output','w');
} else {
$ fp = fopen($ filename,'w');
}
$ result1 = mysql_query($ query1)或die(mysql_error());
if($ headers){
//输出标题行(如果至少存在一行)
$ row = mysql_fetch_assoc($ result1);
if($ row){
fputcsv($ fp,array_keys($ row));
//将指针重置回开头
mysql_data_seek($ result1,0);
}
}
\ n while($ row = mysql_fetch_assoc($ result1)){
fputcsv($ fp,$ row);
}
fclose($ fp);
}
code> pre>
我尝试过像这样设置第二个数组 p>
$ csv_result = arra Y();
也试过
$ csv_result = $ result = mysql_query($ query);
code> pre>
我假设它在这里,但我无法看到它。 p>
div>
There's nothing in this code that demonstrates why you need two separate arrays. After the line where you set $result1
, you can simply do the following for the exact same effect:
$row = mysql_fetch_assoc($result1);
if ($row) {
if ($headers) {
fputcsv($fp, array_keys($row));
}
fputcsv($fp, $row);
}
The variable $row
hasn't been modified, and is still equal to the data retrieved from $query1
. There's really no need to make a duplicate array unless one of them is going to be modified. However, if you want to make a copy of the data at any point, you can just use:
$new_copy = $row;