0

How do you update a database with new info but keep old info aswell?

My aim is to have a favorites button that when clicked it will add the item id to a members favorites list so they could call something like fav.php?fav=janedoe and their favorites list be listed.

I know how to add the button and get the item id from database I just really need the mysql query I would run to update aswell as what the "type" would be when creating the database column I think.

info inside the row would then look like this

1,12,14,15,34,46,74

then if member wanted to add item 98 it would update to

1,12,14,15,34,46,74,98

adding 98 to the end.

I realise this is kind of a "can you do this for me" post, but I just haven't a clue where to start.

4

4 回答 4

2

You should create a new table called something like:

MembersFavoritePage:

  • MemberId.
  • PageId.
  • ...

Then whenever the user mark a page as a favourite page do an insert into this table.

于 2012-10-30T13:33:36.217 回答
1

IF you do want to maintain the string you could do this in the query:

UPDATE `table`
SET `fav` = CONCAT(`fav`, ",98")
WHERE `id` = 1234;

Or do the concat in PHP and just update with that - i.e. get existing string first - but that means 2 queries.

But the separate table is best as suggested by @MahmoudGamal. As this is difficult to 'remove' items from... you'd need to do the manipulation PHP-side.

于 2012-10-30T13:42:03.907 回答
1

You should not save comma separated values in single column. It is a violation of First normal form

Check below answer for broader explanation:

Is storing a delimited list in a database column really that bad?

The best approach is to create separate table as suggested by @Mahmoud Gamal which is easy to maintain in long run.

于 2012-10-30T13:42:48.563 回答
-1

What about creating a table "favs" in which you can store the id and the user who added it to his favs'list?

ID | USER_ID
------------
5  | user_1
6  | user_1
8  | user_2
6  | user_2

select ID from favs where USER_ID = "user_1"

this will get pages'id for user_1.

Remember you'll need to manage the insert/update/delete for this table, if the user needs to add/remove a fav page.

An easier solution could be having a favs pages field in the user's detail

USER_ID| FAVS
-------|-----
user_1 | 5*6
user_2 | 8*6

By using this solution, you will able to easily parse the favs field and get info about the pages (in this case you'll just need to parse the string).

When you'll need to update or remove any page from a user favs'list, you can just parse the string, remove the page id you want to delete or append the new page to the string.

The cons in this case will be you will not be able to find a fav page easily (you'll end up using LIKE construct).

于 2012-10-30T13:48:21.703 回答