2014-02-24 93 views
0

我試圖使用PHP將CSV文件上載到我的數據庫中的現有表中。使用PHP將CSV文件上傳到數據庫時出錯

這是我的全碼:

<?php 
include("detail.php"); 


$connect = mysql_connect("$host", $user, $password) or die("Couldn't connect to SQL Server on $myServer"); 
mysql_select_db("$database") or die("Couldn't open database $myDB"); 

if (mysqli_connect_errno()) 
{ 
echo "Failed to connect to MySQL: " . mysql_connect_error(); 
} 


define('CSV_PATH','E:/4th Year/FYP/'); // specify CSV file path 

    $csv_file = CSV_PATH . "Cash2011.csv"; // Name of your CSV file 
$csvfile = fopen($csv_file, 'r'); 
$theData = fgets($csvfile); 
$i = 0; 
while (!feof($csvfile)) 
{ 
    $csv_data[] = fgets($csvfile, 1024); 
    $csv_array = explode(",", $csv_data[$i]); 
    $insert_csv = array(); 
    $insert_csv['cashAmount'] = $csv_array[0]; 
    $insert_csv['cashReceivedDate'] = $csv_array[1]; 
    $insert_csv['customerID'] = $csv_array[2]; 
    $insert_csv['invoiceNo'] = $csv_array[3]; 
    $insert_csv['monthNum'] = $csv_array[4]; 
    $insert_csv['yearNum'] = $csv_array[5]; 
    $query = "INSERT INTO cash2011(cashAmount,cashReceivedDate,invoiceNo,monthNum,yearNum) VALUES ('','".$insert_csv['cashAmount']."','".$insert_csv['cashReceivedDate']."','".$insert_csv['customerID']."','".$insert_csv['invoiceNo']."','".$insert_csv['monthNum']."','".$insert_csv['yearNum']."')"; 
    $n=mysql_query($query, $connect); 
    $i++; 
    } 
    fclose($csvfile); 
    echo "File data successfully imported to database!!"; 
    ?> 

這些是我繼續接收錯誤: 未定義偏移:1 C:\ APACHE2.2 \ htdocs中\ clearTables.php在線47上(這是$ insert_csv ['cashAmount'] = $ csv_array [0];)。未定義偏移量:2在C:\ Apache2.2 \ htdocs \ clearTables.php在線48上。

有誰知道問題是什麼? 感謝

+0

啥子不的print_r($ csv_array)告訴你? – bart2puck

+0

爲了讓它更清潔一些,爲什麼不把它變成像$ cashAmount = $ csv_array [0];這樣你可以插入$ cashAmount而不是$ insert_csv ['cashAmount'];在那裏做什麼沒有錯,只是一個小清潔器IMO – bart2puck

+0

你確定你的CSV文件中的所有行包含6個值,如現金,東西,其他等等,似乎有些行只有1個值。 – CodeBird

回答

0

我測試你的代碼,並且工作得非常好... ,當我回聲查詢,返回:

INSERT INTO cash2011(cashAmount,cashReceivedDate,invoiceNo,monthNum,yearNum) 
VALUES ('','ad4213','ad4214','ad4215','ad4216','adware','ad7777 ') 
    //'','ad4213','ad4214','ad4215','ad4216','adware','ad7777 ' -> data in my example csv file 

一些東西.. 我相信,你的文件不存在的,這就是爲什麼你有這些錯誤,請嘗試前while (!feof($file))

if(is_file($csv_file)){ //your code} 

也與這條線檢查,在您的查詢,你有5個值,只有在行定義4。 以及爲什麼你在那裏有,

如果您的問題仍然存在,請檢查我的回答here,如果您看,則是您的類似代碼。

0

你在下面的代碼中有語法錯誤。所以更換

$query = "INSERT INTO cash2011(cashAmount,cashReceivedDate,invoiceNo,monthNum,yearNum) VALUES ('','".$insert_csv['cashAmount']."','".$insert_csv['cashReceivedDate']."','".$insert_csv['customerID']."','".$insert_csv['invoiceNo']."','".$insert_csv['monthNum']."','".$insert_csv['yearNum']."')"; 

通過

$query = "INSERT INTO cash2011(cashAmount,cashReceivedDate,invoiceNo,monthNum,yearNum) VALUES ('".$insert_csv['cashAmount']."','".$insert_csv['cashReceivedDate']."','".$insert_csv['customerID']."','".$insert_csv['invoiceNo']."','".$insert_csv['monthNum']."','".$insert_csv['yearNum']."')"; 
相關問題