1

I've been trying for many days to export from a query some values in .csv with MySQLi, but I have a problem when the export is made, everything is exporting to a single column, instead I need that the export should make like SQL code (I have 3 selected columns and I need 3 exported columns in .cvs). Bellow you can find two codes:

1) This code creates a data base, table and insert the values:

<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}
// Create database
$sql = "CREATE DATABASE myDB";
if ($conn->query($sql) === TRUE) {
    echo "Database created successfully";
} else {
    echo "Error creating database: " . $conn->error;
}
// Create connection pt a crea tabela
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}
// sql to create table
$sql = "CREATE TABLE MyGuests (
    id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    firstname VARCHAR(30) NOT NULL,
    lastname VARCHAR(30) NOT NULL,
    email VARCHAR(50),
    reg_date TIMESTAMP
)";
if ($conn->query($sql) === TRUE) {
    echo "Table MyGuests created successfully";
} else {
    echo "Error creating table: " . $conn->error;
}
// Create connection pt a insera valori
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}
// Insert value in db
$sql = "INSERT INTO MyGuests (firstname, lastname, email)
    VALUES ('John', 'Doe, Mark', 'john@example.com'),
    ('Mary', 'Moe-Johny', 'mary@example.com'),
    ('Julie', 'Dooley', 'julie@example.com')";
if ($conn->query($sql) === TRUE) {
    echo "New record created successfully";
} else {
    echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>

2) This code is for the export in .csv:

<?php
//header to give the order to the browser
header('Content-Type: text/csv');
header('Content-Disposition: attachment;filename=export.csv');
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT id, firstname, lastname FROM MyGuests";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
    // output data of each row
    while($row = $result->fetch_assoc()) {
        echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " . $row["lastname"]. "<br>";
    }
} else {
    echo "0 results";
}
$conn->close();
?>

I'm using this XAMP version:

Apache/2.4.18 (Win32) OpenSSL/1.0.2e PHP/7.0.1

Database client version: libmysql - mysqlnd 5.0.12-dev - 20150407 - $Id: 7e72f9690b1498a1bead7a637c33a831c0d2f655 $

PHP extension: mysqli Documentation

PHP version: 7.0.1

This version creates some problems for the MySQL code, that's why I prefer the code in MySQLi. Thank you very much!

Alessio Cantarella
  • 4,659
  • 3
  • 21
  • 29
Sterica St
  • 123
  • 1
  • 2
  • 12
  • Can you please point to the line of code where yo think "Comma Separated Values" are written to the file? (Rhetorical question. A simple csv line would look like `34,John Doe` while your code prints something like `id:34 - Name: John Doe
    `. So at the very least you'd have to tell the importing apllication to use `-` as the delimiter; but I doubt that the result is what you want. You might be interested in http://docs.php.net/fputcsv
    – VolkerK Feb 05 '16 at 09:11
  • There has been another user asking how to convert MySQL data into csv files. Take a look here, I am sure this will put you on track: http://stackoverflow.com/questions/125113/php-code-to-convert-a-mysql-query-to-csv – Werner Feb 05 '16 at 09:16
  • In the table are the words witch are delimitated by: , . - ; / – Sterica St Feb 05 '16 at 09:16
  • `In the table are the words witch are delimitated by: , . - ; /` please eleaborate. – VolkerK Feb 05 '16 at 09:34

1 Answers1

5

Based on the new information I have this as the solution.

<?php

// call export function
exportMysqlToCsv('export_csv.csv');


// export csv
function exportMysqlToCsv($filename = 'export_csv.csv')
{

   $conn = dbConnection();
// Check connection
    if ($conn->connect_error) {
        die("Connection failed: " . $conn->connect_error);
    }
    $sql_query = "SELECT id, firstname, lastname FROM MyGuests";

    // Gets the data from the database
    $result = $conn->query($sql_query);

    $f = fopen('php://temp', 'wt');
    $first = true;
    while ($row = $result->fetch_assoc()) {
        if ($first) {
            fputcsv($f, array_keys($row));
            $first = false;
        }
        fputcsv($f, $row);
    } // end while

    $conn->close();

    $size = ftell($f);
    rewind($f);

    header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
    header("Content-Length: $size");
    // Output to browser with appropriate mime type, you choose ;)
    header("Content-type: text/x-csv");
    header("Content-type: text/csv");
    header("Content-type: application/csv");
    header("Content-Disposition: attachment; filename=$filename");
    fpassthru($f);
    exit;

}

// db connection function
function dbConnection(){
    $servername = "localhost";
    $username = "root";
    $password = "";
    $dbname = "myDB";
    // Create connection
    $conn = new mysqli($servername, $username, $password, $dbname);
    return $conn;
}


?>
ArrowHead
  • 555
  • 4
  • 15
  • I am the error: Notice: Trying to get property of non-object in C:\xampp\htdocs\export_csv\export_csv.php on line 19 0 results – Sterica St Feb 05 '16 at 09:22
  • I export everything in one column. You can see here: http://pastie.org/10709704 I want to confirm that the table contains: , . ; - / : – Sterica St Feb 05 '16 at 09:43
  • Actually that is fine, take a look at this example in the attached link, it depends on what program you are using to open the file. The fact is since they are comma separated it can be read as a valid csv by computer programs. You can see if you can add some formatting to it. See this example : [Multiple columns in csv](http://stackoverflow.com/questions/19542975/multiple-columns-in-csv) – ArrowHead Feb 05 '16 at 10:23
  • It's not good. id, firstName and lastName are head table. id->A1; firstname->B1; lastname->C1 – Sterica St Feb 05 '16 at 11:10
  • Well, that is not what your initial post was doing, based on the new info i have redone the function. – ArrowHead Feb 05 '16 at 11:20
  • he code works, but I have another little problem. Regional settings of my PC are not on the US but on Romanian. This means that with the US separation is done by "," and in Romanian by ";" and Excel takes regional settings of the PC. What can I do to code to make separation by ";" ? – Sterica St Feb 05 '16 at 19:35
  • Ok, Mr. ArrowHead, thank you very much for you help, I made a big step. – Sterica St Feb 06 '16 at 08:08