How to import comma seperated text file to mysql database in php

    This are two ways of doing this first is if file already placed on server then you can give filepath and tablename and run create this file import.php
    <?php
    $connec
    = mysql_connect(<hostname>,  <username>,<password>);
    mysql_select_db(<dbname>, $connec);

    $sql = "LOAD DATA LOCAL INFILE '<filepath>'
                        REPLACE
                        INTO TABLE <tablename>
                        FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '\"'
                        LINES TERMINATED BY '\r\n'
                        IGNORE 1 LINES
                        "
    ;
    mysql_query($sql);
    if(
    mysql_error()) {
        echo(
    mysql_error());
    } else {
        echo(
    "Import sucessfull data imported to mysql table.");
    }
    ?>

    Seocnd Way to upload and Import


    upload.php
        <form action="import.php" method="post" enctype="multipart/form-data">
    Upload Text File: <input type="file" name="file" />
    <input type="submit" name="Submit" value="Submit" />
    </form>
    import.php
    <?php
    $connec
    = mysql_connect(<hostname>,  <username>,<password>);
    mysql_select_db(<dbname>, $connec);
    if (
    $_FILES["file"]["type"] == "text/plain")
      {
      if (
    $_FILES["file"]["error"] > 0)
        {
        echo
    "Return Code: " . $_FILES["file"]["error"] . "<br />";
        }
      else
        {
      
    $sql = "LOAD DATA LOCAL INFILE '".$_FILES["file"]["tmp_name"]."'
                        REPLACE
                        INTO TABLE <tablename>
                        FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '\"'
                        LINES TERMINATED BY '\r\n'
                        IGNORE 1 LINES
                        "
    ;
    mysql_query($sql);
    if(
    mysql_error()) {
        echo(
    mysql_error());
    } else {
        echo(
    "Import sucessfull data imported to mysql table.");
    }
        }
      }
    else
    {
        echo
    "Invalid file type. Please make sure it is a text file.";
    }

    ?>
    5
    Average: 5 (1 vote)

    User login