php If statement as part returned value inside of a function

I have a function to see what a user's role is. It works great on it's own in the html document. But I have several functions that connect to a database and print information. I want certain parts of the function to be available to all users and some only to admin. Right now it is printing <?php ?> in the source file.

function isUserInRole($userRole){
    $retVal = false;

    if ($userRole == $_SESSION['role']) {
        $retVal = true;
    }

    return $retVal;
}

This works fine in the html document:

<?php if(isUserInRole('Admin')){ ?>
    <?php print "<a href='edit/staffDetailsForm.php?ID=$staffId'><button>Edit &gt;</button></a>" ?>
<?php } ?>

Here is a function that is not working:

function getLabelCodes ($staffId, $staffName, $compId){
    $retVal = "";

    include "inc/DBconnect.php";

    $query = "SELECT l.listName, l.listCode FROM labels AS l INNER JOIN agtLabels AS al ON l.listCode = al.listCode WHERE al.staffId = $staffId AND al.compId = $compId";

    if ($result = $mysql->query($query)) {
        while ($aRow = $result->fetch_assoc()) {

            $listCode = $aRow['listCode'];

            $retVal = $retVal . "<li class='remove'><form action='delete/removeStaffLabel.php' method='post' onsubmit='return confirm('Do you really want to remove" . $staffName . "from " . $listCode . "?')'>";
            $retVal = $retVal . $aRow['listName'] .

                " <input type='hidden' name='staffId' value='" . $staffId . "' />
                    <input type='hidden' name='compId' value='" . $compId . "' />
                <input type='hidden' name='listCode' value='". $listCode . "' />
                <input class='remove' type='submit' value='Remove from "  . $aRow['listName'] . "' />
                </form>
                </li>";
        }
    } return "<?php if(isUserInRole('Admin')){ ?><h3>Label Lists:</h3><a href='edit/staffLabels.php?staffId=" . $staffId . "&compId=" . $compId . "' /><button>Add to Label list</button></a><ul>" . $retVal  . "</ul><?php } ?>";

    $mysqli->close();

}

I have tried placing the<?php if(isUserInRole('Admin')){ ?> bit in the return (as it is now) as well as part of $retVal. I have to find a way to fix it within the function because I have many other functions that are similar and I have no real way of breaking them up further.

The source-code prints </contact><comments></comments><?php if(isUserInRole('Admin')) { ?><h3>Label Lists:</h3>. How do I get isUserInRole() to perform it's action prior to the page load being complete?

Any help would be greatly appreciated.

1 answer

  • answered 2017-10-23 23:24 Cayo Henrique Rodrigues

    You can do it inside your function:

    if(isUserInRole('Admin')){
        return "<h3>Label Lists:</h3><a href='edit/staffLabels.php?staffId=" . $staffId . "&compId=" . $compId . "' /><button>Add to Label list</button></a><ul>" . $retVal  . "</ul>"
    }