Get all possible parent ids only if has parent bigger than 0
I have a way to do it in one query, though it may not be faster than your current solution.

DELIMITER $$

CREATE DEFINER=`root`@`localhost` FUNCTION `get_parent_id`(`id` INT) RETURNS varchar(1024) CHARSET utf8
    DETERMINISTIC
BEGIN
    DECLARE return_string VARCHAR(1024);
    DECLARE return_string_separator CHAR(1);
    DECLARE parent_id INT;

    SET return_string = '';
    SET return_string_separator = '';
    SET parent_id = id;

    WHILE parent_id &gt; 0 DO

        SET parent_id = (
            SELECT
                forum_parent_id
            FROM
                forums
            WHERE
                forum_id = parent_id and forum_parent_id not in (Select forum_id from forums where forum_parent_id=0)
        );

        IF (parent_id &gt; 0) THEN
            SET return_string = CONCAT(return_string, return_string_separator, parent_id);
            SET return_string_separator = ',';
        END IF;

    END WHILE;

    RETURN return_string;
END$$