I got a few queries built dynamically by my scripts. They usually fit the following template:
SELECT ...
FROM ...
JOIN ...
WHERE ... (lots of filters, search conditions, etc. here) ...
ORDER BY (optional) ...
LIMIT (optional) ... OFFSET (optional)
I want to remove the LIMIT and OFFSET parts from the query. I used
$sql_entitati = implode("LIMIT", explode("LIMIT", $sql_entitati, -1));
to do it but then it hit me: what if there’s no LIMIT in the query and what if the only LIMIT is somewhere in the where clauses?
So my question to you is: How can I safely remove everything after the LIMIT key word, without screwing it up if there’s no LIMIT and/or there’s a “LIMIT” somewhere in the where clause? All this done in php.
A bit of an edit for clarity:
the algorithm i use:
$sql = implode("LIMIT", explode("LIMIT", $sql, -1));
Will work on 99% of the cases. The problem occurs when the “LIMIT” key word at the end is missing, AND there is “LIMIT” written somewhere in the conditions. for example:
SELECT * FROM table WHERE bla = 'SPEED LIMIT' ORDER BY table.a
this is the problem i need to tackle.
Solved using the following algorithm (Credit to techfoobar):
$p = strrpos($sql, "LIMIT");
if($p !== false) {
$q = strpos($sql, ")", $p);
$r = strpos($sql, "'", $p);
$s = strpos($sql, "\"", $p);
if($q === false && $r === false && $s === false)
$sql = substr($sql, 0, $p);
}
You should do something like:
p")"character afterp– if so, it is part of some inner query inside a condition etc.."'"character afterp– if so, it is part of some user input stringpMore hints:
strrposfor the last occurrence ofLIMITstrposwithpas the search start offsetsubstrto strip off everything afterp