简体   繁体   中英

Fetch latest updates from different tables MYSQL +PHP

I would like to make somehow latest updates script for my webpage. I have several tables in my MySQL database:

TABLES:

  • latest_updates
  • images
  • gallery_images
  • profile_info
  • questions

Example:

  • User1 adds new image to "images" table
  • User2 adds new question in "questions" table
  • User1 adds changes his profile info in "profile info" table

All these tables are containing user_id which is connected to certain user.

Now what is the best solution to make this status updates script when some user updates or inserts new row to any of these tables

I would like to have some sort of script saying:

  • User1 has added new image to his gallery
  • User2 has created new question
  • User3 changed his profile information

Is it to make another table and every new insert in any tables above, also insert the update in that table or try to make some sort of SQL query to join the tables and read the latest?

If the second option is the best could you please give an example?

Cheerz

Create new table user_updates (or some else) with fields:

  • id (autoinc, primary)
  • id_user
  • id_dest (destination table id)
  • table_dest (destination table name)
  • action (modify/create)
  • changed (timestamp, when happened)

Then you can retrieve all newest rows from this table and show recent updates. You can also join this table to "real" data and show what has been modified.

The easiest way would be to create a new table which would record when things are created/edited. If you prefer the harder route.. I would break down each section into it's own SQL query, and order it by the latest SQL timestamp.

eg to display the latest updates to images:

$sql="select * from images ORDER BY TIMESTAMP ASC";
$stmt = $connection->prepare($sql);
$stmt->execute();
$res = $stmt->get_result();
$latestimages = $res->fetch_array(MYSQLI_ASSOC);
echo $latestimages['user'] . " has uploaded a new image!";

Doing it this way has some advantages, for example if you had content boxes on your page each with its own header eg Latest Images, Latest Forum Posts, Latest Blog Updates etc you could use code similar to this and just add a LIMIT to the SQL query. (to display latest 5 results, add a LIMIT of 5)

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