Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
159 views
in Technique[技术] by (71.8m points)

php - GET multiple values from URL and have them in one string

I have created a simple cms for myself where i can post articles and have them have multiple categories.

so i.e. Article 1 has categories: Music and Technology and Article 2 has categories Music and Games

so if i go visit the Music category page i will see both Articles since they both have the category Music in them.

Now i only need to create that last part, the category page.

So whenever someone filters the categories: Music and Games it sends out the data to the URL like: http://domain.com/categories.php?cat1=music&cat2=games

now how would i GET those values music and games and place them in a string like: $filter = "music games" since those values are different every time someone filters the categories they want to see.

Someone else might filter Technology and Music then i want the string to be like: $filter = "technology music"

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I suspect you would want to do something along the lines of:

<form action="categories.php" method="GET">
  <fieldset>
    <legend>Filter Categories</legend>
    <p>
      <label><input type="checkbox" name="categories[]" value="music"/> Music</label>
      <label><input type="checkbox" name="categories[]" value="technology"/> Technology</label>
      <label><input type="checkbox" name="categories[]" value="film"/> Film</label>
    </p>
  </fieldset>
  <button type="submit">Filter</button>
  <button type="reset">Reset</button>
</form>

When submitted, this will give you a URL such as the following:

http://example.com/categories.php?categories[]=music&categories[]=technology

Then, in the script that displays the matching entries having one of these categories, you could do the following with the WHERE clause:

$get_categories = $_GET['categories'];
$cat_clauses = array();

while ($category = array_shift($get_categories)) {
    // Clean it
    $category = preg_replace('/[^a-z0-9-_]/i', '', $category);

    if ($category) {
        array_push($cat_clauses, "OR category LIKE '%$category%'");
    }
}

if ($cat_clauses) {
    $cat_where = "AND (" . implode(' ', $cat_clauses) . ")";
}

Which might give you something like:

SELECT *
FROM blog
WHERE active = 1
AND (category LIKE '%technology%' OR category LIKE '%music%')

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...