Forum Moderators: coopster

Message Too Old, No Replies

Form handling with Checkboxes

Form handling with Checkboxes

         

knippysing

6:35 pm on Apr 19, 2007 (gmt 0)

10+ Year Member



I am trying to get the form handling figured out and for some reason cannot make it fly.
The code below is an example of what I am trying to do. I can't seem to pass the array results to the $query. If I have the "echo $city" within the foreach function, it will display correctly but once it's out of the foreach function it only lists the last item in the array that was passed.
Does anyone have any ideas? I can't seem to find that right answer anywhere.

$cities = $_POST['city'];
foreach ($cities as $citypieces){
$citypieces = "$citypieces;";
$pieces = explode(";", $citypieces);
$count = count($pieces);
//start IF two locations
$city = implode("' OR (city)='", $pieces);
}
echo $city;

$query = "select * from sg_listings WHERE (((active)=1) AND ((city)='$city'))";

cameraman

7:02 pm on Apr 19, 2007 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



To answer your question specifically, I think what you really want to do here:
$city = implode("' OR (city)='", $pieces);
is to concatenate it:
$city .= implode("' OR (city)='", $pieces);

You should set $city to an empty string before the foreach loop:
$city = '';
foreach($cities.....

From the title of your post I'm assuming that you have a bunch of cities as checkboxes on a form, each with attribute name="city[]"
As it appears that you've figured out, that comes to you as an array in the variable $_POST['city'].
What you can do with that is:
$city = implode("','",$_POST['city']);

In that line above, the first argument for implode() is a double-quote single-quote comma single-quote double-quote
After that line, you'll have something similar to:
Akron','Baltimore','Chicago','Denver

Now (and this could have been done on the implode line above but we're breaking it down dontcha know):
$city = "'" . $city . "'"; // double-quote single-quote double-quote on each end

And we've got:
'Akron','Baltimore','Chicago','Denver'

And now, finally, your query can be:
$query = "select * from sg_listings WHERE ((active=1) AND (city IN ($city)))";

Your entire code segment, then, can be replaced with:
$city = "'" . implode("','",$_POST['city']) . "'";
$query = "select * from sg_listings WHERE ((active=1) AND (city IN ($city)))";
$count = count($_POST['city']); // If you'll be needing this later on.

Pretty cool, eh?