我正在尝试使用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。
有谁知道问题是什么? 感谢
答案 0 :(得分: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,如果您查看,则与您的代码类似。
答案 1 :(得分: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']."')";