create a mySQL table from the field headings line of a CSV file

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • chabrenas
    New Member
    • Dec 2007
    • 1

    create a mySQL table from the field headings line of a CSV file

    What I'm looking for is a lazy man's way to define a table structure, using the table headings row in a CSV file. I'd be happy to start with all fields being VARCHAR(50) or some such default, and then making appropriate changes via PHPmyAdmin later.

    The reason for being this lazy is the number of fields that I need to define - the CSV file is downloaded from a hotel booking affiliate, and contains every conceivable detail about the hotels. If they were also using mySQL, I could have asked if they'd provide a dump instead of a CSV file...

    Anyone have any bright ideas?
  • ronverdonk
    Recognized Expert Specialist
    • Jul 2006
    • 4259

    #2
    As follows (maybe a bit late):
    [php]<?php
    $handle = fopen("test.csv ", "r");
    // Read first (headers) record only)
    $data = fgetcsv($handle , 1000, ",");
    $sql= 'CREATE TABLE table_name (';
    for($i=0;$i<cou nt($data); $i++) {
    $sql .= $data[$i].' VARCHAR(50), ';
    }
    $sql .= ')';
    echo $sql;
    fclose($handle) ;
    ?> [/php]Ronald

    Comment

    • Gerald Ekosso
      New Member
      • Sep 2010
      • 1

      #3
      Adding to the code

      There is a small problem when you try to run the resulting query in MYSQL. That is because there is an extra comma "," resulting from the generated SQL. I got around it by adding one line more. Code below:

      <?php
      $handle = fopen("Master_G erald.csv", "r");
      // Read first (headers) record only)
      $data = fgetcsv($handle , 1000, ",");
      $sql= 'CREATE TABLE table_name (';
      for($i=0;$i<cou nt($data); $i++) {
      $sql .= $data[$i].' VARCHAR(50), ';
      }
      //The line below gets rid of the comma
      $sql = substr($sql,0,s trlen($sql)-2);
      $sql .= ')';
      echo $sql;
      fclose($handle) ;
      ?>

      Comment

      • dkdenni7
        New Member
        • Mar 2017
        • 1

        #4
        hi in this by default varchar , how i change data according to data ....?????

        Comment

        Working...