Do while loop executes check_privs (sends SELECT query), then it moves to the next check_privs (sends SELECT query) and so on. The check to see if there is an entry happens at another time when results are retrieved from database, so the query that inserts data if there are no entries is sent after all SELECT queries from do while loop were sent.
To fix it you can simply concatenate all data that you want to send using do while loop and send it using 1 query.