tags:

views:

44

answers:

2

I want to update a MySQL table with information from two other tables. I'll set up a cron job, but I don't know what PHP code to use.

Every time the cron job runs, I want the 'VideoNumber' column from the 'Profiles' table to be updated with the amount of videos they've uploaded to the site. Video information is stored in a table called 'Videos', and each video has an 'OwnerID' to identify the user who uploaded it. This corresponds to the 'ID' column in the 'Profiles' table.

I also wanted the 'PhotoNumber' column in the 'Profiles' table to be updated with the amount of photos the same user has uploaded - photo data is stored in the 'Photos' column.

Can anybody help?

A: 

You must first SELECT data from those two tables, assign certain data to the INSERT and pass it on.

Tomasz Kowalczyk
The OP wants to update the Profiles table.
Guillaume Bodi
A: 

You're doing it wrong. Update values of those columns immediately after new video/photo is created/deleted. You can enclose everything within transaction to make sure that everything will be fine:

BEGIN TRANSACTION;
INSERT INTO videos VALUES (...);
UPDATE profiles SET videosCount = videosCount + 1 WHERE id = ?;
COMMIT;



BEGIN TRANSACTION;
DELETE FROM videos WHERE id = ?;
UPDATE profiles SET videosCount = videosCount - 1 WHERE id = ?;
COMMIT;

Do the same for photos.

You can even use triggers to make everything clearer (ie. let database handle increase/decrease count columns' values)

DELIMITER \\
CREATE TRIGGER abc AFTER INSERT ON videos
FOR EACH ROW BEGIN
   UPDATE profiles SET videosCount = videosCount + 1 WHERE id = NEW.profile_id;
END\\

DELIMITER ;
Crozin
The INSERT trigger works. What trigger would I use for when videos are deleted?
Jamie
I figured it out, you replace "+ 1" with "- 1" and "NEW.profile_id" with "OLD.profile_id". Thanks
Jamie
P.S., if anybody is reading this problem - I really recommend changing the PHP code like Crozin suggested. Triggers are okay, but they're more of an easy hack in my opinion. Also, to my incredulity, some hosts refuse to allow you to create triggers on phpMyAdmin via SQL command. Unless you buy a VPS or dedicated server package, of course...
Jamie