Plummer
Plummer

Reputation: 6688

mySQL getting multiple arguments for single column from URL query

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?

Upvotes: 0

Views: 254

Answers (2)

eggyal
eggyal

Reputation: 125865

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']);

Upvotes: 1

Samuel Cook
Samuel Cook

Reputation: 16828

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.

Upvotes: 3

Related Questions