PHP working with CSV

Quick info on how to import export csv

/**
 * CREATE A TABLE
 *  CREATE TABLE `php_csv`.`users` ( 
 *      `id` INT NOT NULL AUTO_INCREMENT ,
 *      `f_name` VARCHAR(30) NOT NULL ,
 *      `l_name` VARCHAR(30) NOT NULL ,
 *      `age` INT NOT NULL ,
 *      PRIMARY KEY (`id`)
 * ) ENGINE = InnoDB;
 */

class CSV extends mysqli {
    private $state_csv = false;
    public function __construct()
    {
        parent::__construct( HOST, NAME, PASSWORD, DBNAME);
        if ($this->connect_error) {
            echo "Failed to connect to DB: ". $this->connect_error;
        }
    }
    public function import($file)
    {
        $file = fopen($file, 'r');
        while ( $row = fgetcsv($file) ) {
            $value = "'".implode("','", $row)."'";
            $query = "INSERT INTO users(f_name, l_name, age) VALUES($value)";
            // var_dump($query);
            if ( $this->query($query) ) {
                $this->state_csv = true;
            } else {
                $this->state_csv = false;
                echo $this->error;
            }
        }
        echo "Successfull upload";
    } 
    public function export() {
        $this->state_csv = false;
        $query = "SELECT u.f_name, u.l_name, u.age FROM users as u";
        $stmt = $this->query($query);
//$stmt , [current_field] => 0 , [field_count] => 3 , [lengths] =>  , [num_rows] => 8 , [type] => 0
        if ( $stmt->num_rows > 0 ) {
            // $fileName = "data_".uniqid().".csv";
            $fileName = "exportToHere.csv";

            $file = fopen("files/" . $fileName, "w");
            while ( $row = $stmt->fetch_array(MYSQLI_NUM) ) {
                if ( fputcsv( $file, $row) ) {
                    $this->state_csv = true;
                } else {
                    $this->state_csv = false;
                }
            }
            if ( $this->state_csv ) {
                echo "Success exporting";
            } else {
                echo "UnSuccessfull exporting";
            }
            fclose($file);
        } else {
            echo "No rows found";
        }
}

add it to the export function

 // Download link 
        $output = "";
        $columns_total = mysqli_num_fields($stmt);

        // Get the name of the data columns so it can be used in the header row of the export file.
        // Content of the export file is temporarily saved in the variable $output
        for ($i = 0; $i < $columns_total; $i++) { $headings = mysqli_fetch_field_direct($stmt, $i); $output .= '"'.$headings->name.'",';
        }
        $output .= "\n";		
        // The /n is the control code to go to a new line in the export file.
        // Loop through each record in the table and read the data value from each column.
        while ($row = mysqli_fetch_array($stmt)) {
           for ($i = 0; $i < $columns_total; $i++) {
              $output .= '"'.$row["$i"].'",';
           }
           $output .= "\n";
        }
        // Create the export file and name it with the name specified in variable $Filename
        // Also appends the current timestamp (in the format yyyymmddhhmmss) to the filename and give it a .CSV file extension.
        // The timestamp serves as a time reference to identify when the data was exported.
        //File is comma delimited with double-quote used a the text qualifier
        // Once  file is created, download of the file begins automatically (tested on Google Chrome).
        $fileName = "Example_MySQL_Export_"; 
        $time = date("m_d-H_i");
        $fileName .= $time.".csv";
        header('Content-type: application/csv');
        header('Content-Disposition: attachment; filename='.$fileName);
        echo $output;

 

Was this article helpful?

Related Articles

Leave A Comment?