CSV into MySQL using PHP

I wanted to get various fields from a CSV into a MySQL table, it was a two second job. Here is is for anybody that needs it:


[codesyntax lang=”php”]


//error reporting


ini_set('display_errors', 1);

//1) connect to mysql

$db = new PDO('mysql:host=localhost;dbname=database;charset=utf8', 'username','password');


$row = 1;

if (($handle = fopen("tweets.csv", "r")) !== FALSE) {

    while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {


        $num = count($data);

        echo "<p> $num fields in line $row: <br /></p>n";


          $query = "INSERT INTO store(store, site, date) VALUES('$data[7]', 'twitter','$data[5]')";

          print $query;

          $result = $db->exec($query);

  print $result;

          print  $db->lastInsertId();







Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.