1

I've got a table with some rows that contain 3 fields (category, title, image). At first I created a foreach loop that returned some html with the information from each of the rows. However, now I actually want to create a scenario where I can "filter" my loop by category.

What I mean to say is that I want to create a function that will only generate the html for rows that have a particular value for their category field. I want to be able to apply this function to all the different values for category.

Any help would be appreciated.

4
  • 1
    why not filter it directly in your query? so you won't need any filters in your php code? all you have just to do is to display an html for the rows. Commented May 22, 2013 at 3:11
  • Is filtering using mysql okay? Commented May 22, 2013 at 3:11
  • yeah, you could have just something like this in your where clause, WHERE category <> NULL Commented May 22, 2013 at 3:16
  • As the other comments have suggested and I've used in my answer, a WHERE statement is one of the basic functions of MySQL that lets you filter your queries. Can you put up the code where you are querying mysql? Then I can show you how to modify it to match the query below.. Commented May 22, 2013 at 3:20

2 Answers 2

2

MySql query solution:
Use a Where Statement in your query, and keep your PHP the same.
e.g.

Select * From table Where `category`="Filter Value";

Let me know if that works for you, or if you're constrained to only using PHP to filter the category..

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

2 Comments

I wanted to do it PHP simply because I didn't know how easy of a solution it was to do in the mysql query.
MySQL is for querying. lol It's whole purpose is retrieving data.
1

Either use the WHERE clause as asifrc suggested.

Or do something like this

while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
    if($row['category'] == 'category1') {
      // do some stuff example
      $html_output .= '<p style="font-weight:bold">Important category: ' . $row['title'] . '</p>';
    } else if($row['category'] == 'category2') {
      // do other stuff
      $html_output .= '<p>Not important category: ' . $row['title'] . '</p>';
    }
}

2 Comments

Yea, that's how I had it in PHP, but I was wondering if there was something less convoluted (I've got a lot of categories)
Does your handling of categories have to be unique for each category? Are there groups of categories? i.e. if there are 5 categories of categories then we can split them up using a switch. Or if the handling depends on some aspect of the category, that might be a clue. Any more info?

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.