clearly your if statement is not being met and therefore the code that begins '$sql=substr($sql, 0, (strLen($sql)-3) is messing up your SQL.