Skip to content
Advertisement

Parent Child Relationships PHP/MYSQL

I have a table like this:

  • id
  • name
  • parent_id

I then want to select certain rows based on their id, so something like this:

JavaScript

I want to, from this query, also show the parent/child relationship, like:

JavaScript

So the final output would look something like this:

JavaScript

Do I do this outside of mysql, i have tried using arrays, but can’t figure it out, or
Do I do it inside MYSQL, which i don’t know how to do that either.

Advertisement

Answer

Here is what I was able to come with which seems to be working great.

PS-Sorry about the formatting, can’t figure it out 🙁 (fixed?)

  1. I grab my parent_id and id from MYSQL and put it into an arraly where the array keys are the id’s and the values are the parents, so with in the while loop for mysql, something like this: $testarray[$id] = $parent_id;
  2. Then I run it through the functions below, and it orders it just how I need it.

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