bockzior
bockzior

Reputation: 199

Is this a safe way to prevent sql injections?

I need some opinions about my php coding. I'm specially curious if this is safe against sql injections. Apparently it seems to be, but I might be wrong.

And what do you think of this "style" of coding, as in, is it acceptable or really bad practice ?

$validinputs = array(1,9,21,'a','b');

if(in_array($_GET['search'], $validinputs))
{
  $queryfilter = " = " . $_GET['search'];
}
else
{
  $queryfilter = "IS NOT NULL";
}

(...)

$query = "SELECT * FROM `table` WHERE `field` {$queryfilter}";

Thanks!

EDIT: In this case i compare with $validinputs because these are the only valid search terms for that field, any other search term would return nothing.

Upvotes: 0

Views: 80

Answers (2)

0x8BADF00D
0x8BADF00D

Reputation: 972

In my opinion, this is acceptable but not good practice at all. Why don't you use the standard SQL escape functions? These are really powerful and maintainable when wrapped in a class. I don't think that someone wants to maintain your application / script when you need to escape your strings this way that often. Probably causing a huge mess.

Upvotes: 1

gfish3000
gfish3000

Reputation: 1567

Ideally, you'd use stored procedures and your query would look like so...

$query = "call find_in_table('" . $_GET['search'] . "')";

... but since you have a list of acceptable inputs and are very strictly filtering them before passing them into a query string, I would say you're quite safe from SQL injection and using a stored procedure would be a performance enhancement for you more so than a security feature.

Upvotes: 0

Related Questions