简体   繁体   中英

Nested SQL query in PHP while-loop causes Memory Leak - What are some other solutions?

Explanation: I'm attempting to transfer pricing on items from one table to another by comparing code to partnumber and updating the row. The temporary table contains:

code        price
M1          1.23
M2          4.56
M3          7.89

And the second table contains:

partnumber  price
M2          0.00
M3          0.00
M1          0.00

The issue is that I haphazardly nested a mysql_query inside of a while loop, so I was getting a memory leak. I have around 70,000 rows of data and it bombed out at around row 160. T_T How should I go about bringing the data from the temporary table temp_yahooprices to combined_stock? Keep in mind that the server only runs PHP4 so I cannot write prepared PDO statements. The pertinent code is pasted below (and the SQL query is commented out):

//Import Price Data
echo 'Attempting to write Yahoo pricing data...
      <div style="margin:20px; border:1px solid #C0C0C0; overflow:scroll; height:200px; width:50%;">';
$query = "CREATE TABLE temp_yahooprices
          AS (SELECT DISTINCT
          Code AS code, 
          `Sale-price` AS price
          FROM nteproject.ynmdataz
          ORDER BY Code);";
    $result = mysql_query($query) or die('ERROR: Could not create temporary Yahoo pricing table. ' . mysql_error() . '<br>');
$query = "SELECT * FROM temp_yahooprices";
    $result = mysql_query($query);
while($row = mysql_fetch_assoc($result)) {
    $price = $row['price'];
    $code = $row['code'];
    echo '<b>' . $code . '</b> = ' . $price . '<br>';
    //mysql_query("UPDATE combined_stock SET price=$price WHERE partnumber='$code'") or die("There was a problem updating pricing columns: " . mysql_error());
}
echo '</div> Pricing column was successfully created.<br><br>';

You can do it all very nicely with a single SQL statement:

UPDATE combined_stock dest LEFT JOIN (
    SELECT price, code FROM temp_yahooprices
) src ON dest.partnumber = src.code
SET dest.price = src.price

This creates a temporary table called src based on the data from temp_yahooprices. Then it goes through your target table (combined_stock) and updates all elements where the target partnumber equals the source code and updates its price.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM