Fetch latest updates from different tables MYSQL +PHP - 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.
e.g 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 e.g. 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)

Related

Run A Conditional Check On Data From One Table, Prior To Database Submission On Another Table - MySQL

I have a MySQL table that works as a pivot/linking table and it initially contained two columns, both of which were foreign keys. These two columns were a board_id column and an image_id column. This table basically holds the data for when images are allocated to image boards. Obviously a board can hold multiple images, and an image can be be on multiple boards. This table is the called boards_images table. I'm using PHP PDO to update the database.
The Issue
Although a user has to be logged in to add images to the boards, because this data is publicly viewable on the submitting form via value attributes in form elements (i.e. a submit button and an input element) I want to be able to run a check first, to ensure the board (board_id) that the image is being allocated to belongs to the logged in user. A user's user_id is available via a logged in $_SESSION value. If I don't run this check a user could manually make changes to these values in the HTML and add the images to random boards of other users.
My initial approach has been that the boards_images linking table now contains three columns board_id, image_id and user_id which are foreign keys from the boards, images, and users tables respectively.
My question is how do I run the check, to ensure the board_id belongs to the logged in user, prior to adding an image to the board?
The boards table does have the user_id as a foreign key.
The code I'm currently using is below, it uses INSERT IGNORE to prevent duplicates (i.e. it prevents images being added to the same board more than once).
if (isset($_POST['submit-board-name'])) {
$boardIdValue = $_POST['board-name']; // board id value is shown in button's value attribute
$imageIdValue = $_POST['image-id-for-board']; // hidden element that shows image id of selected image
$stmt = $connection->prepare(
"INSERT IGNORE boards_images (board_id, image_id, user_id)
VALUES (:board_id, :image_id, :user_id)"
);
$stmt->execute([
':board_id' => $boardIdValue,
':image_id' => $imageIdValue,
':user_id' => $sessionId
]);
}
Will I need to a do SELECT of joined data first from the boards table?
When deleting an image from the board this is very simple to allocate to the logged in user, because all I need to do is add another condition to the WHERE clause, i.e
"DELETE FROM boards_images
WHERE board_id = :board_id AND image_id = :image_id AND user_id = :user_id"
// do PDO stuff
Question Summary
How do I check that when the board is being allocated an image, this board belongs to the logged in user, prior to allocating the image to that board?
Any help would be amazing.
Well if you say the boards table also have a user_id column...
$stmt = $connection->prepare(
"SELECT user_id
FROM boards
WHERE board_id = :board_id
LIMIT 1"
);
$stmt->execute([':board_id' => $boardIdValue]);
if($stmt->fetchColumn() == $sessionId) {
// The board belongs to the user, add the image
}
else {
// The board does not belong to the user, print error message etc.
}

MYSQL table suggestions

I am new to MySQL and PHP. I am having issues wrapping my mind around how to accomplish something. I am building a site that has basically a forum style post page. Users enter text into a textarea which then posts that text along with a timestamp and $_SESSION['Username'] into a MySQL table titled "campaigns." So the table has postEntry, postName and postDate rows currently.
On this same page that I have the form, I then display the entire contents of the campaigns table into a div. So it can show each post in descending order.
This has been working great for me, but I am now trying to look at the bigger picture and am thinking this is not a good way to do what I need. I basically need the ability to have an endless amount of "campaigns" each with their own set of posts. Then give the user the ability to select which campaign they want to view and show corresponding posts for that campaign in the div.
So the real question is: Is there a way to do this with just one table. Or would each campaign need it's own table in the database?
Add a campaign_id to the POST table and viola!
edit: more info:
you need one table for the campaign like so:
Campaign
-------------
campaign_id
name
then you need another one for all the posts
post
-------------
post_id
campaign_id
post_time
name
this way, each post is associated to a specific named campaign.

How to make a select with 3 tables?

I have 2 tables: tbImages, tbUsers
tbImages has lots of paths of images with unique ids
tbUsers has lots of users with unique ids...
I will code a page that make a delivery of images...This page will show all images ordering by id... The admin will select 7 images to send it to some user by email... I will have to register when and how many times some user has received that image (a 3rd table maybe)...
Here is the problem... I'll have to ORDER images by date of register.. Images already sent have to appear at end of that delivery page...
What is the better way to do this? tbImages has lots of columns one for each user? A 3rd table (tbDelivered) one row each user with column 'images received'? ?How to make this SELECT to show already sent images at end?
A 3rd table relating your imageID to a userID (relational table). Then you can use JOIN statements in your query. For example:
relational_table
imageID
userID
sendCount
Query could be:
SELECT sendCount
FROM relational_table
WHERE imageID = $imageID
AND userID = $userID
That would give you back the number of times that image has been sent to that user.
You will have to create a 3rd table that will contain:
The image ID
The user ID
The quantity
And you will make a select statement that will look like this:
SELECT tbImages.imageID, tbDelivered.quantity
FROM tbImages, tbDelivered
WHERE tbImages.imageID = tbDelivered.imageID;
To show the ones that have not already been delivered you will have to add at the end of it:
AND quantity = 0;
I hope this helps

get last id from table#1 to determen new ID on table#2

I have an old registration system, and a new one. (two tables).
The old system holds an old category, and the new one holds some new categories that couldn't be implemented into the old system just yet.
So moving everything to one of the systems is not an option at the moment.
My problem:
I need to connect the two tables so the ID's operate as "auto increment" and will follow each other somehow.
Here is a scenario:
// table#1 = old system (car)
// table#2 = new system (tractor, truck, marine)
A new car is registered in table#1 and gets the ID : 13579,
then some other vehicle is registered in table#2 and should get the ID : 13580,
and when a new car is registered in table#1 again, it should get ID : 13581.
and so on...
In my mind it goes something like this:
Right before adding the new vehicle into one of the tables, always do a lookup in the other table and check which one is the last/highest ID and do +1 before setting the new ID...
UPDATE 20120614:
Here is one solution I came up with:
$qry_tbl1 = mysql_query('SELECT MAX(id) AS tbl1_max_id FROM tbl1');
$get_tbl1 = mysql_fetch_assoc($qry_tbl1); extract($get_tbl1);
$qry_tbl2 = mysql_query('SELECT MAX(id) AS tbl2_max_id FROM tbl2');
$get_tbl2 = mysql_fetch_assoc($qry_tbl2); extract($get_tbl2);
$new_max_id = max(array($tbl1_max_id,$tbl2_max_id)) + 1;
This is not a good solution, but the only one I got to work.
Immediately after the user hits the submit button, I do this and the INSERT a new record.
Then, further down the script, based on $new_max_id i update that record with additional data...
Is this an acceptable solution?
I think you can use this approach.
Or you can create new table, with such fields:
id (auto increment), table_id, table_name
And save into it table_id - is id for your table entity, table_name - is some attribute, that determines to which table belong this id. During select you have to use this table to determine what id to use. This will avoid id calculations.

Facebook newsfeed in mysql

I want to create a Facebook like newsfeed for my users that basically does the following
it keeps track of the activities of users and their friends
users can see recent friend activities on their newsfeed
but i am not quite sure how best to implement this in mysql. Like what sort of tables will I need? What is the structure of these tables? What will I store in these tables? How will I keep track of user and friends activities. I want to build an efficient system that will scale up. I prefer working with PHP and Mysql if possible!
I was thinking of having a NEWSFEED table and when a user does something (posts a comment, etc), I add an entry to that table for the user's friends and the user himself that will show up on their newsfeed.
The table structure would be as follows
uid INT
activity ENUM
activity_id INT
So let's say I have a comments table with the following structure:
title VARCHAR(255)
message TEXT
If the user posts to that table and an entry with ID=5 gets created for that user, then the following entry will be added to the NEWSFEED table
uid=3 activity="comment" activity_id=5
that means that to display the newsfeed for each user, I would have to do the following:
SELECT * FROM newsfeed WHERE UID = ....
FOR EVERY ROW:
CHECK activity type (if activity == 'comment')
**QUERY the corresponding table and display the result (so I would query the comments table an display the person's comment)**
I am thinking of deleting entries more than >3 months old to prevent the table from getting too huge. But I don't like that I am doing independent queries to display for each activity type (just as I did above where I queried the COMMENTS table to display the comment whose ID is mentioned in the NEWSFEED table).

Categories