Hi,
I'm kind of stumped.
I have a table of items with fields: ID, title, created_by, group.
I also have another table of groups with fields: ID, created_by, group_name
and a final table of users with fields: ID, username, password etc.
The idea is that only items created by the logged in user or items where the logged in user is part of the item's user group can be seen by that user.
Each user can be part of an unspecified number of groups and each group can contain an unspecified number of users.
The only way at the moment that I can think of doing this is to have a separate table for each user (listing all the groups of which they are members).
I then first search the items table for items created by the logged in user.
Secondly, search that user's "groups" table to find the ids of each group to which they belong and then recursively search through the items table again and load each item where the currently found group_id matches the item's group id.
I know this will work if coded correctly for small numbers of items, groups and/or users but I suspect each page would take a long while to load/process for larger tables. It also seems quite messy to have a new table for each user given that you could have thousands of users and therefore thousands of tables.
I suspect that table joins may provide the solution but I don't really see how at the moment. If this is the case I'm perfectly happy to rename the table fields to achieve this.
My current code for retrieving the items is this (I know it's probably not ideal):
$query = "SELECT * FROM items WHERE user_id=:u_id";
$stmt = $conn->prepare($query);
$stmt->execute(array(':u_id'=>$_SESSION['u_id']));
$exist = '<option></option>';
while( $uRow = $stmt->fetch() ) {
$exist .= '<option value="'.$uRow['id'].'">'.$uRow['title'].'</option>';
}
$user_groups_tbl = "user_groups_".$_SESSION['u_id'];
$query1 = "SELECT * FROM $user_groups_tbl";
$query2 = "SELECT * FROM items WHERE group_id=:group";
$stmt1 = $conn->prepare($query1);
$stmt2 = $conn->prepare($query2);
$stmt1->execute();
while( $gRow = $stmt1->fetch() ) {
$stmt2->execute(array(':group'=>$gRow['group_id']));
while( $row = $stmt2->fetch() ) {
if( $row['user_id'] !== $_SESSION['u_id'] ) {
$exist .= '<option value="'.$uRow['id'].'">'.$uRow['title'].'</option>';
}
}
}
return $exist;
I hope my needs and intentions are clear. Any help would be appreciated.