2015-11-29 65 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! –