使用csv和LOAD DATA INFILE导出和导入多个表

时间:2018-09-03 21:03:02

标签: mysql csv export-to-csv

我有几个表,我想将所有表数据导出到一个csv文件中,然后再使用LOAD DATA INFILE导入mysql。我已经使用以下代码成功导出和导入了一个表(在本例中为media_table):

导出:

$result = $conn->query("SELECT * FROM {$table} WHERE playlist_id='$playlist_id'");
$num_fields = mysqli_num_fields($result);

$headers = array(); 
  for ($i = 0; $i < $num_fields; $i++) {
  $headers[] = mysqli_fetch_field_direct($result, $i)->name;
}

$fp = fopen('php://output', 'w');
if ($fp && $result) {
  header('Content-Type: text/csv');
  header('Content-Disposition: attachment; filename="'.$filename.'.csv"');
  header('Pragma: no-cache');
  header('Expires: 0');
  fputcsv($fp, $headers);
  while ($row = $result->fetch_array(MYSQLI_NUM)) {
    fputcsv($fp, array_values($row), '|', '^');
  }
  die;
}

导入:

$query = <<<eof
  LOAD DATA INFILE '$filename' INTO TABLE {$table}
  FIELDS OPTIONALLY ENCLOSED BY '^'
  TERMINATED BY '|'
  ESCAPED BY ''
  LINES TERMINATED BY '\r\n'
  IGNORE 1 LINES;
eof;

这是表的简化版本(有更多的数据和表,但我希望对如何完成工作有所了解):

$sql = "CREATE TABLE $media_table (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `type` varchar(50) NOT NULL,
  `title` varchar(255) DEFAULT NULL,
  `playlist_id` int(11) NOT NULL,
  PRIMARY KEY (`id`)
) $charset_collate;";

$sql = "CREATE TABLE $path_table (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `path` varchar(500) DEFAULT NULL,
  `def` varchar(50) DEFAULT NULL,
  `media_id` int(11) NOT NULL,
  PRIMARY KEY (`id`),
  INDEX `media_id` (`media_id`),
  CONSTRAINT `mvp_path_ibfk_1` FOREIGN KEY (`media_id`) REFERENCES {$media_table} (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) $charset_collate;";

$sql = "CREATE TABLE $subtitle_table (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `label` varchar(50) NOT NULL,
  `src` varchar(500) NOT NULL,
  `media_id` int(11) NOT NULL,
  PRIMARY KEY (`id`),
  INDEX `media_id` (`media_id`),
  CONSTRAINT `mvp_subtitle_ibfk_1` FOREIGN KEY (`media_id`) REFERENCES {$media_table} (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) $charset_collate;";

是否可以在一个csv中导出多个表?

0 个答案:

没有答案