CSV. From MySQL to 'csv'. From 'csv' to MySQL
This script converts table data to 'csv' file. You can recreate table from 'csv' file
in another computer.
<?php
// connect to database
require_once '../db_config.php';
$conn = new mysqli ( $dbhost, $dbuser, $dbpass, 'olimrefdb' );
if ($conn->connect_errno) die ( 'no db connection' );
$tableToConvert = 'mdata';
$csvFileName = $tableToConvert . '_' . date ( "Ymd" );//will contain 'csv' data
// -----------------------------MySQL table to CSV--------------------------
$tableSchema = $conn->query ( "SHOW CREATE TABLE $tableToConvert" )->fetch_assoc ();
$result = $conn->query ( "SELECT * FROM $tableToConvert" );
$handle = fopen ( $csvFileName.'.csv', 'w' );//to store 'csv' data file
$handle_schema = fopen ( $csvFileName.'_schema.csv', 'w' );//to store table schema
fputcsv ( $handle_schema, $tableSchema );
while ( $row = $result->fetch_assoc () ) {
fputcsv ( $handle, $row );
}
fclose ( $handle );
fclose ( $handle_schema );
// -----------------------------CSV to MySQL table--------------------------
$handle = fopen ( $csvFileName.'.csv', 'r' );//open 'csv' data file
$handle_schema = fopen ( $csvFileName.'_schema.csv', 'r' );//open table schema
$tableSchema = fgetcsv ( $handle_schema );
$newTableName = "$tableSchema[0]_" . date ( "Ymd" );
// change table name in schema
$tableSchema [1] = preg_replace ( "/$tableSchema[0]/", $newTableName, $tableSchema [1], 1 );
$conn->query ( "DROP TABLE IF EXISTS $newTableName" );
$conn->query ( $tableSchema [1] );//CREATE TABLE
// $conn->query ( "CREATE TABLE $newTableName LIKE $tableToConvert");//the same, but without using schema
while ( $row = fgetcsv ( $handle ) ) {
$data = implode ( "','", $row ); //convert array to string
if ($conn->query ( "INSERT INTO $newTableName values('$data')" )) {
} else {
echo '<span style="color:red">Problem:</span> ' . $data . '<br>';
var_dump ( $conn->error_list );
fclose ( $handle );
exit ();
}
}
fclose ( $handle );
echo 'Congratulation!!!' . '<br>';