php csv generator不输出文件,多次选择不传递值

时间:2017-01-11 20:38:50

标签: php sql-server-2008 csv

我正在构建一个CSV生成器,它从多个选择框中选择一些区域并循环选中,根据数据库信息为每个项目弹出一个单独的CSV,或者至少它应该是,它会不断弹出用我的标题包含一个PHP文件,然后为我选择的每个项目输入一个未定义的$ filename变量错误,它不会从多个select中传递Area_ID。另一个奇怪的事情(至少据我所见,可能是正常但对我来说似乎很奇怪)是CSVGen函数如果包含在一个单独的文件中,则需要我的数据库连接字符串在函数内部,其中调用它的页面具有我的数据库连接包括目前,打开多达24个新会议而不是使用我已经开设的会议似乎是不切实际的。

这是主页:

<?php
$page_title="CSV Generator";
include("\Include\header.inc");
include("\Include\connect-db.php");
include("\Include\CSVGen.php");

$error="";

$start_date=date("Y-m-d");
$end_date=date("Y-m-d", strtotime("+7 days"));


if(isset($_GET['reg'])) 
{
    $reg=$_GET['reg'];
}

else{
    $reg='1';
}


if($start_date>$end_date){
    $error = 'ERROR: End Date cannot be before Start Date!';
}

if ($error != '')

{

echo '<div class="container">
  <div class="row">
  <div class="alert alert-danger col-md-12">'.$error.'
  </div>
  </div>
  </div>';

}
        $sqlareas="SELECT Area_Name, Region_ID FROM Listings_Areas WHERE region = '$reg'";
        $arearesult= sqlsrv_query($conn, $sqlareas, array(), array("Scrollable"=>"buffered"));
        $areacount = sqlsrv_num_rows($arearesult);


function renderForm($arearesult, $areacount, $start_date, $end_date){
?>

<html>

<head>

</head>

<body>

<div class="container">

<div class="row">
    <form id="form1" name="form1" method="post">
    <div class="col-md-2 col-md-offset-1">

        <p><select name="arealist[]" size="<?php echo $areacount ;?>" multiple="multiple" tabindex="1">

        <?php

        while($areas=sqlsrv_fetch_array($arearesult)){
        echo'<option value="' . $areas['Area_ID'] . '">' . $areas['Area_Name'] . '</option>';
        }
        ?>

        </select>
    </div>

    <div class="col-md-3">   
        <strong>Start Date: </strong> <input type="date" name="start" value="<?php echo $start_date; ?>" />
    </div>
    <div class="col-md-3">  
        <strong> End Date: </strong> <input type="date" name="end" value="<?php echo $end_date; ?>" />
    </div>
    <div class="col-md-2">  
        <input type="submit" name="submit" value="Get CSVs">
    </div>
    </form>

  </div>

</div>

<div class="row">
<?php
}

if (isset($_POST['submit'])){

$start_date=$_POST['start'];
$end_date=$_POST['end'];
$areasselect=$_POST['arealist'];

foreach($areasselect as $selected){
$area_id = $selected;

//echo $area_id . $start . $end;

CSVGEN($area_id, $start_date, $end_date);

}
}

else {renderForm($arearesult, $areacount, $start, $end);}

?>
</div>

这里是CSVGen.php,我最初是独立构建的,用于测试(工作正常),所以有一些注释掉的部分可以从URL中提取变量。

<?php
// connect to db
function CSVGen($area_id, $start_date, $end_date){

include("\Include\connect-db.php");
//if (isset($_GET['area']) && is_numeric($_GET['area']) && $_GET['area'] > 0)

//{ 
//    $area_id = $_GET['area'];
//    $start_date = $_GET['start'];
//    $end_date = $_GET['end'];

// fetch the data
$sql = "SELECT * FROM Listings WHERE area_id ='$area_id' AND date >=convert(datetime, '$start_date') And date <=convert(datetime,'$end_date')";
$results = sqlsrv_query($conn, $sql);
$prev_program = "";
$i=0;
$csv= array();
while($row = sqlsrv_fetch_array($results)) {
        $program=$row['name'];
        $date=$row['date'];
        $start=$row['time_start'];

        $programclean = str_replace("'","''", $program);

        //echo 'area id ' . $area_id . ' / program ' . $program . ' / date ' . $date . ' / start time ' . $start . '<br>';
        if($prev_program!=$program){
        $sql2= "SELECT Area_Name, Region_ID FROM Listings_Areas WHERE Area_ID = '$area_id'";
        $results2= sqlsrv_query($conn, $sql2);
        $row2= sqlsrv_fetch_array($results2);
        $filename=$row2['Area_Name'] . ' Eastlink TV.csv';
        $station_ID = $row2['Region_ID'];
        //echo 'station ID ' . $station_ID . ' / Filename ' . $filename . '<br>';

        $sql3 = "SELECT PID, description, DUR, GENRE, TYPE FROM pid WHERE Title='$programclean'";
        $results3= sqlsrv_query($conn, $sql3);
        $row3=sqlsrv_fetch_array($results3);

        if($row3){

        $PID=$row3['PID'];
        $gendesc=$row3['description'];
        $gendur=$row3['DUR'];
        $genre=$row3['GENRE'];
        $subgenre=$row3['TYPE'];

        //echo '<br>pid ' . $PID . ' / gendesc ' . $gendesc . ' / gen duration ' . $gendur . ' / genre ' . $genre . ' / subgenre ' . $subgenre . '<br>';
        }
        $sql4 = "SELECT EID FROM asdb WHERE airdate='$date' AND PID='$PID'";
        $results4 = sqlsrv_query($conn, $sql4);

        if($rows=sqlsrv_has_rows($results4)==true){
            $row4=sqlsrv_fetch_array($results4);
            $EID=$row4['EID'];

            $sql5 = "SELECT Description, DUR FROM eid WHERE EID='$EID'";
            $results5= sqlsrv_query($conn, $sql5);

            if($rows=sqlsrv_has_rows($results5)==true){
                $row5=sqlsrv_fetch_array($results5);
                $desc=$row5['Description'];
                $dur=$row5['DUR'];
            }
        }
        else{
            $sql6 = "SELECT EID, PID, Description, DUR FROM eid WHERE LIST_Title='$programclean'";
            $results6= sqlsrv_query($conn, $sql6);

            if($rows=sqlsrv_has_rows($results6)==true){
                $row6=sqlsrv_fetch_array($results6);
                $PID=$row6['pid'];
                $desc=$row6['description'];
                $dur=$row6['DUR'];
            }
        }

        if(empty($gendesc)){$gendesc=$program;}
        if(empty($desc)){$desc=$gendesc;}

        if(empty($gendur)){$gendur="30";}
        if(empty($dur)){$dur=$gendur;}

        $start_time=date("H:i", strtotime($start));
        $end_time=date("H:i", strtotime("+".$dur." minutes", strtotime($start)));
        $date= date("m/d/y", strtotime($date));

        $csv[$i]['Station ID']=$station_ID;
        $csv[$i]['Program Start Date']=$date;
        $csv[$i]['Program Start Time']=$start_time;
        $csv[$i]['Program End Time']=$end_time;
        $csv[$i]['Duration']=$dur;
        $csv[$i]['Program Title']=$program;
        $csv[$i]['Program Description (optional)']=$desc;
        $csv[$i]['Category']=$genre;
        $csv[$i]['Sub Category']=$subgenre;
        $csv[$i]['Time Zone?']='Atlantic';
        $csv[$i][]="\r\n";

        }
        $prev_program = $program ;
        unset($gendesc, $desc, $dur, $gendur, $end, $end_time, $start, $start_time);
        $i++;
}


// create a file pointer connected to the output stream
$output = fopen("php://output",'w') or die("Can't open php://output");

// output headers so that the file is downloaded rather than displayed
header('Content-Type: text/csv; charset=utf-8');
header("Content-Disposition: attachment; filename='" . $filename . "'");

// output the column headings
fputcsv($output, array('Station ID', 'Program Start Date', 'Program Start Time', 'Program End Time', 'Duration', 'Program Title', 'Program Description (optional)', 'Category', 'Sub Category', 'Time Zone?' . "\r\n"));

// loop over the rows, outputting them
foreach ($csv as $line) {
                fputcsv($output, $line);
}

fclose($output) or die("Can't close php://output");
}
?>

如果有人能告诉我这里有什么明显的错误,我会很感激,过去几天我一直对此感到沮丧......

编辑:我意识到我的一个明显的错误,这个:

$sqlareas="SELECT Area_Name, Region_ID FROM Listings_Areas WHERE region = '$reg'";

应该是:

$sqlareas="SELECT Area_Name, Region_ID, Area_ID FROM Listings_Areas WHERE region = '$reg'";

现在我只有一个问题就是它用我的头文件随后是所有选定区域的数据而不是每个没有头文件的单独文件来吐出单个CSV(在所选择的第一个区域中正确命名)无法弄清楚为什么它会打印出来。我真的不需要在顶部发送带有导航条代码的CSV ...

1 个答案:

答案 0 :(得分:0)

你所做的是所谓的&#34;条件声明&#34;。

在while循环中是一个if语句,其中创建/赋值变量$ filename(!)。当循环启动并且不满足if条件时,$ filename未定义,因为if-case代码从未执行过。

一旦定义,它将保持其最后一次分配,直到再次满足if条件。它基本上是一个你已编程的分组中断,无论是否有意,但你错过了一个重要的事实:你的数据必须被订购,否则分组中断将无法正常工作。

您应该开始调试代码以了解其工作流程。首先通过初始化变量来删除条件声明。

你应该重新考虑你的编码风格,这种压痕非常难以阅读,特别是因为你把它混合起来......