I am quite the database noob 🙁 If I have a simple table designed like so:
CREATE TABLE IF NOT EXISTS picture
(
ID INT NOT NULL AUTO_INCREMENT,
userID INT NOT NULL,
name VARCHAR(150),
PRIMARY KEY(ID),
FOREIGN KEY (userID) REFERENCES user(ID)
)ENGINE=InnoDB
and described, for example, like so:
+----+--------+------+
| ID | userID | name |
+----+--------+------+
| 1 | 1 | john |
| 2 | 1 | jack |
| 3 | 2 | amir |
| 4 | 2 | chan |
| 5 | 2 | jose |
| 6 | 3 | jane |
| 7 | 3 | buba |
+----+--------+------+
How would I design a database which meets the following two constraints:
- Users
1,2and3can add new entries to thepicturestable. - Users
1,2and3can modify only those rows which haveuserIDs1,2and3, respecitvely
I know this might be non trivial, so feel free to ask any additional questions and I will edit this question accordingly.
Drawing off of this answer I put this together:
This assumes you have a
userstable with some entries:This assumes the names in the
userstable matches the database user name as returned bySELECT SUBSTRING_INDEX(USER(), '@', 1).Also, note that this only prevents updates from happening. You’d have to create additional insert/delete triggers as well to prevent creation/deletion of entries.
Finally, this doesn’t prevent someone from changing the userID of their entry in the pictures table, essentially locking them out from further edits. If this matters to you, you can add an additional check in the trigger for that.