Hi there again,
I found my error, I had improperly set query3. Upon running the corrected code, it ran properly for about 20 records, then errored out:
1 : 25.00.
1 : 20.00.
1 : 25.00.
1 : 25.00.
1 : 25.00.
1 : 5.70.
1 : 25.00.
1 : 50.00.
1 : 15.00.
1014 : 135.00.
102 : 5.00.
1029 : 45.00.
1032 : 70.00.
<abridged>
1545 : 120.00.
1565 : 20.00.
1589 : 10.00.
159 : 25.00.
159 : 20.00Duplicate entry '159' for key 1
The code didn't have problems with multiple user_id of 1, but errored when it got a second user_id of 159. I tried removing the index key from user_id, but after running it again, I got a whole new problem(I know, it seems that's just what I do).
I now have 278 records in donation_totals with the same value for both user_id and total_donated.
user_id | total_donated
981 | 260 <~~~ This shows up in the totals table 278 times.
The very last records that the script calculated was user_id of 981, so it seems that it overwrote all previous user_id and totals with the last user_id that it hit.
8522 : 70.00.
8522 : 50.00.
8577 : 30.00.
8584 : 20.00.
86 : 80.00.
93 : 25.00.
957 : 10.00.
968 : 120.00.
969 : 15.00.
981 : 210.00.
981 : 25.00.
981 : 25.00
You can see that user 981 donated 260.
Can you see a reason why it would overwrite all previous data with the last one calculated?
/*function to completely rebuild total donated table. If the total for the user_id is right, leave it alone, if it's incorrect or missing, update the total.*/
$query1="SELECT user_id, mc_gross FROM donation_paypal ORDER BY user_id ";
$result1=mysql_query($query1) or die (mysql_error());
$numr=mysql_num_rows($result1);
if($numr>0){
while($row1=mysql_fetch_array($result1)){
$donator_id=$row1['user_id'];
$total_donated=$row1['mc_gross'];
echo "<b>. </b>";
echo "<br>".$donator_id." : ".$total_donated;
// I need to check for the existence of the user_id in the totals table. If it exists, check/replace and if it's not there, insert new entry.
$query2="SELECT user_id, total_donated FROM donation_totals WHERE user_id=$donator_id";
$result2=mysql_query($query2) or die (mysql_error());
$numr=mysql_num_rows($result2);
if($numr>0){
// We are updating! Yay!
$query3="UPDATE donation_totals
SET user_id= '$donator_id', total_donated = (
SELECT SUM(mc_gross) FROM donation_paypal WHERE user_id=$donator_id)";
}else{
// We are creating new record, so still yay!
$query3="INSERT INTO donation_totals
SET user_id= '$donator_id', total_donated = (
SELECT SUM(mc_gross) FROM donation_paypal WHERE user_id=$donator_id)";
}
//run the sql insert or update
if($query3) $result3=mysql_query($query3) or die (mysql_error());
}
}