Skip to content
Advertisement

PHP – Loop through UNION ALL query and add custom text once after the last item per category

I have a union query which joins several categories. I want to include the link after the last item of the category.

The query goes like:

JavaScript

… the result is

JavaScript

The output should be like this:

JavaScript

Here is the loop thanks to user @Luuk, but now I would like to include a link after the last item from the category.

JavaScript

Advertisement

Answer

There are quite a few questions I have regarding this logic:

  1. Are you getting all of this data from the same table, I assume so as you have used the same table name in the question.
  2. Why are you limiting each category? do you only ever want to get that many records for that category? what if there was 7 records for category 2, why would you not want to show the last record?
  3. What do you mean by go to the category? PHP is rendered on the server and therefore cannot perform any extra actions after it has ran. When you say go to the category do you mean open a new page displaying data about this category?
  4. Is the category an ID to another table called “category” that has the information about that category? ( if not it really should be ).

My answer below is assuming the answers to the above questions are 1:Yes; 2:Don’t need a limit; 3:Yes, open a new page; 4:Yes. I don’t mean any offence but I am assuming from the question your new to Web Development so I will explain each step.

Query:

JavaScript

Here you’re getting all items in the item table and joining them onto the category table, then ordering it by the category_id to make sure they all come back in the order they will be displayed in. You should end up with a list that looks like this:

JavaScript

the first variable being the item id, the second being the item name, the third being the category id and the forth being the category name

Code:

JavaScript

Then you would have another file, I have called it ‘category.php’ that has a URL parameter telling the category page which category it needs to load. On the category.php page the code to grab that ID would look like this:

JavaScript

as the user could change the URL parameter you would definitely need to wrap the $category_id in some sort of security function that strips it of any potential hackers code but for simplicity I have not included that.

Although I am not 100% this answers your question, I hope it provides some explanation as to how you would normally do something like this.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement