2012-11-14 264 views
1

我有這個代碼,我使用的是爲了首先提取我的數據庫中存在的所有用戶, 然後,我查詢他們每個人,看他們已經計算了多少點。 我的問題是,有點分配查詢提取正確的信息的用戶,但如果用戶沒有任何點,那麼,所有這些用戶不會出現0分,但另一個用戶的積分給他們.. 什麼我的代碼有問題嗎?問題與PHP foreach問題

//here i get all user id's 
$query = 'SELECT * FROM users'; 
    $result = mysql_query($query) or die(mysql_error()); 
    $id_user = array(); 
    $phone = array(); 
    $name = array(); 
    while($row = mysql_fetch_array($result)){ 
     $id_user[]=$row['user_id']; 
     $phone[]=$row['phone']; 
     $name[]=$row['first_name']; 
    } 
//here i get all points collected for each user 
    foreach ($id_user as $user_id) { 
    $queryuser ='SELECT SUM(basket_value) as total_sum FROM retailer WHERE user_id="'.$user_id.'"'; 
    $resultuser = mysql_query($queryuser) or die(mysql_error()); 
    echo "<table>"; 
    while($row = mysql_fetch_array($resultuser)){ 

      $total += $row['total_sum']; 
      echo "<tr>"; 
      echo "<td>"; 
      echo $total; 
      echo "</td>"; 
      echo "<td>"; 
      echo $user_id; 
      echo "</td>"; 
      echo "</tr>"; 
     } 
    } 
    echo "<table>"; 
+0

最後的回聲「

」應該是
jussi

回答

1

您的問題:all those users won't appear 0 points, but another user's points are given to them

因爲你需要初始化$total=0;while($row = mysql_fetch_array($resultuser)){

+0

哦,你說的沒錯,我已經忘記了它:$ –

0

您必須在while循環之前重置$total爲0。

你也可以簡化你的計算,當您加入兩個表:

select u.user_id, u.phone, u.first_name, sum(r.basket_value) as total_sum 
from users u 
left join retailer r on r.user_id = u.user_id 
group by u.user_id, u.phone, u.first_name; 

然後你就可以遍歷結果集只有一次,並保存所有這些額外的查詢。

0

你忘了在foreach循環中初始化$ total。

foreach ($id_user as $user_id) { 
    $total = 0; 
    ...