You are being saved in this case by PHP, not by SQL.
https://wiki.php.net/rfc/invalid_strings_in_arithmetic explains the Notice: A non well formed numeric value encountered
notice. PHP 7.1 introduced more strict
rules about using strings in arithmetic expressions.
Your expression $page*$maxPerPage
is an arithmetic expression, but you're trying to multiply a string $page
by an integer. This causes the notice.
You could ignore the notice by not enabling error_reporting(E_NOTICE);
or by suppressing the notice with the @
operator:
@$numberOfApples = "10 apples" + "5 apples";
Whether you suppress the notice or not, the value will be converted to a numeric, ignoring the extra text after the digits. This happens before the result of the multiplication is interpolated into your SQL string, so it's guaranteed to be an integer, therefore it's safe from SQL injection.
Another workaround would be to coerce $page
to be an integer as you fetch it from the $_GET
superglobal:
$page = (int) $_GET["p"];
Once you do that, you can use it in your multiplication without causing a notice. But by casting it to an integer, you've already filtered out anything that could cause SQL injection.
So the comments above were unable to provide an example of an SQL injection exploit, because there is none possible in this example.
But it's still a good habit to use query parameters instead of concatenating strings. The reason is that if you use different methods, it requires the programmer to understand deeply how expressions will evaluate in every case. If they see a string-concatenation expression like yours, they will of course notice it as a potential SQL injection vulnerability, and it will take some time to analyze it until they understand that it is safe.
You want to make your code easy to maintain by people who come after you. That means making it clear and consistent. There will undoubtedly be cases where you have to use query parameters because you're interpolating strings, not results of arithmetic expressions. Any programmer who reads your code will wonder, "why use query parameters only sometimes?"
So I agree with the other comments that you should use query parameters, not string concatenation, even when you know because of some nuance of PHP expressions that it is safe in a specific case.