简体   繁体   中英

Beginner's PHP Question: Using method=“get” with checkboxes

I have a form something like this:

<form action="video-sort.php" method="get">      
<h3>Game</h3>
<ul> 
    <li><input id="game-180man" type="checkbox" name="game" value="180man">180man</li>
    <li><input id="game-18man"  type="checkbox" name="game" value="18man">18man</li>
    <li><input id="game-mtt"    type="checkbox" name="game" value="MTT">MTT</li>        
</ul>       
<h3>Type</h3>
<ul>
    <li><input id="type-lecture"  type="checkbox" name="type" value="Lecture">Lecture</li>
    <li><input id="type-liveplay" type="checkbox" name="type" value="Liveplay">Liveplay</li>
    <li><input id="type-tutorial" type="checkbox" name="type" value="Tutorial">Tutorial</li>
</ul>       
<input type="submit" />     
</form>

If the first of each set is checked, I get the URL:

video-sort.php?game=180man&type=Lecture

Great! But when more than one checkbox in each category is checked, I get (if I check all, for example):

video-sort.php?game=180man&game=18man&game=MTT&type=Lecture&type=Liveplay&type=Tutorial

No good! It only takes the final argument.

Also, I tried a form where name=game[] and name=type[] but the URL ended up just adding the brackets to the names (ex: video-sort.php?game[]=180man&game[]=18man instead of putting them together.

I'd like to get the URL to read:

video-sort.php?game=180man,18man,MTT&type=Lecture,Liveplay,Tutorial

How could I accomplish this? Any help would be greatly appreciated!

EDIT: This is for a Wordpress site. I'm creating a post filter and for Worpdress to understand the query, to the best of my knowledge, the arguments need to be in a commma-separated list. If I use the brackets, I get the error:

Warning: preg_split() expects parameter 2 to be string, array given in /wp-includes/query.php on line 1694

(source of that file: http://phpxref.com/xref/wordpress/wp-includes/query.php.source.html )

That's correct,

?game[]=180man&game[]=18man

just adds keys to an array. Keep it like that.

The proper way really is to use the array syntax (game[]), that way in your video-sort.php code you can fetch the whole array like this:

$games = $_GET['game'];
foreach ($games as $game) {
  // do something
}

If you really had to have the game parameter be a comma delimited list, you would probably want to use javascript (ie jquery) to fetch a list of checked values, create the list, and then append that to your form post. Too much work and too prone to error. What if one of your games had a comma in its value?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM