So I have this script that needs to Update total uploads per user and store into the users table.
I have a function that can count the number of uploads made by each user but not stored into database, my site is already live and a busy site that I can't update this manually since the posts are non-stop.
Below is my function to count the uploads...
function get_row_count($table, $suffix = "") {
$res = SQL_Query_exec("SELECT COUNT(*) FROM $table $suffix");
$row = mysql_fetch_row($res);
return $row[0];
}
The users table looks like this
[users table]
id username numuploads numcomments
the uploads table looks like this
[uploads table]
fileid userid added enabled
So how can I run an SQL query to count the number of uploads per user from the uploads table and update it into each user's numuploads at once without doing it manually.
Thanks..
EDIT
UPDATE users SET numuploads = (SELECT COUNT(id) as numuploads FROM uploads WHERE owner = users.id)
Problem is solved now
Instead of selecting the the count as a separate query, then adding 1 and updating some DB column, You could do directly the update only:
UPDATE table SET number = number + 1 WHERE id = <ID>
This query should be run each time when a new comment/upload is done by that user and requires the number column to be of numeric type with default value set to 0 (zero). The above query is just an example that You should change to meet Your DB scheme.
Related
I have a check-in / check-out system which writes for every check-in a new row in my table and updates the table when the person checks out (like checkedout = 1)
Now I'm making a new site that always shows the newest checked in person. I do it by polling and storing the highest ID on a variable on that page. In the polling I search for entries > the id i stored. It's working good so far.
But now I want to extend it and show either the latest checked in person OR the latest checked out person. How can I get the last "updated" row in my table?
You can add a column for ex. date_checked of type datetime and update it whenever something happens.
After that just select by that column.
use mysql function called mysqli_insert_id() which will give you last inserted primary key value of the table
try this:
SET #update_id := 0;
UPDATE some_table SET column_name = 'value', id = (SELECT #update_id := id)
WHERE some_other_column = 'blah' LIMIT 1;
SELECT #update_id;
More Click Here
So, I have a table A that each time a user sends an image, a record is created storing the time it was uploaded, the username of the user and the image number out of all the images uploaded over time.
I need to make a second table B that will store the amount of images uploaded per user and the user name. I need this table B to be updated when a new entry is generated in A.
I found that a trigger function can be created, nevertheless I'm having a rough time finding an example that will suit my needs.
Does anyone know a way of doin what I want?
Just update b table with a select count of total inserted records on a from current user NEW.userid (userid is your column name or whatever name you have there, and NEW is a fixed mySql reference for the current values to be inserted):
CREATE TRIGGER img_sum AFTER INSERT ON a
FOR EACH ROW SET b.total = (SELECT COUNT(*) FROM a WHERE a.userid=NEW.userid)
WHERE b.userid = NEW.userid;
From what you have described i don't think you need a second table. You can just count the number of time a user name has occurred, and you will get the number of images that user has uploaded.
You can get the count doing something like that
SELECT COUNT(DISTINCT username) FROM table_name;
If you still need to create 2 tables, you might want to take a look at procedures and how they work.
Let's say we have 3 tables for this case:
- users(id, username, email ....),
- user_images(id, userId, image_num, date_uploaded)
- user_images_count(id, user_name, images_count)
The user_images_count is initially empty. We have to fill it up by such query:
INSERT into user_images_count(user_name, images_count)
SELECT (select username from users where ui.userId = id) as username, count(userId) as counter FROM `user_images` ui group by ui.userId;
Then, we must immediately create the trigger that will process every INSERT operation into user_images table.
CREATE TRIGGER `count_user_images` AFTER INSERT ON `user_images`
FOR EACH ROW begin
declare u_name tinytext default "";
set u_name = (select username from users where id = NEW.userId limit 1);
if(u_name != "") then
update user_images_count set images_count = images_count + 1 where user_name = u_name;
end if;
end
This two queries (user_images_count fulfillment and trigger creation must be performed in one transaction, one by one).
I've created similar triggers on my local databases. They work pretty good. )))
I have a single-column MySQL database table ids (id INTEGER PRIMARY KEY AUTOINCREMENT) where I store pre-generated unique ids in an ascending order. In order to get a random id from that table I use this query:
SELECT id FROM ids ORDER BY RAND() LIMIT 1;
And now I am wondering how to ensure that the id I got is never used again. I see two options. One is to delete the id from the table and the other is add a column tracking the use of that id:
DELETE FROM ids WHERE id=?; //where id is the one I got from the previous query
or
SELECT id FROM ids WHERE used=0 ORDER BY RAND() LIMIT 1;
UPDATE ids SET used=1 WHERE id=?; //where used is new column with 0 as default value
There is only a slight problem with both of these. If the server load is heavy then two queries for a random id might return the same id before it gets removed from the list (or disabled with used column).
Would transaction help?
Wrapping your select and your update in a transaction will work. If you want to avoid a transaction as well as the race condition between selecting your item and marking it unusable, you can run the UPDATE first. You'll need a way for each of your processes to identify itself as the owner of the row between claiming it and deletion. For example, assume your ids schema is
id (integer)
owner (string)
Have each process pick a UUID (or something else suitably unique) and run the following:
UPDATE ids SET owner = $process_id WHERE owner IS NULL ORDER BY RAND() LIMIT 1
SELECT id FROM ids WHERE owner = $process_id
DELETE FROM ids WHERE id = $selected_id (or otherwise mark it used)
Step 1 atomically claims the row for the process so that no other process can claim it. Step 2 pulls out the claimed ID. Step 3 removes the ID from the available set for good. If Step 3 doesn't delete the row, just marks it used, make sure you clear owner as well so your process won't select it again later.
Add an extra column to your ids table. Let us say selected. You will update this column when it is generated in your randomized query.
1 for selected and 0 for not yet.
For example
SELECT id FROM ids ORDER BY RAND() WHERE selected = 0 LIMIT 1;
$id = $row['id']; /* STORE THE SELECTED ID TO A VARIABLE */
Then update the table with
UPDATE ids SET selected = 1 WHERE id = $id
So that your next run of your randomized query will only get the row of selected 0 value, and not the one with 1 value.
you could try updating the id 1st before selecting it. try this one.
-- get firstID
SELECT #MinID:=id FROM ids ORDER by id ASC LIMIT 1;
-- get last id
SELECT #MaxID:=id FROM ids ORDER by id DESC LIMIT 1;
-- get random id
SELECT #rndomID :=ROUND((RAND() * (#MaxID-#MinID))+#MinID);
-- update first
UPDATE ids SET used=1 WHERE id=#rndomID;
-- select the id
SELECT id FROM ids WHERE used=0 WHERE id=#rndomID;
This might sound quite stupid, but whats the best approach to count a users db entries of today, so I can publish the most activate member with mysqli?
Thanks..
Edited; Current code
$promote_amount_posts = mysqli_query($mysqli,"SELECT COUNT(rec_by_id) FROM posts LIMIT 1 ");
$row = mysqli_fetch_assoc($promote_amount_posts);
$promote_amount_posts = $row['COUNT(rec_by_id)'];
$most_active_user_id = $row['rec_by_id'];
Lets say my user_id (which goes into the rec_by_id column) is 82392 and I created 20 posts. There should be atlease MY 20 posts in the 'posts' table. How do I fetch my user_id so I can echo it anywhere?
The following query should return the count in today_db_entries as long as you have a created column and a id column - swap out those names for whatever your schema uses.
SELECT COUNT(id) as today_db_entries
FROM table
WHERE created BETWEEN getdate() AND getdate()-1
im having a problem with a small issue within this query
$update = mysql_query("UPDATE earnings SET userid = (SELECT ID FROM users WHERE installid is NOT NULL ORDER BY rand() LIMIT 1) WHERE userid='0'");
this query update the userid within the earning table when it value of '0'
what i need to do is to update the userid where its not found within the user table
for example
Earnings table has 5 entries where userid=10
the userid 10 is not found with in the users table and users table have those ids (1'2'3'4'5)
then update this userid which have the value 10 with any of the ids found within the users table and have the installid not nulled
I'd imagine a customer would want their earnings data, of all things, to be relevant, not completely random (if some if the data is random and you don't know which, all of the data is corrupted). That said, the query gets you where you want with
UPDATE earnings SET userid = (SELECT ID FROM users WHERE installid is NOT NULL ORDER BY rand() LIMIT 1) WHERE userid NOT IN (SELECT ID FROM users)
What I'd do instead is put a foreign key on the ID and prevent the random data being written in in the first place. I cannot see a solution where having random IDs would be better than not having those rows at all. If the IDs are not important, why have them at all?