mickburkejnr
mickburkejnr

Reputation: 3690

How to pass multiple values of a variable through a URL

I've an application that I'm building, and I'm stuck at a certain point.

I'm trying to pass a variable that has multiple values. So my URL will look like:

localhost/report.php?variable=value1, value2, value3

Problem is I'm not sure how I can do this. The variables are to be used to retrieve data from a database. I'm using PHP and no Javascript.

Any help would be great!

EDIT:
Here is the HTML I have in my page where the variables are selected:

<select name="types" size="19" multiple>
    <option value="all" selected>All Types</option>
    <option value="book" selected>Books</option>
    <option value="cd" selected>CD</option>
</select>

So a user could select Books and CD, and I would need to pass these two values in the "types" variable.

Upvotes: 8

Views: 91490

Answers (6)

DACrosby
DACrosby

Reputation: 11470

As noted at https://stackoverflow.com/a/2407401/1265817, you can use this method.

If you want PHP to treat $_GET['select2'] as an array of options just add square brackets to the name of the select element like this: <select name="select2[]" multiple …

Then you can acces the array in your PHP script

<?php
header("Content-Type: text/plain");

foreach ($_GET['select2'] as $selectedOption)
  echo $selectedOption."\n";

Upvotes: 5

Chris
Chris

Reputation: 342

There is a simple way to do this in PHP by calling http_build_query() and pass your values as an indexed array. You would do something like:

$value_array = array('types' => array('book', 'cd'));
$query = http_build_query($value_array);

Then generate the url using $query.

Upvotes: 6

MAMProgr
MAMProgr

Reputation: 410

You can use serialize like:

echo '<a href="index.php?var='.serialize($array).'"> Link </a>';

and get data using unserialize like:

$array= unserialize($_GET['var']);

serialize function giving you storable (string) version of array type, and can be restored by unserialize function.

Upvotes: 0

DACrosby
DACrosby

Reputation: 11470

I think you have your URL correct

localhost/report.php?variable=value1,value2,value3

Then use PHP to get all of the values on the report.php page

$variable = explode(",", $_GET["variable"]);

// Output
$variable[0] = "value1";
$variable[1] = "value2";
$variable[2] = "value3";

Upvotes: 3

WayneC
WayneC

Reputation: 5740

try localhost/report.php?variable[]=value1&variable[]=value2 will give you an array in php

Upvotes: 2

user153923
user153923

Reputation:

Use &

localhost/report.php?variable=value1&val2=value2&val3=value3

Is that what you are after?

Upvotes: 11

Related Questions