We have a cars database and a few users. We want to handpick users that are able to view/edit/delete specific cars. We'll show how this can be done with the help of cross-reference table.

Posted Image

CarsUsers is a cross reference table. It stores relations between users and cars. If you want to provide an access to certain cars for certain user simply add a new record to CarsUsers specify correct carid and userid.

Posted Image

For instance on the picture above you can see that user #1 (admin/admin) can access cars #1 and #3. Lets write some code now to make this happen.

1. In AfterSuccessfulLogin event we want to save the ID from Users table in session variable.


$_SESSION["user_id"]=$data["ID"];



2. Now in AfterTableInit event we need to restrict access to those cars that are specified in UsersCars for the current user. We do this by adding the following where clause:

$query->addWhere("id in (select carid from UsersCars where userid=".$_SESSION["user_id"].")"); 


This is it. We can logon as user #1 and see cars #1 and #3. Mission accomplished and we only had to write two lines of code.

Posted Image

Post a Comment