The broken SQL is the result not the root cause, mostly (guessing) due to opcache and function calls.
As I say here https://moodle.org/mod/forum/discuss.php?d=362349#p1461346, the problem ist that the caps array has not the right capabilities and then the roleid is "NULL". And the strange thing is, that the error must come from the database (I explain it in the previous comments, what I've done...).
So what I think is, that moodle can't access the right capabilities from the database and then this "SELECT ... statemenet" for search through the site administration gives an error.
Why this behaviour happened only with PHP 7.1.12 is also dubious.