简体   繁体   中英

How should I store the data of the liked pages by a user into Mysql database

I have used the Facebook PHP SDK to fetch the pages user likes.

$liked = $facebook->api('/me/likes');

After decoding the JSON I get the output array something like this:

Array ( 
[data] => Array ( 
[0] => Array ( [category] => Book [name] => Steve Jobs by Walter Isaacson [id] => 152707268157952 [created_time] => 2012-12-05T15:10:14+0000 ) 
[1] => Array ( [category] => Internet/software [name] => Evernote [id] => 30670583128 [created_time] => 2012-11-24T04:39:25+0000 ) 
[2] => Array ( [category] => Product/service [name] => HTC [id] => 112176482203770 [created_time] => 2012-11-15T06:36:59+0000 )
....
....
....
)

I want to store the category and name of every page the user has liked into the database table. I want to store it in such a way that I can efficiently compare two users, and get mutually liked pages. For example: When a user wants to compare the books in common with another user, the user can get the mutually liked books.

How should I store the data from the array into the table in such a way that I can use it later for comparisons.

Create a table ( liked_pages ) with columns for all the data you wish to store:

  • user_id
  • category
  • name
  • id
  • created_time

Store the data from your array in this table.

Then given two user_ids (for this example, let's say 1 and 2 ), to find mutually liked pages you could do the following:

SELECT id FROM liked_pages
WHERE user_id IN (1,2)
GROUP BY id
HAVING COUNT(id) = 2

If you wanted to extend this to only find mutually liked pages in a certain category (let's say 'books'), you would add an additional where clause category = 'books' .

Edit:

To expand on the questions you are asking in the comments, it is best practise to store only one record per row in a database table as this allows you to search and sort for relevant records when retrieving data, something which database engines are optimised for.

The alternative to this would be to serialize the array and store only one entry per user and then retrieve the array from the database, unserialize it and then do all of the searching/sorting in PHP but this would be less efficient.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM