Results 1 to 1 of 1

Thread: php script to import csv file into mysql

  1. #1
    Join Date
    Aug 2009
    Posts
    74
    Thanks
    7
    Thanked 1 Time in 1 Post

    Default php script to import csv file into mysql

    <?php


    $databasehost = "localhost";
    $databasename = "test";
    $databasetable = "sample";
    $databaseusername ="";
    $databasepassword = "";
    $fieldseparator = ",";
    $lineseparator = "\n";
    $csvfile = "Tasks.csv";

    $addauto = 1;

    $save = 1;
    $outputfile = "output.sql";
    /********************************/


    if(!file_exists($csvfile)) {
    echo "File not found. Make sure you specified the correct path.\n";
    exit;
    }

    $file = fopen($csvfile,"r");

    if(!$file) {
    echo "Error opening data file.\n";
    exit;
    }

    $size = filesize($csvfile);

    if(!$size) {
    echo "File is empty.\n";
    exit;
    }

    $csvcontent = fread($file,$size);

    fclose($file);

    include("db.php");

    $lines = 0;
    $queries = "";
    $linearray = array();

    foreach(split($lineseparator,$csvcontent) as $line) {

    $lines++;

    $line = trim($line," \t");

    $line = str_replace("\r","",$line);


    $linearray = explode($fieldseparator,$line);

    $linemysql = implode("','",$linearray);

    if($addauto)
    $query = "insert into $databasetable values('','$linemysql');";
    else
    $query = "insert into $databasetable values('$linemysql');";

    $queries .= $query . "\n";

    @mysql_query($query);
    }

    @mysql_close($con);

    if($save) {

    if(!is_writable($outputfile)) {
    echo "File is not writable, check permissions.\n";
    }

    else {
    $file2 = fopen($outputfile,"w");

    if(!$file2) {
    echo "Error writing to the output file.\n";
    }
    else {
    fwrite($file2,$queries);
    fclose($file2);
    }
    }

    }

    echo "Found a total of $lines records in this csv file.\n";


    ?>
    --------------------------------------------------------------------------


    i am able to import csv file by this script

    my problem is, in my csv file there r arround 97 records. among them from 60-90 some records are having data and time(23 Sep, 2009 09:00:00). 30 records containing data and time are not inserted in mysql database.

    if anyone knows help me out??????????????????????????
    Last edited by hemi; 09-25-2009 at 06:59 AM.

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •