2015-11-29 78 views
1

我從循環和循環(再次)問題JOINPHP MYSQL INNER對PHP MYSQL INNER JOIN循環和循環再

所以,這是我的代碼:

這裏有兩個表產品股票

他們每個人都包含一排有關係

= id_product

id_product // this is product table 
----------- 
    1 
    2 
    3 

id_product | stock // this is stock table 
--------------------- 
    1  | 2 
    2  | 2 
    3  | 2 

$stockSum = 0; 
$tommorow = mysqli_query($con, 
      "SELECT product.id_product, 
        stock.id_product, 
        stock.stock AS allstock 
      FROM product INNER JOIN stock 
      ON stock.id_product = product.id_product 
      WHERE stock.id_product = product.id_product"); 

while ($dataTommorow = mysqli_fetch_assoc($tommorow)) { 

    $stockSum += $dataTommorow['allstock']; 

    <li><?php echo $stockSum; ?> Stocks</li> // output = 2 
    <li><?php echo $stockSum; ?> Stocks</li> // problem occure it's stacking -> output = 4 
    <li><?php echo $stockSum; ?> Stocks</li> // (again) now become -> output = 6 
} 

那麼,什麼我期望是這樣的:

<li><?php echo $stockSum; ?> Stocks</li> // output = 2 
<li><?php echo $stockSum; ?> Stocks</li> // output = 2 
<li><?php echo $stockSum; ?> Stocks</li> // output = 2 

有什麼錯我的代碼?

在此先感謝

+0

你爲什麼要循環它們?您只需運行一次內連接,然後返回給您的數據集應該爲您提供所需的內容。在相同的數據集上不斷重複地運行連接並不是好的做法,也不應該這樣做。可能存在邏輯問題而不是代碼問題。 – djowinz

+0

你不需要查詢中的where部分。 – Joerg

回答

0
$stockSum = 0; // You are casting to an integer instead cast to an array 
$stockSumArray = array(); // Do this instead 

while($dataTomorrow = mysqli_fetch_assoc($tomorrow)) { 

    // You are appending data to this, so if it returned 2 on the next return 
    // it will add what ever integer was returned to the previous data that 
    // was returned. If it returns a string it will try to cast the string to 
    // an integer and add it together/add on to the existing string 
    $stockSum += $dataTomorrow['allstock']; 


    // !~~~ Instead Do This ~~~! 

    // So instead of appending/adding the returned data together lets 
    // push it to an array so we can later loop through it. 
    array_push($stockSumArray, $dataTomorrow['allstock']; 
} 

for($i = 0; $i < count($stockSumArray); $i++) { 

    // We are going to do exactly what you did before but just echo it out 
    // while looping through the array 

    <li><?php echo $stockSumArray[$i]; ?> Stocks</li> 
} 

你可以得到一個稍微複雜&瘋狂與上面的代碼,但是這是不是你在上面做一個更好的解決方案。希望這會有所幫助,儘量避免在同一個表上使用同一個數據集運行多個JOINS,只需運行一次即可獲取所需的數據。更少的調用,等於更快的頁面加載,反過來等於更高性能的代碼,這反過來等於提高了代碼的可測試性。

+0

感謝您的建議!你搖滾djonwinz! –