Welcome to the Question2Answer Q&A. There's also a demo if you just want to try it out.
+2 votes
in Q2A Core by
Is there any function which results all categories.
Actually I want to fetch all categories for db. how can I get it?

1 Answer

+1 vote
selected by
Best answer

I don't think there's a dedicated function for listing the categories, but you can easily query them from the database. Categories are stored in the table qa_categories, so the query for fetching the category names would look like this:

SELECT title FROM qa_categories;

Use the function qa_db_query_sub() for querying the database, and use the function qa_db_read_all_values() for retrieving the values from the returned result set.

if (qa_using_categories()) {
  $query      = 'SELECT title FROM ^categories';
  $result     = qa_db_query_sub($query);
  $categories = qa_db_read_all_values($result);

The circumflex (^) in the query is a shortcut. Q2A automatically expands it to the table name prefix (by default "qa_").

Beware, though, that categories can be hierarchical (i.e. a category can have sub-categories). In the database table this is reflected by referencing the ID of the parent category in the field parentid. If you do have hierarchical categories and the hierarchy is relevant for your application, you need to query category ID and parent ID along with the title and then construct a tree data structure (usually that will be an associative array) from the result set.

if (qa_using_categories()) {
  $query      = 'SELECT categoryid, parentid, title FROM ^categories';
  $result     = qa_db_query_sub($query);
  $categories = qa_db_read_all_assoc($result);
  // build tree data structure from $categories here

qa_db_read_all_assoc() returns the records as a list of associative arrays with the column names as keys.

Thanks for your elaborate explanation. It will help.