Skip to content

Instantly share code, notes, and snippets.

@Stoffo
Last active August 29, 2015 14:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Stoffo/cd0083fd7698a70dcb1e to your computer and use it in GitHub Desktop.
Save Stoffo/cd0083fd7698a70dcb1e to your computer and use it in GitHub Desktop.
import a CSV file easily with this file
#!/usr/bin/php
<?php
error_reporting(0);
$server = "localhost";
$port = 3306;
$username = "csv_test";
$password = "test";
$db = "test_db";
$table_name = "test";
//--------------------------------------------------------------------
$admin_address = "admin@example.de";
$from_name = "CSV Importer";
$from_mail = "noreply@example.de";
// Wenn true, werden auch Mails bei Success geschickt:
$mail = true;
//--------------------------------------------------------------------
$error = null;
$time_start = microtime(true);
$mysqli = new mysqli($server, $username, $password, $db, $port);
if ($mysqli->ping()) {
$mysqli->set_charset("utf8");
if (!$mysqli->query("TRUNCATE `{$table_name}`;")) {
$error .= "Error while doing Query:\n\n".$mysqli->error."\n";
}
//Daten direkt aus der CSV in die DB schreiben:
//@ignore bedeutet, dass eine Spalte der CSV übersprungen wird.
if (!$mysqli->query("
LOAD DATA LOCAL INFILE '/root/bin/tmp/tchibo.csv'
INTO TABLE `$table_name`
FIELDS TERMINATED BY ';'
OPTIONALLY ENCLOSED BY '\"'
LINES TERMINATED BY '\r\n'
IGNORE 1 LINES
(@ignore,
title,
@ignore,
@price_csv,
@ignore,
@deeplink_csv,
@ignore,
category,
@ignore,
@ignore,
img_url,
@ignore,
@week_csv,
@ignore,
@ignore,
@ignore,
@ignore,
@ignore)
SET
price = REPLACE(@price_csv, 'EUR',''),
deeplink = SUBSTRING(@deeplink_csv, 249),
start_week = REPLACE(@week_csv, 'KW',''),
start_week = SUBSTRING_INDEX(start_week, '/', 1)
")
) {
$error .= "Error while doing Query:\n\n".$mysqli->error."\n";
}
} else {
$error = "Error: ".$mysqli->error." (Server down?)";
}
$time_end = microtime(true);
$exec_time = round($time_end - $time_start, 2)." Seconds";
$date = date("d.m.Y - H:i:s", time());
// Mail-Versand bei Fehler:
if ($error != null) {
$mail_topic = "Error while processing csv file";
$mail_text = wordwrap($error."\n\n Duration of Execution: ".$exec_time."\n\n".$date);
$param = "From: $from_name <$from_mail>\n";
mail($admin_address, $mail_topic, $mail_text, $param);
exit(0);
} // Mail-Versand bei Erfolg
elseif ($mail == true && $error == null) {
$mail_topic = "Successfully imported csv file";
$mail_text = wordwrap("Duration of Execution: ".$exec_time."\n\n".$date);
$param = "From: $from_name <$from_mail>\n";
mail($admin_address, $mail_topic, $mail_text, $param);
exit(1);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment