Reputation: 596
I know you are supposed to prepare all SQL statements where the user has influence over, this question is more to see if you can also have a SQL query where the user can change but you handle the errors differently.
The code which is SQL injectable:
if(isset($_GET['delete']) && (int)$_GET['delete'] && is_numeric($_GET['delete'])){
$query = $handler->query('SELECT * FROM portfolio WHERE id =' . $_GET['delete']);
}
else{
echo'Error';
}
Would the SQL query be safe from injection due to the if
statement around it or is there still some way of injecting it?
This is purely for research and it is obviously not in any real live website.
This is how the code looks when it is prepared just to show that I am not asking how to prepare:
if(isset($_GET['delete']) && (int)$_GET['delete'] && is_numeric($_GET['delete'])){
$query = $handler->prepare('SELECT * FROM portfolio WHERE id = :id');
$query->execute([
':id' => $_GET['delete']
]);
}
else{
echo'Error';
}
Upvotes: 0
Views: 40
Reputation: 157839
Yes, this particular code snippet is safe.
I wonder what useful conclusion you ever can draw from this answer.
Also, to answer some statements of yours.
you are supposed to prepare all SQL statements where the user has influence over,
This is one of the worst delusions connected to SQL injection problem. In fact, you are only considered safe if all 100% of your queries are parametrized, and you never ever bother yourself with a question "whether the data I am dealing with is one a user has influence over".
but you handle the errors differently.
this handling should be never ever connected to each other. If you want to verify the input parameters - it's a good idea. But by no means your SQL handling code should depend on the result of such a verification. It's just different matters. And in a properly organized code your input parameters verification never sit in the same file with SQL handling code. And the latter knows absolutely nothing of the fact of verification. Or any changes that has been done to such a verification (for example it allowed only numers at first and then changed to accept an arbitrary string). An SQL handling code should be able to run safe on any data provided.
Upvotes: 1