to create and load the csv file from mysqli query (using object oriented) I think this will help.
This is a class that connects to the database, and the functions will do what you want using mysqli and PHP. In this case, calling this class (require or include), just use the downloadCsv () function.
As an example, this will be the file "class.php":
<?php class DB{ private $con; //this constructor connects with the database public function __construct(){ $this->con = new mysqli("Your_Host","Your_User","Your_Pass","Your_DatabaseName"); if($this->con->connect_errno > 0){ die('There was a problem [' . $con->connect_error . ']'); } } //create the function that will download a csv file from a mysqli query public function downloadCsv(){ $count = 0; $header = ""; $data = ""; //query $result = $this->con->query("SELECT * FROM Your_TableName"); //count fields $count = $result->field_count; //columns names $names = $result->fetch_fields(); //put column names into header foreach($names as $value) { $header .= $value->name.";"; } } //put rows from your query while($row = $result->fetch_row()) { $line = ''; foreach($row as $value) { if(!isset($value) || $value == "") { $value = ";"; //in this case, ";" separates columns } else { $value = str_replace('"', '""', $value); $value = '"' . $value . '"' . ";"; //if you change the separator before, change this ";" too } $line .= $value; } //end foreach $data .= trim($line)."\n"; } //end while //avoiding problems with data that includes "\r" $data = str_replace("\r", "", $data); //if empty query if ($data == "") { $data = "\nno matching records found\n"; } $count = $result->field_count; //Download csv file header("Content-type: application/octet-stream"); header("Content-Disposition: attachment; filename=FILENAME.csv"); header("Pragma: no-cache"); header("Expires: 0"); echo $header."\n".$data."\n"; } ?>
After creating the "class.php" file in this example, use this function in the "download.php" file:
<?php //call the "class.php" file require_once 'class.php'; //instantiate DB class $export = new DB(); //call function $export->downloadCsv(); ?>
After downloading, open the file using MS Excel.
Hope this helps you, I think I wrote it well, I didn’t like the text box and code box.
source share