How to get database table header information in a CSV file

I am trying to connect to the database and get the current state of the table and update this information in the csv file, with the code snippet below, I can get information about the data in the csv file, but I can not get the header information from the database table in the csv file.

So my questions are: How to get database table header information in a CSV file?

$config['database'] = 'sakila';
$config['host'] = 'localhost';
$config['username'] = 'root';
$config['password'] = '';

$d = new PDO('mysql:dbname='.$config['database'].';host='.$config['host'], $config['username'], $config['password']);
$query = "SELECT * FROM actor";
$stmt = $d->prepare($query);

// Execute the statement
$stmt->execute();

var_dump($stmt->fetch(PDO::FETCH_ASSOC));

$data = fopen('file.csv', 'w');

while ($row = $stmt->fetch(PDO::FETCH_ASSOC))
{
    echo "Hi";
    // Export every row to a file
    fputcsv($data, $row);
}

The value of the header information:

Vehicle     Build   Model
 car        2009    Toyota
 jeep       2007    Mahindra

So the header information for this will be a car assembly model

Any guidance would be greatly appreciated.

+3
source share
4 answers

$row: array_keys(). , CSV .

======= EDIT =======

<?php

$header = array();

while ($row = $stmt->fetch(PDO::FETCH_ASSOC))
{
    if(empty($header)){ // do it only once!
      $header = array_keys($row); // get the columnnames
      fputcsv($data, $header); // put them in csv
    }

    echo "Hi";
    // Export every row to a file
    fputcsv($data, $row);
}
?>
+12

SHOW COLUMNS FROM, . CSV:

// Do this before adding the rows from the database
$query = "SHOW COLUMNS FROM some_table";
$stmt = $d->prepare($query);
$stmt->execute();
$columns = '';
while ($row = $stmt->fetch(PDO::FETCH_ASSOC))
{
    $columns .= $row['Field'] . ',';
}
$columns = substr($columns, 0, -1);
fputcsv($data, $columns);
+2

mysqldump:

mysqldump -u user -p --fields-terminated-by=',' --tab=/tmp mydatabase mytable

2 /tmp. mytable.sql mytable.txt. sql , txt mytable , .

+1

PDO:: FETCH_ASSOC: , ,

EDIT: ( while lopp)

fputcsv($data, array_keys($stmt->fetch(PDO::FETCH_ASSOC)));

Read about php arrays and associative arrays in particular, and about array functions (such as array_keys). Answers to specific questions cannot replace an understanding of basic concepts such as arrays.

0
source

Source: https://habr.com/ru/post/1738992/


All Articles