Search code examples
phpopencsv

Multiple CSV File Creation in PHP


I have a code below

<?php  
    /* Error display */
    error_reporting(E_ALL);
    ini_set('display_errors', 1);
    ini_set('memory_limit', '512M');

    /* Requires */
    require 'conn.php';

    /* Parameters (DIM) */
    $param_customer                = $_POST['param_customer'];
    $param_user                    = $_POST['param_user'];

    /* Others */
    $param_email    = $_POST['email'];
    $file_dump_area = "../general_sync/";

    /* Array */
    $jsonData     = array();
    $arr_result   = array();

    /******************************** Download customer      *********************************/
    $cur_filename = $file_dump_area . removeCharEmail($param_email)  . "_" . $param_customer . ".csv";
    $cur_file     = fopen($cur_filename, "w");
    $cur_sql      = "CALL android_getCustomer('" .$param_email. "')";
    $cur_result   = mysqli_query($con,$cur_sql);

    if ($cur_file && $cur_result) {
        while ($row = $cur_result->fetch_array(MYSQLI_NUM)) {
            fputcsv($cur_file, array_values($row));
        }
        array_push($arr_result, array('done_process' => "done_cus"));
    }
    fclose($cur_file);

    /******************************** Download user          *********************************/
    $cur_filename = $file_dump_area . removeCharEmail($param_email)  . "_" . $param_customer . "1.csv";
    $cur_file     = fopen($cur_filename, "w");
    $cur_sql      = "CALL android_getCustomer('" .$param_email. "')";
    $cur_result   = mysqli_query($con,$cur_sql);

    if ($cur_file && $cur_result) {
        while ($row = $cur_result->fetch_array(MYSQLI_NUM)) {
            fputcsv($cur_file, array_values($row));
        }
        array_push($arr_result, array('done_process' => "done_user"));
    }
    fclose($cur_file);


    $jsonData = array("received"=>$arr_result);
    echo json_encode($jsonData,JSON_PRETTY_PRINT);

    function removeCharEmail($val) {
        $new_val1 = str_replace(".", "", $val);
        $new_val2 = str_replace("@", "", $new_val1);
        return $new_val2;
    }
?>

The target output of that code is to create 2 csv which is it does but the problem is the 2nd csv has no data although the query shows some it does not write. I tried to copy the 1st line of codes. it does create the file but it didnt write

Whats the problem?

Updated with help of Mr. Barmar

i got this error Commands out of sync; you can't run this command now


Solution

  • The stored procedure is apparently returning two result sets. You need to fetch the next result set before you can start another query. Add:

    $cur_result->close();
    $con->next_result();
    

    After each loop that fetches the results. See https://stackoverflow.com/a/14561639/1491895 for more details.