Code-review tip: I do not see a definition for $limit, either. And if, as I believe to be the case, the offset and limit can be supplied as parameters ("?"), they should be. (Basically, never interpolate any values into an SQL string.) This code seems to have several logic errors in it. Carefully desk-check what you have just posted and you will see what I mean.