March 15, 2012

csv to mysql loading

Question by Tzook Bar Noy

Im trying to upload this csv file to mysql on my hosting.

The csv is built by two collums:
alias, id

and than each row contains the data.
here is an image
a screenshot of my csv file

But the mysql rejects me.
why is that?

Answer by sam yi

You can also open up csv from excel and generate series of insert statements. Not the best solution but might be useful if you’re looking for something quick and dirty.

Answer by Starx

Solution using PHP

$file = 'path/to.csv'; 

$lines = file($file);
$firstLine = $lines[0];
foreach ($lines as $line_num => $line) {
    if($line_num==0) { continue; } //escape the header column
    $arr = explode(",",$line);
    $column1= $arr[0];
    $column2= $arr[1];

    echo $column1.$column2."<br />";
        //put the mysql insert statement here
}

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!