How to use a function in multiple forms?

hi everyone,
I have a function listing hierarchical categories I am using it in an update form in admin panel,
and have to copy and rename each time when need to use in another page.
I want to know how to use it in multiple pages and in li or option without copying it again and again :frowning:

here is the function

$stmt = $conn->prepare("SELECT cat_id, cat_name, seo_url FROM categories WHERE parent_id = ?");
    function list_categories($stmt, $parent_id = 0){
    $stmt->reset();
    $stmt->bind_param('i', $parent_id);
    $stmt->execute();
    $stmt->bind_result($cat_id, $cat_name, $seo_url);
    $cats = array();
    while($stmt->fetch()) $cats[] = array('cat_id' => $cat_id, 'cat_name' => $cat_name, 'seo_url' => $seo_url);

    foreach($cats as $row) { //use rows instead cats
        echo'<ul>';
            echo'<li><a href="'.htmlspecialchars($row['cat_id']).'-'.htmlspecialchars($row['seo_url']).'">'.htmlspecialchars($row['cat_name']).'</a>';
            list_categories($stmt, htmlspecialchars($row['cat_id']));
            echo'</li>';
        echo'</ul>';
    }
}

First off, I wouldn’t have the function actually do the echoing, I’d have the function return the information that the query produces, and echo it at the point of calling it. That deals with the issue of whether to have the output as a list of selection or whatever.

Basically to make a function callable in several situations, you need to convert as much of the hard-coded bits to parameters as you can. By preparing the query outside of the function you do that, but then you add a requirement to always use $parent_id as the parameter, which might not always be the case. If it is, then that’s fine. You can gradually change things to parameters as you see how the function needs to change between the different usages. An sometimes you’ll get to a point where making the function cover all the things you want it to makes it too complex, that’s the point to have more than one function.

2 Likes

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.