mrphuzz
mrphuzz

Reputation: 199

DELETE IN with explode()

I have a form that submits an array of transaction IDs to $_POST['transid'] so those transaction records can be deleted.

I typically use mysqli_real_escape_string to help prevent attacks, but I am not sure how to go about it with an array. The following is my query:

$query = 'DELETE FROM TRANSACTIONS WHERE (transid) IN ("'.implode('","',$_POST[transid]).'")'

...which gives me something like this:

$query = 'DELETE FROM TRANSACTIONS WHERE (transid) IN ("123","124","138","145")'

This seems to be asking for trouble. How can I protect myself from disaster (malicious or otherwise)? Is there an efficient way to sanitize the array? Or should I go about this another way?

Any thoughts or guidance would be appreciated.

Upvotes: 4

Views: 465

Answers (2)

Stephen O'Flynn
Stephen O'Flynn

Reputation: 2329

You're probably better off sanitizing the $_POST before you use it to implode and for that you'll have to traverse it. @user870018 beat me to the punch on the structure but here's what I'd do anyway:

function sanitize($n)
{
    return your_escape_function_here($n);
}

$values = implode(",", array_map("sanitize", $_POST[transid]));
$query = 'DELETE FROM TRANSACTIONS WHERE (transid) IN ('.$values.')';

Upvotes: 3

Kver
Kver

Reputation: 787

Use a foreach loop before building your query;

foreach ($_POST[transid] as &$x) $x = your_escape_function_here($x);

Or (if you use arrays in this manner regularly) build it into a function to keep the overall program a bit cleaner;

function sqlEscapeArray($arr){
foreach ($arr as &$x)
$x = your_escape_function_here($x);
return $arr;
}

Then use it like so;

$query = 'DELETE FROM TRANSACTIONS WHERE (transid) IN ("'.implode('","',sqlEscapeArray($_POST[transid])).'")';

Of course, replace your_escape_function with, well.... Your escape function.

Upvotes: 2

Related Questions