使用php导入csv并更新mysql中的记录


Import csv and update records in mysql using php

我试图在php中导入csv文件并更新mysql数据库中的现有记录,但我的代码只是不起作用,它没有任何错误,但它不会更新我的数据库。代码如下:

<?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; 
} 
?>

试试这个…

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
        ));