08.08.2017, 12:46
First of all, never ever query the database in a loop. Build the query earlier, call it once. Second of all, code looks ok at the first glance - to debug it, dump printf everywhere, then look at server console to see which steps were called and which weren't.