PHP MySQL code optimize -
is there mysql function optimize code? child id getting parent id
function get_parents() { $ids = array(); while($id) : $query = "select placement_id referrals user_id = $id"; $query = $this->db->query($query); $result = $query->row(); if(!isset($result->placement_id)) : break; elseif(isset($result->placement_id) && $result->placement_id == 2) : break; endif; $id = $result->placement_id; array_push($ids, $id); if($result) : continue; endif; break; endwhile; return $ids; }
the code above return parent id of given user_id, stop if nothing found. found code slow , heavy load.
my table
relations table | id | user_id | placement_id | | 1 | 2 | null | | 2 | 3 | 2 | | 3 | 4 | 2 | | 4 | 5 | 3 | | 5 | 6 | 4 | | 6 | 7 | 3 | | 7 | 8 | 3 | | 8 | 9 | 3 | | 9 | 10 | 6 | | 10 | 11 | 5 | | 11 | 12 | 6 | | 12 | 13 | 4 | | 13 | 14 | 3 | | 14 | 15 | 9 | | 15 | 16 | 10 |
user_id child , parent placement_id
you can rewrite code as:
function get_parents() { $ids = array(); while($id){ $query = "select placement_id referrals user_id = $id"; $query = $this->db->query($query); $result = $query->row(); if(isset($result->placement_id) && $result->placement_id !== 2) { $id = $result->placement_id; array_push($ids, $id); } } return $ids; }
it excludes additional function calls such continue,break etc. also, make sure have int type of user_id indexing on column.
Comments
Post a Comment