PHP:在函数内创建MYSQL查询

时间:2015-11-02 14:37:07

标签: php mysql

我有一个执行SQL查询的函数,“queryValue”要执行的实际查询稍后会传递。

Function queryCreate($queryValue){
    //DB connection variables
    $host = "";
    $user = "";
    $password = "";
    $database = "";

    //create the connection
    $conn = new mysqli($host, $user, $password, $database);

    if ($conn->connect_error) {
        die('DB Connection error: (' . $conn->connect_error . ') ' . $conn->connection_errorno);
    }
    $query = mysqli_query($conn,$queryValue) or die(mysqli_error($conn));

    if ($result = mysqli_fetch_array($query,MYSQLI_ASSOC)) {
        fputcsv($fh, array_keys($result));
        fputcsv($fh, $result);
        while ($result = mysqli_fetch_array($query,MYSQLI_ASSOC)) {     
            fputcsv($fh, $result);
        }
    }
    return $queryValue;
}

然后我尝试在单独的if语句中分配查询值。下面:

if(isset($_POST["Submit"]) && ($_POST['Weight'] == 'Weight')) {
    $fh = csvCreate("Output Weight Null ".date('m-d-Y-His').".csv");
    $queryValue = queryCreate('SELECT * FROM  `table` WHERE WEIGHT = 0 OR weight IS NULL');
}

我遇到的问题是查询似乎没有传递给函数。有谁能建议我在哪里出错?非常感谢。

csvCreate函数如下所示:

   function csvCreate($filename){
   header("Cache=Control: must-revalidate, post-check=0, pre-check=0");
   header('Content-Description: File Transfer');
   header("Content-type: text/csv");
   header("Content-Disposition: attachment; filename={$filename}");
   header("Expires: 0");
   header("Pragma: public");
   $fh = @fopen( 'php://output', 'w' );
   return $fh;
}

1 个答案:

答案 0 :(得分:3)

问题在于queryCreate()函数中fputcsv()调用的参数。

使用csvCreate()函数在queryCreate()函数之外声明文件处理程序($ fh变量):

$fh = csvCreate("Output Weight Null ".date('m-d-Y-His').".csv");

但是,$ fh不作为参数传递给queryCreate(),也不是$ fh声明为全局变量,而$ fh变量用于在所有fputcsv()调用中引用该文件:

fputcsv($fh, array_keys($result));

在这种情况下,queryCreate()中的$ fh不会引用调用queryCreate()的$ fh变量,但它会创建一个本地$ fh变量(此处为空),因此fputcsv()调用将失败。 csv文件是在csvCreate()中创建的,这与将值放在文件中无关。

最好的解决方案是将$ fh作为参数传递给queryCreate(),或者从queryCreate()调用csvCreate()。在后一种情况下,数据集的名称应作为参数传递。

UPDATE  我们也看一些代码:

//declaration of queryCreate()
Function queryCreate($queryValue, $reportName){ //$reportName is the name of the report
    ...
    //create the csv file, put some parameter checks here as well
    $fh = csvCreate($reportName.date('m-d-Y-His').".csv");
    //and some error handling here
    ...
    //output the contents of the query to the csv file
    if ($result = mysqli_fetch_array($query,MYSQLI_ASSOC)) {
        fputcsv($fh, array_keys($result));
        fputcsv($fh, $result);
        while ($result = mysqli_fetch_array($query,MYSQLI_ASSOC)) {     
            fputcsv($fh, $result);
        }
    }       
    ... //should include closing of the csv file
} //end queryCreate()

...

//call the queryCreate()
if(isset($_POST["Submit"]) && ($_POST['Weight'] == 'Weight')) {
    $queryValue = queryCreate('SELECT * FROM  `table` WHERE WEIGHT = 0 OR weight IS NULL','Output Weight Null ');
}