I'm trying to upload a CSV file into an existing table in my database using PHP.
Here is my full code:
<?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!!";
?>
These are the errors that I keep receiving: Undefined offset: 1 in C:\Apache2.2\htdocs\clearTables.php on line 47 (which is $insert_csv['cashAmount'] = $csv_array[0];). Undefined offset: 2 in C:\Apache2.2\htdocs\clearTables.php on line 48.
Does anyone know what the problem is? Thanks
mysql_querywhich should not be used in new applications because it's being removed from future versions of PHP. PDO is not hard to learn and provides a simple, reliable way of adding data to queries. A guide like PHP The Right Way outlines best practices.