When I run this few times, it updates table ps_stock_available but with wrong values and after some time is stops to update that table? The problem is in the last query, two queries above are working
Can you tell me what other errors you got? You never mention what error you got instead you just mention the last query? When you ran the code what error messages appear on which line? You have to understand I don't have a db to test this out.
Currently you're problem description and code is cryptic, if you can ellaborate more, the better. Check this part if you're really getting inside the ifs, or the part where you're using the $shopProductIndex:
// ako je postavljen raspon ...
if ( $nrRows > 0 )
// ... preskoci prve ...
if ( $shopProductIndex < $first )
// ... ili prekini nakon zadnjeg
else if ( $shopProductIndex > ($first + $nrRows - 1) )