I am using the PHP code below to make bulk insert into database table in SQL Server. I already have a table called ShopifyItem (with 25 columns) but when I use this code I got
Undefined offset: 24
error message and in Item table I only see
(26 row(s) inserted properly) even the csv file have more than 1,000 in row.
Can anyone tell me what’s wrong?
PHP code:
$server = "**\**,1433";
$connectionInfo = array( "Database"=>"**", "UID"=>"**", "PWD"=>"**" );
$conn = sqlsrv_connect( $server, $connectionInfo );
if( $conn === false ) {
die( print_r( sqlsrv_errors(), true));
}
$file_handle = fopen("Table.csv", "r");
while (!feof($file_handle) ) {
$line_of_text = fgetcsv($file_handle, 1024);
$tsql = "INSERT INTO Item (Handle, Title, [Body(HTML)], Vendor, [Type], Tags, [Option1 Name],[Option1 Value], [Option2 Name], [Option2 Value], [Option3 Name], [Option3 Value], [Variant SKU], [Variant Grams], [Variant Inventory Tracker],[Variant Inventory Qty], [Variant Inventory Policy], [Variant Fulfillment Service], [Variant Price], [Variant Compare At Price], [Variant Requires Shipping], [Variant Taxable], [Image Src], HQID, WebPrice)
VALUES ('$line_of_text[0]','$line_of_text[1]', '$line_of_text[2]', '$line_of_text[3]', '$line_of_text[4]', '$line_of_text[5]', '$line_of_text[6]', '$line_of_text[7]', '$line_of_text[8]', '$line_of_text[9]', '$line_of_text[10]', '$line_of_text[11]', '$line_of_text[12]', '$line_of_text[13]', '$line_of_text[14]', '$line_of_text[15]', '$line_of_text[16]', '$line_of_text[17]', '$line_of_text[18]', '$line_of_text[19]', '$line_of_text[20]', '$line_of_text[21]', '$line_of_text[22]', '$line_of_text[23]', '$line_of_text[24]' )";
if( sqlsrv_query( $conn, $tsql))
{
echo "Statement executed.\n";
}
else
{
echo "Error in statement execution.\n";
die( print_r( sqlsrv_errors(), true));
}
}
If there are no problems with your csv file, the likely candidate is this line:
You are limiting the data read for each line to 1024 bytes. If the line is longer than this, it will be truncated, and possibly give you this error of missing elements. You can change the buffer size, like this, if you know the maximum line length:
Or even try it like this to see if this is the cause of your problem:
This will just run a little slower, but will not limit your line length.
If this does not work, then it would be useful if you could post the csv data lines 20-30.