php pdo copy column between tables - php

I got the two tables(Table1 and Table2):
Table1:
id hits url
1 11 a
2 5 b
3 6 c
4 99 d
5 14 e
Table2:
id url 2014.04.13 2014.04.14
1 a 0 5
2 b 0 1
3 c 0 3
4 d 0 60
5 e 0 10
hi all,
Table1 one contains the actual hits(which are always up-to-date) and Table2 to statistics(which are done every day at midnight). The columns id(unique number) and url are in both tables the same. So they got the same amount of rows.
So i create every day a new column(with the date of today) and copy the column hits from the table 'Table1' into the new created column into the table 'Table2'
First i alter Table2:
$st = $pdo->prepare("ALTER TABLE Table2 ADD `$today_date` INT(4) NOT NULL");
$st->execute();
Then i cache all entries i need from Table1:
$c = 0;
$id = array();
$hits = array();
$sql = "SELECT id, hits FROM Table1 ORDER BY id ASC";
$stmt = $pdo->query($sql);
while($row = $stmt->fetch(PDO::FETCH_ASSOC))
{
$id[$c] = $row['id'];
$hits[$c] = $row['hits'];
$c++;
}
At last i update Table2:
for ($d = 0 ; $d < $c ; $d++)
{
$id_insert = $id[$d];
$sql = "UPDATE DOWNLOADS_TEST SET `$datum_det_dwnloads`=? WHERE id=?";
$q = $pdo->prepare($sql);
$q->execute(array($hits[$d], $id[$d]));
if($q->rowCount() == 1 or $hits[$d] == 0) // success
$hits[$d] = 0;
else // error inserting (e.g. index not found)
$d_error = 1; // error :( //
}
So what i need is to copy(insert) a column from one table to another.
The two tables are having ~2000 elements and the copying as described above takes around 40 sec. The bottleneck is the last part (inserting into the Table2) as i found out.
One thing i found is to do multiple updates in one query. Is there anything i can do besides that?

I hope you realise that at some point your table will have irrational number of columns and will be highly inefficent. I strongly advise you to use other solution, for example another table that holds data for each row for each day.
Let's say you have a table with 2000 rows and two columns: ID and URL. Now you want to know the count of hits for each URL so you add column HITS. But then you realise you will need to know the count of hits for each URL for every date, so your best bet is to split the tables. At this moment you have one table:
Table A (A_ID, URL, HITS)
Now remove HITS from Table A and create Table B with ID and HITS attributes). Now you have:
Table A (A_ID, URL)
Table B (B_ID, HITS)
Next move is to connect those two tables:
Table A (A_ID, URL)
Table B (B_ID, A_ID, HITS)
Where A_ID is foreign key to attribute "A_ID" of Table A. In the end it's the same as first step. But now it's easy to add date attribute to Table B:
Table A (A_ID, URL)
Table B (B_ID, A_ID, HITS, DATE)
And you have your solution for database structure. You will have a lot of entries in table B, but it's still better than a lot of columns. Example of how it would look like:
Table A | A_ID | URL
0 index
1 contact
Table B | B_ID | A_ID | HITS | DATE
0 0 23 12.04.2013
1 1 12 12.04.2013
2 0 219 13.04.2013
3 1 99 13.04.2013
You can also make unique index of A_ID and DATE in Table B, but I prefer to work on IDs even on linking tables.

Related

Php Mysql sum over 2 colums and select from 2 tables

I have a MySQL database with 3 tables.
Table player
P_id = content (1, 2, 3,)
P_name = content (Spieler1name, Spieler2name, Spieler3name)
Table tournament
T_id = content (1, 2)
T_date = content (2018, 2019)
T_players = content (123, 123)
Table Games
G_id = content (1, 2)
G_tournament_id = content (T_id from table tournament)
G_player_away = Content (as an example user id 1)
G_player_home = content (as an example user id 2)
G_player_away_points = Content (11)
G_player_home_points = Content (8)
The Games table has even more data.
Now I want to create a table with PhP as ranking.
Place name points
Spieler1name 11
Spieler2name 8
Spieler3name 4
....
Can someone tell me how the php query from the mysql database works? I tested this but it doesn't work.
SELECT SUM(G_player_away_points) AS total FROM Games
UNION
SELECT SUM(G_player_home_points) AS total FROM Games
GROUP BY G_player_away
In the code above, he also sums the points from the opponent. This is of course not correct, it should only the points obtained by him appear in the output with php table. Furthermore you have to get the name from the table players. Can someone help me?
If you are using single table and multiple column for sum then you should try with this
SELECT SUM(G_player_away_points + G_player_home_points) AS total FROM Games
GROUP BY G_player_away

I want to subtract 2 columns of two different tables

tbl_blood:
id|qty
1 14
2 15
3 16
tbl_blood_list:
id|blood_quantity
1 1
2 1
3 1
My question is the tbl_blood table's column qty should subtract the blood_quantity column in tbl_blood_list's table. I need codes that I can implement in my php mysqli.
I have tried this code but it really cannot work:
$add_inv = "UPDATE tbl_blood
SET qty=(qty - '$blood_quantity')
WHERE id='$minus_blood_id' ";
If i m not misjudging your question so you want to update join but in your table structure i can't find any common column if there is Any common column in both table so you can join and update your table in one statement i think id are common in both table if yes so try this
$pdo->query("UPDATE tbl_blood AS tb JOIN tbl_blood_list AS tbl ON (tbl.id = tb.id) SET tb.qty = (tb.qty - tbl.blood_quantity)")
Please let me know if there is any problem or i misjudge your issue
Hope it's help you.
There are more efficient ways to handle this kind of situation, you should consider a different structure for your program/tables, why having two separate tables when tbl_blood could be decremented directly.
With your current structure, the code below works:
<?php
$pdo = new PDO('mysql:host=localhost;dbname=blood', 'user', 'password');
/* Retrieve values to update */
$result = $pdo->query('
SELECT tb.id, (tb.qty - tbl.blood_quantity) n
FROM tbl_blood tb
LEFT JOIN tbl_blood_list tbl ON (tbl.id = tb.id)');
/* Update */
foreach ($result as $row)
$pdo->query('UPDATE tbl_blood SET qty = '.(int)$row['n'].' WHERE id = '.(int)$row['id'].' LIMIT 1');
?>
Result:
tbl_blood
id|qty
1 13
2 14
3 15
Also:
You may consider harmonizing your field names (e.g. 'blood_qty' and not 'blood_quantity')
Make sure "qty" and "blood_quantity" fields are unsigned integers
Make sure too that both "id" fields are primary keys
You may add a timestamp field in both tables to keep track of updates

How do i update 1 field or 2 of a database table if another table has matching field values?

Let's say I have a table with these columns and values:
id field
-----------
1 0001
2 0002
3 0003
4 0004
5 0005
Then i have this other table with these fields and values:
id tid info_1 field_1 info_2 field_2
---------------------------------------------------
1 1 7 0000 null null
2 2 null null 10 0002
3 3 17 0003 null null
4 4 29 1111 null null
5 6 null null 44 0005
I need an update query that will update the records of table 2, just in the info columns, but only if table 1 has matching fields in table 2 and also only when id of first table and tid of second table match.
So for example table 1 id of 1 and table 2 tid of 1 match but field_1 or field_2 doesn't have the same field number as table 1.
Table 1 id of 2 and table 2 tid of 2 match and field_2 does have a matching number as the field in table one, so i would like to change info_2 of record 2 of table 2 to a number of my choosing. let's just say 50. in all cases the number in info_1 or info_2 will be changed to 50.
Now table 1 id of 3 and table 2 tid of 3 match and field_1 has matching number as the field in table 1, so i need to change info_1 to 50 for that 3rd record in table 2.
In record 4 the id and tid match but no fields match so skip that one.
In record 5 even though field_2 of table 2 matches field in table one, the id of first table and tid of second table do not match, so that 5th record can be skipped.
Here is what i tried so far:
$updatequery1 = "UPDATE table2 LEFT JOIN table1 a ON a.field = field_1 SET info_1 = 50";
$updateresult1 = mysql_query($updatequery1) or die(mysql_error());
So for this first attempt i didn't set id and tid to match, i just went right for looking for field matching. i also didn't incorporate field_2. not even sure if it can all be done in one pass or if multiple queries are needed. in any case, this attempt made all info_1 values equal to 50 even if there were no field matches.
Can someone help me with this query and make both info columns change at same time if possible?
If i were to do a select query for selecting all records that match in table 1 id and table 2 tid, it would be like this, but don't know how to incorporate it into the update query.
SELECT table1.*, table2.*
FROM table1
LEFT JOIN table2
ON table1.id = table2.tid
I can also try and incorporate field matching and it would probably be something like this:
SELECT table1.*, table2.*
FROM table1
LEFT JOIN table2
ON table1.id = table2.tid
WHERE table1.field = table2.field_1
OR table1.field = table2.field_2
But again, wouldn't know how to turn that into an update query so that either info_1 or info_2 changes accordingly.
So to summarize in a quicker way. if id and tid match and field and field_1 match, info_1 should change to 50. if id and tid match and field and field_2 match, info_2 should change to 50
you can use CASE statement in the SET
UPDATE Table2 as T2
JOIN Table1 T1
ON T2.tid = T1.id
set
info_1 = CASE WHEN T2.field_1 = T1.field then 50 ELSE T2.field_1 END ,
info_2 = CASE WHEN T2.field_2 = T1.field then 50 ELSE T2.field_2 END

MYSQL returning duplicate rows

I have a Database table in MYSQL, it looks like this:
Project_ID user_ID name
11 1 fred
11 2 rick
11 1 fred
I want to get the names in the table, but when I display it I get the same name twice because the user_ID 1 appears twice in the table. I tried to display it with GROUP BY and SUM, but I don't want to do it this way. How do I get it not to return duplicate rows?
Use DISTINCT
SELECT DISTINCT user_ID
, verschil_ma
FROM project_uren
WHERE project_ID = 11
GROUP BY user_ID
Point 1 is that should the user be assigned to the project twice?
Point 2 - Use the DISTINCT keyword to return only unique records - http://dev.mysql.com/doc/refman/5.0/en/distinct-optimization.html
SELECT DISTINCT user_ID
FROM TABLE
WHERE Project_id = 11
That will return you 1 and 2 (You won't get 1 twice)
Thanks
$results = // query
$results = array_unique($results);

How to sum the value of all columns in one row except the ID

I need to sum the totals of a row except the first column.
Something similar too:
SELECT SUM( col2 + col3 + col4 +colN)
FROM numbers
WHERE user_name = 'person';
My table will continuously have columns added to it. So I want it to automatically pick up the sum of the new columns too without it needing to be hard coded into the query?
user_name | Col | col2 | Col3 | Col4 + other columns.
person1 | 2 | 3 | 76 | 56 etc. ---------> sum of row
person2 | 6 | 72 | 200 | 13 etc. ---------> sum of row
Thanks in advance for any help!
Not wishing to 'avoid' the question, but it looks like you could do with having a different data structure.
You should consider having a 'users' table with columns for id and user_name, and a new table (e.g. properties) with a row for each of the other columns in your current table (Col1, Col2 ... ColN). The new table would then have a column for user_name to link it to the users table.
That way you'd be able to do something like:
SELECT SUM(property_column) FROM properties WHERE user_name = <RequiredUserName>
I'd also recommend selecting users by ID (i.e. have the properties table with a user_id column, rather than a user_name column), unless you're confident that a user_name is never going to change (and even then...).
Maybe the easiest solution is to do it in PHP:
$res = mysql_query("select * from numbers where user = ...");
while ($row = mysql_fetch_assoc($res)) {
$row['Id'] = 0; // don't want to sum the Id
$sum = array_sum($row); // this is the required sum
....
}
As stated you would be better advised revisiting your database structure,
If you can't and
If you want to do it in PHP you can get the resultset back and then loop through the fields and exclude the fields you don't want then add up everything else, assuming it is of the right type, use mysql_field_type to find those of a specific type.

Categories