[英]Error when uploading CSV file to database using PHP
我正在嘗試使用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!!";
?>
這些是我一直收到的錯誤:未定義的偏移量:第47行的C:\\ Apache2.2 \\ htdocs \\ clearTables.php中的1($ insert_csv ['cashAmount'] = $ csv_array [0];)。 未定義的偏移量:第48行的C:\\ Apache2.2 \\ htdocs \\ clearTables.php中的2。
有人知道問題出在哪里嗎? 謝謝
我測試了您的代碼,並且工作得非常好……並且,當我回顯查詢時,返回:
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))
之前與這一行進行檢查while (!feof($file))
if(is_file($csv_file)){ //your code}
此外,在查詢中,您有5個值,而行定義中只有4個值。 並且,為什么你有一個,
在那里?
如果您的問題仍然存在,請在此處檢查我的答案,如果您看的話,與您的代碼相似。
您在以下代碼中有語法錯誤。 所以更換
$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']."')";
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.