Skip to content
Advertisement

how to optimize this sql insertion php code?

I have mysql database and I want to insert about 40’000 rows into it from PHP code , but my code takes more than 15 minutes to insert the rows, is there any chances to optimize it? where is my problem(PHP code / database design) ?

here are the details:

– the row data are stored in a utf-8 txt file the values separated by “t” tab character and every row sets in one line of the file, like this

string view:

JavaScript

text reader view:

JavaScript

-the data base has 3 tables as this:

JavaScript

– php code was like this

JavaScript

first I thought it is an index problem that slows down the insertion , so I removed all the indexes from “imports” table , but it didn’t go faster!! is the problem from the database design or from my php code?

also note that the browser is notifying “waiting for response from the server” for the first 5 minutes then most of the remaining time is notifying “transferring data from server”, is this because the response html has more than 40’000 line for the row counter1:1 </br> 2:1 </br> .....(declared in the php code)?

please consider I’m very newbie, thanks.

Advertisement

Answer

Thank you very much tadman and Hanlet Escaño and Uueerdo and Julie Pelletier and Solarflare for helping me in the comments.

I did 3 different changes in my PHP code using the approaches you suggested in the comments, then I tested the results and here are the tests results.

The conclusion of the 3 tests: as tadman suggested, the key is in LOAD DATA INFILE . it dramatically reduced the execution time to less than 7 seconds, and these are the 3 tests.


ORIGINAL CODE: ~ 26 minutes

enter image description here


TEST 1 : ~ 34 minutes

enter image description here

(as Uueerdo suggested I removed the echo statements and the rows counter from the loop)

JavaScript

TEST 2 : ~ 7 seconds

enter image description here

(As tadman said I searched for LOAD DATA INFILE and it was super powerful

JavaScript

TEST 3 : ~ 5 seconds

enter image description here

It was the same as test 2 except that I found useful tips on the same page that tadman give, that help in maximizing the speed for.

Bulk Data Loading for InnoDB Tables

JavaScript
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement