MySQLi导出表到CSV

时间:2016-02-05 09:02:01

标签: php csv mysqli export

我已经多天尝试使用MySQLi从查询中导出.csv中的某些值,但是在导出时出现问题,所有内容都导出到单个列,而不是我需要导出应该像SQL代码一样(我有3个选定的列,我需要.cvs中的3个导出列)。 贝娄你可以找到两个代码:

1)此代码创建数据库,表并插入值:

<?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)此代码用于导出.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();
?>

我正在使用这个XAMP版本:

  

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

     

数据库客户端版本:libmysql - mysqlnd 5.0.12-dev - 20150407 - $ Id:7e72f9690b1498a1bead7a637c33a831c0d2f655 $

     

PHP扩展:mysqli文档

     

PHP版本:7.0.1

这个版本为MySQL代码带来了一些问题,这就是为什么我更喜欢MySQLi中的代码。 非常感谢你!

1 个答案:

答案 0 :(得分:5)

根据新信息,我将此作为解决方案。

<?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;
}


?>