⚠ In case you've missed it, we have migrated to our new website, with a brand new forum. For more details about the migration you can read our blog post for website migration. This is an archived forum. ⚠

  •     

profile picture

Import csv file to database on upload



shibbolith

shibbolith
  • profile picture
  • Member

Posted 22 March 2015 - 16:16 PM

I'm looking for an example of how to import the contents of a .csv file to my database when I upload it.

 

My upload function works (will save the file to the appropriate folder and place the url/path in the database), but am struggling with code to import the file to a data-table in my database.

 

I found a separate function that could accomplish this, but have not been able to use it in the CI / Grocery CRUD model I've set up.

if (isset($_POST['submit'])) {
    if (is_uploaded_file($_FILES['filename']['tmp_name'])) {
        echo "<h1>" . "File ". $_FILES['filename']['name'] ." uploaded successfully." . "</h1>";
        echo "<h2>Displaying contents:</h2>";
        readfile($_FILES['filename']['tmp_name']);
    }

    //Import uploaded file to Database

    $handle = fopen($_FILES['filename']['tmp_name'], "r");

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

        $import="INSERT into contacts_short(contact_first,contact_last,contact_email) values('$data[0]','$data[1]','$data[2]')";

        mysql_query($import) or die(mysql_error());

    }

    fclose($handle);

I'm relatively new to Grocery CRUD but have been impressed with it so far.  Any help would be appreciated.