Pregunta

Okay i'm creating a little community website. A user joins my site and he has the option to enter his informations upload photos add friends and post to his wall. By now i want to know how to implement the album table.

The album has the following attributes:

albumID
albumName
albumCover
albumDescription
albumDate
albumPrivacy enum
userID
username

Now i want to know how to link albums table with the users table. Every user has its ID and username. The usersId is primary key and the username is unique.
1 user can have many albums. 1 album can belong to only 1 user. How can i do relationships ???

Help please because im not that good at databases and i want to get things done in optimized and secured way.

By now i use usersid and username as attributes in albums table to identify which album belongs to who. like this SELECT * FROM albums WHERE userid='$userid' AND username ='$username'.
Where $userid is value from session variable and $username is value from session variable.

¿Fue útil?

Solución

Is username in the Users table? If so, then you don't need to worry about including it in the Albums table, too.

The usersId is primary key and the username is unique.

Just to clarify, the userID should be a primary key on the Users table, but a foreign key on the Albums table (as matthewh mentioned). "albumID" is the column that should be the primary key for the Albums table.

Your SELECT SQL can also be simplified, as you should not need username in your WHERE clause. I'm going to assume that users can't have multiple usernames, so only stating userID in your WHERE should be sufficient.

However, if you still want to see username in your Albums result set, you can do this:

SELECT a.*, u.username
FROM albums a
INNER JOIN users u ON u.userid = a.userid
WHERE a.userid='$userid';

Also I feel compelled to mention that you should really parameterize your SQL statement (in your PHP code) instead of concatenating your SQL command string together. That will protect it from SQL injection attacks. It's a bigger danger with user input, so using a session variable should be ok. But it's still a good habit to get into.

Otros consejos

The way you've done it is pretty much right. You only need to have the userID column in the album table, because it is a primary key in the user table and thus guaranteed to be unique. Having the username column in the album table is redundant.

You just need to make sure the userID column in the album table is defined as a FOREIGN KEY and of course has an index applied to it.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top