Skip to content
Advertisement

Select active data by order

I have 2 tables posts and categories, There is one-to-many relation between both tables.

Here are the two tables:

JavaScript

There is a relation between category_id and c_id, So that the category_id in the posts table refers to the category id c_id.

The post_order and c_order are used to order both posts and categories.

And the post_active and c_active are used to define if it would be displayed for the users or not, 1 means yes it will be displayed, While 0 is no.

I show the categories and the posts are beneath them like:

JavaScript

The code to display the data:

JavaScript

There is HTML code inside the previous PHP code for creating tabs and accordion for each post, If that would help, Here is the full code:

JavaScript

I should get all the active categories and posts, But I only get the first active category with its posts ordered.

Advertisement

Answer

I’ll recommend this query:

JavaScript
  • Rather than asking php to trim the title, just fix it up within the query.
  • I am using INNER JOIN because I expect all rows in posts will have a corresponding row in categories.
  • Order by c_order then post_order so that categorical entries are grouped together when you iterate the resultset.

Based on my demo: http://sqlfiddle.com/#!9/4ca1a1/3

And referencing fetchAll‘s FETCH_GROUP

JavaScript

Your categories are in array_keys($resultset).

And you can iterate the prepared resultset and access the first level keys and the subarray rows to display the data.

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