I have 2 tables with different databases and servers. Table 1 in Server 1 holds the destination and invoice no columns, and Table 2 in Server 2 holds Invoice No and Total columns.
I need to sum up total of all destination. The only matching value of both tables is invoice no, where WS10001 = 10001. The method I'm doing it, is select all values from Server 1 and Table 1, using foreach to loop the values and run the query in Table 2 in Server 2 to sum up the total.
$sql ="select * from table1 group by destination";
$result=mysql_query($sql) or die(mysql_error());
while($myrow=MySQL_fetch_array($result,MYSQL_ASSOC))
{
extract($myrow);
$invno=$myrow[2];
sql2 = "select total from table2 where invoice_no like '%$invno%'";
$result2 = mysqli_query($conn, $sql);
while ($row=mysqli_fetch_row($result2)) {
$value = $row[0];
}
if (destination == "Washington")
{ $wstotal += $value;}
else if (destination == "Hawaii")
{ $wstotal += $value;}
else if (destination == "Budapest")
{ $wstotal += $value;}
}
This method works pretty quick when I use a sample table to run it with 100 records, however when i apply it to the actual tables which has more than 10000 records, it runs for hours to complete it because it has to run a query for every foreach loop.
Is there any ways that can shorten the time to complete it, or can I save down all values from both tables, sum up in php ?
