Log in

View Full Version : passing array in URL, cannot make $_GET produce array



jonas-e
08-19-2007, 06:40 PM
Hello,
I want to pass an array through a URL, then select data in my database from those values.
I have this URL:
../elements_by_id.php?id[]=1&id[]=2&id[]=5
Then I use this code:

$id = array();
$id = $_GET{'id'};
$id_select="";
$count = count($id);
$incr = 0;
foreach ($id as $ids) {
$id_select.="$ids";
$incr = $incr + 1;
if ($count = $incr) {$comma = ", ";}
else {$comma = "";}
$id_select.="$comma";
}
- to produce the array and from that a mysql select statement.

The idea is that the $id_select should end up having this value:
"1, 2, 5" (*)
- but i appears to be empty. Can anyone see what I am doing wrong?

(*) Will be using this in an mysql statement like this:
"select * from mytable where id in (1, 2, 5)"

jonas-e
08-19-2007, 06:45 PM
OK - perhaps I should inverse the if statement and use "==" instead of "=":

if ($count == $incr) {$comma = "";}
else {$comma = ", ";}

jonas-e
08-19-2007, 06:48 PM
It works - sorry ... :o

thetestingsite
08-19-2007, 06:52 PM
Your best bet would be to do something like this (modified the code you posted):



$id_select="";

$count = count($_GET['id']);

$incr = 0;

foreach ($_GET['id'] as $id) {
$id_select.="$id";
$incr = $incr + 1;
if ($count == $incr) {$comma = ", ";}
else {$comma = "";}
$id_select.="$comma";
}


Hope this helps.

(Note: Not tested for your purposes, but if you go to http://phphost.smackum.com/test/test.php, you can see what how I came up with this code. (The source is at http://phphost.smackum.com/test/test.phps))

//EDIT: Sorry, I was typing as you posted. Glad to hear you worked it out.

jonas-e
08-19-2007, 10:29 PM
Thanks mate - your code is perhaps a bit more condensed but essentially the same? My error was apparently the typical == error - and the wrong if statement ..

Twey
08-20-2007, 03:02 AM
Neither of you have done any validation on that -- they'll own your server before you can say "SQL injection."
$id_select = implode(', ', array_filter($_GET['id'], 'is_numeric'));