Export query to excel file

I have an advanced search option for the user, where they can build the query up and display the results.

The user then has the option to export those results to an exe file.

The operation of sending the query over and populating the exe file works, but what I’m having trouble with is the actual query that is generated to populate the exe file with the search that is being carried out.

<?php
$queryIsValid = true;
if ($contractLike == "CSF" or $contractLike == "ADM") {
$query = "WITH LIMIT AS ( SELECT *, ROW_NUMBER() OVER (ORDER BY ID) AS 'RowNumber' FROM Intranet WHERE {limit clause})  
select COUNT(*) from LIMIT WHERE {limit clause}";
$queryContracts = "WITH LIMIT AS ( SELECT *, ROW_NUMBER() OVER (ORDER BY ID) AS 'RowNumber'   FROM Intranet WHERE {limit clause})  
select * from LIMIT WHERE {limit clause}";

$limitClause  = "";

if (isset($_POST['advrows'])) {
for ($i = 0; $i < sizeof($_POST['field_names']); $i++) {
    if (strlen(trim($_POST['field_names'][$i])) !== 0 && strlen(trim($_POST['operator'][$i])) !== 0)
    //&& strlen(trim($_POST['keyword'][$i])) !== 0)
        {
        if (($_POST['field_names'][$i]) && ($_POST['operator'][$i])) {
            $field_name = ($_POST['field_names'][$i]);
            $operator   = ($_POST['operator'][$i]);
            $keyword    = ($_POST['keyword'][$i]);
            
            if ($i === 0) {
                if ($operator == "like") {
                    $limitClause .= " " . $field_name . " " . $operator . " '" . $keyword . "%'"; // updated
                } else {
                    $limitClause .= " " . $field_name . " " . $operator . " '" . $keyword . "'"; // updated
                }
            } else {
                if ($operator == "like") {
                    $limitClause .= " AND " . $field_name . " " . $operator . " '" . $keyword . "%'"; // updated
                } else {
                    $limitClause .= " AND " . $field_name . " " . $operator . " '" . $keyword . "'"; // updated
                }				
            }
        } else {
            $queryIsValid = false;
            echo "required information missing or is invalid - query was not executed";
            break;
        }
    }
  }

  $_SESSION['limitClause'] = $limitClause; // added this line

  } else { 
    if (isset($_SESSION['limitClause'])) { 
        $limitClause = $_SESSION['limitClause']; 
    } 
 }  


 if ($queryIsValid) 
 {
 $query = str_replace('{limit clause}', $limitClause, $query); // added this line
 //var_dump ($query);
 $queryContracts = str_replace('{limit clause}', $limitClause, $queryContracts); // added this line 
 var_dump ($queryContracts);
 $_SESSION['limitClauseAdv'] = $query;

That above gathers all the info from the query builder, then via the $_SESSION passes it over to be grabbed and used by the code below

 $query = $_SESSION['limitClauseAdv'];

 function cleanData(&$str)
 {
 if($str == 't') $str = 'TRUE';
 if($str == 'f') $str = 'FALSE';
 if(preg_match("/^0/", $str) || preg_match("/^\+?\d{8,}$/", $str) || preg_match("/^\d{4}.\d{1,2}.\d{1,2}/", $str)) {
  $str = "'$str";
 }
 if(strstr($str, '"')) $str = '"' . str_replace('"', '""', $str) . '"';
 $str = mb_convert_encoding($str, 'UTF-16LE', 'UTF-8');
 }

 // filename for download
 $filename = "website_data_" . date('Ymd') . ".csv";

  header("Content-Disposition: attachment; filename=\"$filename\"");
  header("Content-Type: text/csv; charset=UTF-16LE");

  $out = fopen("php://output", 'w');

  $flag = false;

  $result = sqlsrv_query($conn, $query) or die('Query failed!');
  while(false !== ($row = sqlsrv_fetch_array($result, SQLSRV_FETCH_ASSOC))) {

   if(!$flag) {
   // display field/column names as first row
   fputcsv($out, array_keys($row), ',', '"');
   $flag = true;
   }
   //array_walk($row, 'cleanData');
//start
foreach ($row as $key => $value)
	{ 
   if ($value instanceof DateTime) 
	{ 
   $row[$key] = date_format($value, 'd/m/y'); 
	}
    }
//end
$row = str_replace("&#44;", ",", $row);
$row = str_replace("&#46;", ".", $row);
    fputcsv($out, array_values($row), ',', '"');
  }

  fclose($out);
  exit;

?>

This is a query below that I var_dumped to the exe file

string(249) "WITH LIMIT AS ( SELECT * ROW_NUMBER() OVER (ORDER BY ID) AS 'RowNumber' FROM Intranet WHERE  Contract_Status = 'Active' AND Contract_Number like 'MEX%') select COUNT(*) from LIMIT WHERE  Contract_Status = 'Active' AND Contract_Number like 'MEX%'"

And if I turn the var_dump off the only result I get is ‘116’ which is the actual number of contracts being pulled out of the database by the query

I have then tried to use str_replace to help create the query but gave up in the end as you cant cover all eventualities, this is what I was trying below

/*$query = str_replace('WITH LIMIT AS ( ', '', $query); 
$query = str_replace(", ROW_NUMBER() OVER (ORDER BY ID) AS 'RowNumber'", '', $query);
$query = str_replace(", ROW_NUMBER() OVER (ORDER BY Contract_Number) AS 'RowNumber'", '', $query);
$query = str_replace('select * from LIMIT WHERE {limit clause}', '', $query);
$query = str_replace('))', ')', $query);
$query = str_replace('SELECT * FROM Intranet)', 'SELECT * FROM Intranet', $query);
$query = str_replace('SELECT * FROM Intranet WHERE )', 'SELECT * FROM Intranet', $query);
$query = str_replace('select COUNT(*) from LIMIT WHERE', '', $query);
$query = str_replace("%')", "%'", $query);*/

Thank you guys, I think I have got it…

will be back if I’m wrong :confounded:

I think you mean Excel. Which is a xls or a xlsx. An “exe file” is an executable.

1 Like

Sorry yes excel instead of exe :blush:

I do have a problem though when outputting to excel using the code below, as I have a few fields that are ID’s in the database but what I need is the name associated with that value to show instead of the ID from a table called Group.

So in the code below where can I change the value of a field by using its value which is an ID to then go to that table and instead show the name associated with the value, before printing it all out in the excel file.

$query = $_SESSION['limitClauseAdv'];
function cleanData(&$str)
{
if($str == 't') $str = 'TRUE';
if($str == 'f') $str = 'FALSE';
if(preg_match("/^0/", $str) || preg_match("/^\+?\d{8,}$/", $str) || preg_match("/^\d{4}.\d{1,2}.\d{1,2}/", $str)) {
  $str = "'$str";
}
if(strstr($str, '"')) $str = '"' . str_replace('"', '""', $str) . '"';
$str = mb_convert_encoding($str, 'UTF-16LE', 'UTF-8');
}

// filename for download
$filename = "website_data_" . date('Ymd') . ".csv";

header("Content-Disposition: attachment; filename=\"$filename\"");
header("Content-Type: text/csv; charset=UTF-16LE");

$out = fopen("php://output", 'w');

$flag = false;

$result = sqlsrv_query($conn, $query) or die('Query failed!');
while(false !== ($row = sqlsrv_fetch_array($result, SQLSRV_FETCH_ASSOC))) {

 if(!$flag) {
  // display field/column names as first row
  fputcsv($out, array_keys($row), ',', '"');
  $flag = true;
 }
 //array_walk($row, 'cleanData');
//start
foreach ($row as $key => $value)
	{ 
 if ($value instanceof DateTime) 
	{ 
 $row[$key] = date_format($value, 'd/m/y'); 
	}
  }
//end
$row = str_replace("&#44;", ",", $row);
$row = str_replace("&#46;", ".", $row);
 fputcsv($out, array_values($row), ',', '"');
 }

fclose($out);
exit;

Maybe it doesn’t read well, so will have another go.

One of the fields is called Group, and all values in Group are ID’s, which when exported to excel, its no good as what I really need is the name associated with the ID, so what I’m trying to do is interject before it outputs everything to excel, and where its got an ID for a certain field I can grab that ID and with php change it to the name, so that the person reading the excel file, can see the name of the group rather than its ID.

So its not so much the grabbing of the ID and changing it to the name which could be something like below, its where to put it.

if ($field_name == "Group_Name") {
$groupQuery = "SELECT * FROM Groups WHERE (Group_Names='".$keyword."')";
$resb = sqlsrv_query($conn, $groupQuery); 
while ($resultb = sqlsrv_fetch_array($resb, SQLSRV_FETCH_ASSOC)) { 
$keyword = $resultb["Group_Names"];
} }

Will be different to above, but that’s the sort of idea of what I need to do, but just don’t know where to interject in the code to make the change before its displayed in the excel file.

Or is it possible to make the change way before this at the point where the select query is run as below.

 $queryb = "SELECT *, ROW_NUMBER() OVER (ORDER BY ID) AS 'RowNumber' FROM Intranet WHERE {limit clause}";

This is a part of the code that creates the query before passing it over via a session to the export to excel bit

Ye this is a very difficult one, I still cant work it out.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.