I currently have a database table setup like so:
| id | thing_id | value
The "thing_id" relates to a unique ID within the same table.
I'm trying to create a function (in PHP) that will run a query against the MySQL database, dump that information into an array, and if "thing_id" is NOT NULL it will loop back and run the query again, and add the information on to the existing array. This will continue until the "thing_id" is NULL.
How can I go about doing this? Btw, I'm designing this on top of WordPress.
The following below works, but I feel like there is some better way to do this. How can I simplify this and make it not hog resources? Here is what I have:
$related_thingsSql = "
SELECT $thingsDB.value, $thingsDB.thing_id, $thingsDB.id
FROM $thingsDB
WHERE $thingsDB.id = '$related_thing_id'
";
$related_things = $wpdb->get_results( "$related_thingsSql" );
foreach ($related_things as $related_thing) {
$related_thing_name[] = $related_thing->value;
$related_thing_id2[] = $related_thing->id;
$related_thing_id = $related_thing->thing_id;
}
while ($related_thing_id != NULL) {
$related_thingsSql2 = "
SELECT $thingsDB.value, $thingsDB.thing_id, $thingsDB.id
FROM $thingsDB
WHERE $thingsDB.id = '$related_thing_id'
";
$related_things = $wpdb->get_results( "$related_thingsSql2" );
foreach ($related_things as $related_thing) {
array_unshift($related_thing_name, $related_thing->value);
array_unshift($related_thing_id2, $related_thing->id);
$related_thing_id = $related_thing->thing_id;
if (empty($related_thing->thing_id)) {
$related_thing_id = NULL;
}
}
}
$related_things_length = count($related_thing_name);
for ($x = 0; $x < $related_things_length; $x++) {
echo ' > <a href="' . site_url() . '?id=' . $related_thing_id2[$x] . '">' . $related_thing_name[$x] . '</a>';
}