(mdb to) csv to MySQL

Quick and dirty PHP script to turn a CSV file into a table in a MySQL database. Used for a Drupal project, so I ran it with drush php-script. Couldn't find anything better online. Feel free to use it.

If I need it again some time I will probably make it a bit nicer (I might also make it nicer if you ask me nicely and/or pay me to do it).

In the project I'm using it, I first converted an .mdb file to .csv with mdbtools.

<?php

$handle = fopen("/tmp/test.csv", "r");
$headers = fgetcsv($handle);
$sql = 'CREATE TABLE test_csv (';
foreach ($headers as $field) {
    $field = strtolower($field);
    $sql .= strtolower($field).' VARCHAR(255), ';
}
$sql .= ')';
$sql = str_replace('), )', '))', $sql);
echo $sql;

// db_query('DROP TABLE test_csv');
db_query($sql);

while ($data = fgetcsv($handle)) {
    $sql = 'INSERT INTO test_csv VALUES (';
    foreach ($data as $field) {
        $sql .= '"' . $field . '", ';
    }
    $sql .= ')';
    $sql = str_replace(', )', ')', $sql);
    db_query($sql);
}

Comments

Post new comment

  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd>
  • Lines and paragraphs break automatically.

More information about formatting options

By submitting this form, you accept the Mollom privacy policy.
Creative Commons Public Domain
This Work, (mdb to) csv to MySQL, by Kasper Souren is licensed under a Creative Commons Public Domain license.