bulk load to azure using php

Viewed 111

I am trying to load CSV to an Azure webserver database using PHP. The CSV's are 2000 lines each. I have it working but when I run the file on the web page the database is only updated with 479 entries and I am not sure why. The webpage takes a long time to process then it will show the page saying its completed. Here's what I have for the insert statement.

try {
    $connection = new PDO("sqlsrv:server = tcp:".$SrvName.",1433; Database = ".$DBName, $SQL_USER, $SQL_PASS);
    if (($handle = fopen("personal.csv", "r")) !== FALSE) {
        while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
            $num = count($data);
            $sql = "INSERT INTO personal (clientId, lastname, ssn)
                    VALUES ($data[0], $data[1],$data[2])";
            $statement = $connection->prepare($sql);
            $statement->execute();
        }
        fclose($handle);
    }

} catch(PDOException $error) {
    echo $sql . "<br>" . $error->getMessage();
}

Any help is greatly apreciated!

1 Answers

I think we have two solutions:

Solution1
How to: Send Data as a Stream: The Microsoft Drivers for PHP for SQL Server takes advantage of PHP streams for sending large objects to the server.

Solution2
Design a stored procedure, pass the file name as a parameter.
Example code:

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[spBulkInsert]  @FileName varchar(255)
AS
declare @sql varchar(max)
BEGIN Try
set @sql =  
'INSERT into  ext.customer_Staging with (TABLOCK) (customer, age, gender)
   SELECT * FROM OPENROWSET(
   BULK '+ @FileName + ',
   DATA_SOURCE = ''MyDataSource'',
   FORMAT = ''CSV'',
   FORMATFILE_DATA_SOURCE = ''MyDataSource''
   ) AS DataFile;
   go'

 exec(@sql)
END TRY 

BEGIN CATCH
    PRINT ERROR_MESSAGE()
END CATCH

GO

Then use php to call this sqlserver stored procedure instance.


But don't BULK INSERT into your real tables directly.

  • I would always insert into a staging table ext.customer_Staging (without the IDENTITY column) from the CSV file
  • possibly edit / clean up / manipulate your imported data
  • and then copy the data across to the real table with a T-SQL statement like:
INSERT into  ext.customer_Staging with (TABLOCK) (customer, age, gender)
   SELECT * FROM OPENROWSET(
   BULK 'bs140513_032310-demo.csv',
   DATA_SOURCE = 'MyDataSource',
   FORMAT = 'CSV',
   FORMATFILE_DATA_SOURCE = 'MyDataSource'
   ) AS DataFile;
   go

INSERT INTO ext.customer(Name, Address) 
   SELECT customer, age, gender
   FROM ext.customer_Staging
Related