How to add multiple registries in a table mysql and php - php

I have two tables:
Users
uid [pk]
Transactions
uid[fk]
amount
With a one to many relation between both of the tables, so now I want to add all the transactions for every user and show them in a table like this:
UID -> balance
Idon't really know how can I make do this for every user in my table...
Any ideas?
I don't want to store the results, I just want to show them on a table, and after that I'll export that table to Excel.

This SQL query will do the trick:
SELECT uid, SUM(amount) FROM Transactions GROUP BY uid

Related

Copy rows in MySQL table multiple times and adding additional column

I have created MySQL table in database. Table name is products and the columns are( prodict_id(pk) product_name and pack_size) as shown in the figure below.
What I want to do is , copy all the rows in the table and add additional information in additional column called (buyer_name) so each product is associated with a specific buyer which makes it unique
Is there a way I can achieve this using query? Where I can give a list of buyers and it attaches it to all rows in table?
p.s I have almost 700 rows in my table and I have 12 buyers, so if I do it manually, it will consume too much time
As per your comment your buyer details are in a table and you want to map each product with each of the buyer then you can write your insert query like below:
insert into newtable
select t1.*, t2.buyername from products t1 join buyers t2
DEMO
You can use where clause also to filter some results from either of the table.
It seems you want to automate the data insertion from product table to buyer table. How about, if you select that fetches all the buyers first and then you insert into buyer table.
It can be based on subquery where insert is the outer one and select is the nested one.
Good luck !

Update rows while counting rows in other tables

I would like to know if its possible to solve the following action with just one SQL-statement:
Table A: User-Table
Table B: Entries with foreign-keys for users
The relation between table A and Table B is 1 -> *
Because I don't want to count entries in table B for a specific user every time, I want to keep a column for this count in the user table. For that I would need a query that updates this column for each user.
Is this possible?
You can try this: UPDATE USERS U SET COUNT_ENTRIES=(SELECT COUNT(*) FROM ENTRIES WHERE USERID=U.ID)

Recalculate values in MySQL tables

I have a web application that stores points in a table, and total points in the user table as below:
User Table
user_id | total_points
Points Table
id | date | user_id | points
Every time a user earns a point, the following steps occur:
1. Enter points value to points table
2. Calculate SUM of the points for that user
3. Update the user table with the new SUM of points (total_points)
The values in the user table might get out of sync with the sum in the points table, and I want to be able to recalculate the SUM of all points for every user once in a while (eg. once a month). I could write a PHP script that could loop through each user in the user table and find the sum for that user and update the total_points, but that would be a lot of SQL queries.
Is there a better(efficient) way of doing what I am trying to do?
Thanks...
A more efficient way to do this would be the following:
User Table
user_id
Points Table
id | date | user_id | points
Total Points View
user_id | total_points
A view is effectively a select statement disguised as a table. The select statement would be: SELECT "user_id", SUM("points") AS "total_points" FROM "Points Table" GROUP BY "user_id". To create a view, execute CREATE VIEW "Total Points View" AS <SELECT STATEMENT> where SELECT STATEMENT is the previous select statement.
Once the view has been created, you can treat it as you would any regular table.
P.S.: I don't know that the quotes are necessary unless your table names actually contain spaces, but it's been a while since I worked with MySQL, so I don't remember it's idiosyncrasies.
You have to user Triggers for this, to make the users total points in sync with the user_points table. Something like:
Create Trigger UpdateUserTotalPoints AFTER INSERT ON points
FOR EACH ROW Begin
UPDATE users u
INNER JOIN
(
SELECT user_id, SUM(points) totalPoints
FROM points
GROUP BY user_id
) p ON u.user_id = p.user_id
SET u.total_points = p.totalPoints;
END;
SQL Fiddle Demo
Note that: As noted by #FireLizzard, if these records in the second table, are frequently updated or delted, you have to have other AFTER UPDATE and AFTER DELETE triggers as well, to keep the two tables in sync. And in this case the solution that #FireLizzard will be better in this case.
If you want it once a month, you can’t deal with just MySQL. You have too « logic » code here, and put too logic in database is not the correct way to go. The trigger of Karan Punamiya could be nice, but it will update the user_table on every insert in points table, and it’s not what you seem to want.
For the fact you want to be able to remove points, just add bsarv new negated rows in points, don’t remove any row (it will break the history trace).
If you really want it periodically, you can run a cron script that does that, or even call your PHP script ;)

Alternative solution for PHP/SQL max array size problem

I have a table bundled among 100 databases in MYSQL (i.e. 1st x rows of the table in database_1, 2nd x rows of the table in database_2, ... , last x rows of the table in database_100)
Each table has a row whenever a user visits a friend for a game.
The columns are iuin, logtime, beuin.
iuin is the user id of the visitor.
beuin is the user id of the friend who was visited.
logtime is when the visit was made.
I would like to find the # of distinct friends who were visited during a week.
There is roughly 300k distinct users who are visited per day.
However, when I extended my code to calculate for a week, I ran out of memory.
My code basically does an SQL query using SELECT DISTINCT beuin for a selected week for the table in each database. I store all the beuin in an array if it's not already stored (so I count distinct friends who were visited), and return the size of the array at the end.
FYI, I can't edit the database around such as joining all the tables in different databases into one table.
Is there any alternative ways i can do this?
Thanks
It's hard to say anything about your without the one. But I think you can solve this problem using mysql. My quick solution:
Create table - CREATE table if not exist users_ids(user_id INT NOT NULL DEAULT 0 PRIMARY KEY(UNIQUE)); in the first db
Truncate users_ids
Run 100 queries like INSERT IGNORE INTO db1.users_ids select distinct user_id from db1.table1;
Select count(*) from users_ids;

how to connect two mysql tables in which I am inserting data in same time

How to connect two mysql tables in which I am inserting data in same time?
I have table customers which is my app table, and I have user which is used by library I use for my framework, this library handles users and authorization.
I wanted to have user_id (which is id from user) in customers, but I am creating those two tables in same time.
Any ideas? Thanks!
the php command mysql_insert_id gives you the id of the last record inserted into a table. So from my undestanding if your inserting a user you could get the id then insert that into another table?
http://php.net/manual/en/function.mysql-insert-id.php
Or have I understood your question wrongly?
It is simply not possible. Nothing can happen at the same time in a program.
What is possible is to:
Start a database transaction
perform your first query
retrieve the table's key; if it's an autoincrement, there are built-in ways to retrieve the last inserted key in every database API
perform your second query using the retrieved key as a parameter
Commit the transaction; But if an error occurred, you need to rollback the whole transaction
This is how it is done, and it behaves exactly like you want it to.
How about a link table?
users_customers
user_id | customer_id
=====================
1 | 648785552
5 | 145778304
4 | 654566055
You can then join the tables together using this table, for example like this:
SELECT users.name, customers.address
FROM users
JOIN users_customers
ON users_customers.user_id = users.id
JOIN customers
ON users_customers.customer_id = customers.id

Categories