TableServer dynamic query based on login user

TableServer dynamic query based on login user

YoDavishYoDavish Posts: 123Questions: 46Answers: 3

On the tableserver.php, currently, I have it where the query will search on the $_Session['currentUser'] and this works fine. However, if I have a specific user (for instance 'Admin'), I've tried disabling that where clause so that it would show all the data but I get an error. Is there a way to do if and then for the queries based on a user? My original code below:

// Build our Editor instance and process the data coming from _POST
Editor::inst( $db, 'table', 'id' )
->fields(
Field::inst('AssignedTo'),
Field::inst('Note'),
Field::inst('Completed')
)
->where( 'Completed', NULL )
if($_SESSION['currentUser'] != 'Admin') {
->where( 'AssignedTo', $_SESSION['currentUser'])
}

This question has accepted answers - jump to:

Answers

  • wblakencwblakenc Posts: 77Questions: 17Answers: 1
    Answer ✓

    Im thinking you are looking for an ->and_where instead of just a ->where.

    The way I read your code the SQL would look something like the following (if the user was NOT an admin):

    select [whatever]
    from [table]
    where Completed = NULL
    where AssignedTo = "[current user]"
    

    I am not a PHP expert, but I am thinking if you used the ->and_where instead it would look something like the following (if the user was NOT an admin):

    select [whatever]
    from [table]
    where Completed = NULL
    and AssignedTo = "[current user]"
    
  • allanallan Posts: 61,734Questions: 1Answers: 10,111 Site admin
    Answer ✓

    Your PHP syntax is invalid. The idea is right though. Try:

    ->where( 'Completed', NULL )
    ->where( function $(q) {
      if ($_SESSION['currentUser'] != 'Admin') {
        $q->where( 'AssignedTo', $_SESSION['currentUser']);
      }
    })
    

    Or:

    $editor = new Editor( ... );
    
    $editor->where( 'Completed', NULL );
    
    if ($_SESSION['currentUser'] != 'Admin') {
        $editor-where( 'AssignedTo', $_SESSION['currentUser']);
    }
    
    $editor->process(...)->json();
    

    The first one works by using an anonymous function and adding an extra condition if needed (since its a function we can run logic checks).

    The second one works by simply breaking the chain rather than using one long chained method set.

    Regards,
    Allan

This discussion has been closed.