Gem
Gem

Reputation: 113

Import csv and update records in mysql using php

I'm trying to import a csv file in php and update existing records in mysql database but my code just won't work, it does not have any errors but it won't update my database. Here's is the code.

<?php  

$connect = mysql_connect("localhost","root",""); 
mysql_select_db("department",$connect); //select the table  

if (!empty($_FILES['csv']['size']) && ($_FILES['csv']['size']) > 0) {

get the csv file 
$file = $_FILES['csv']['tmp_name']; 
$handle = fopen($file,"r"); 

do { 
    if ($data[0]) { 
        mysql_query("INSERT INTO students (studno, lastname, firstname, mi,    
        sy, sem, course, deptname) VALUES 
            ( 
                '".addslashes($data[0])."', 
                '".addslashes($data[1])."', 
                '".addslashes($data[2])."',
                '".addslashes($data[3])."', 
                '".addslashes($data[4])."', 
                '".addslashes($data[5])."',
                '".addslashes($data[6])."',
                '".addslashes($data[7])."',
            ) 
        "); 
    } 
} while ($data = fgetcsv($handle,1000,",","'")); 

header('Location: admin/uploadinfo.php?success=1'); die; 
} 
?>

Upvotes: 0

Views: 878

Answers (1)

Deenadhayalan Manoharan
Deenadhayalan Manoharan

Reputation: 5444

Try this...

function getdata($csvFile){
    $file_handle = fopen($csvFile, 'r');
    while (!feof($file_handle) ) {
        $line_of_text[] = fgetcsv($file_handle, 1024);
    }
    fclose($file_handle);
    return $line_of_text;
}


// Set path to CSV file
$csvFile = 'test.csv';

$csv = getdata($csvFile);
echo '<pre>';
print_r($csv);
echo '</pre>';

Array
(
    [0] => Array
        (
            [0] => Project
            [1] => Date
            [2] => User
            [3] => Activity
            [4] => Issue
            [5] => Comment
            [6] => Hours
        )

    [1] => Array
        (
            [0] => test
            [1] => 04/30/2015
            [2] => test
            [3] => test
            [4] => test
            [5] => 
            [6] => 6.00
        ));

Upvotes: 1

Related Questions