504 Gateway Time-out after custom plugin inserts data into mysql database

I have a custom plugin that inserts multiple rows into a custom table in the wordpress database. After about 50 seconds I get a 504 Gateway Time-out error. The 50 seconds is around about the time it takes to insert ~400 rows. Anything less, and the script completes just fine.

I’ve added the usual things to wp-config.php and .htaccess

wp-config.php

.htaccess

…but none of these seem to make any difference. The script always timeout after about 50 seconds and I get 504 Gateway Time-out The server didn't respond in time error screen.

My code:

Then I do a foreach loop where I prepare my data based on some other conditions. I end up with this array structure towards the end of the loop:

Then I end my loop. This loop could have added hundreds of arrays to $insert_data. All the data are strings.

Then I prepare my sql query:

After this script runs for about 50 seconds I get the 504 Gateway Time-out

Anyone? Cheers.