0

I have a form that outputs data to this:

index.php?city=ADDIEVILLE&city=ALBERS&city=ALHAMBRA

Then need to go into a mysql where statement like so:

WHERE CITY = ADDIEVILLE OR CITY = ALBERS OR CITY = ALHAMBRA

How would I be able to pass those multiple cities along to the mySQL query using PHP?

1
  • 2
    In your form, you should not have multiple elements with name='city' instead, you should define them all with the same name as an array name='city[]' Then $_GET['city'] will itself be an array. Commented Jan 3, 2013 at 19:59

2 Answers 2

3

index.php?city=ADDIEVILLE&city=ALBERS&city=ALHAMBRA

would print as: $_GET['city']='ALHAMBRA';

whereas:

index.php?city[]=ADDIEVILLE&city[]=ALBERS&city[]=ALHAMBRA

would print as an array.

this could then be transformed into:

$cities = $_GET['city'];

$str = "CITY='".implode("' OR CITY='",$cities)."'";
echo $str;

Note: $cities should be sanatized for injections.

Sign up to request clarification or add additional context in comments.

2 Comments

It's not passing it through as city[] but as city%5B%5D
it would appear it is encoding the URL
1

As @MichaelBerkowski says, you should use city[] as your field name, then you can do something like this:

$dbh = new PDO("mysql:dbname=$dbname", $username, $password);
$dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES, FALSE);

$qry = $dbh->prepare('
  SELECT *
  FROM   my_table
  WHERE  CITY IN ('.implode(',', array_fill(0, count($_GET['city']), '?')).')
');

$qry->execute($_GET['city']);

1 Comment

First select multiple. Thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.