2011-07-10 19 views
1

我一直在尋找一個星期,如何實現這一點,但沒有任何教程已經工作 - 我通常會收到一條消息「資源ID 18」。如何獲得MySQL列的總和使用PHP作爲可用變量

我正在創建一個銀行模擬遊戲。

最終目標:我想要一個變量「$ player_balance」作爲該玩家擁有的所有賬戶餘額的總和,以便在帳戶餘額下顯示在表格的底部。

這是我的代碼,感謝您提供的任何幫助或方向。

function displayMyAccounts(){ 
    global $database, $session; 
    $q = "SELECT game_account_number,game_account_owner,game_account_name,game_account_balance FROM ".TBL_ACCOUNTS." WHERE game_account_owner='".$session->username."'"; 
    $result = $database->query($q); 
    /* Error occurred, return given name by default */ 
    $num_rows = mysql_numrows($result); 
    if(!$result || ($num_rows < 0)){ 
     echo "Error displaying info"; 
     return; 
    } 
    if($num_rows == 0){ 
     echo "Database table empty"; 
     return; 
    } 

    /* Display table contents */ 
    echo "<table align=\"left\" border=\"1\" cellspacing=\"0\" cellpadding=\"3\" width=\"100%\">\n"; 
    echo "<tr><td><b>Account Number</b></td><td><b>Account Name</b></td><td><b>Balance</b></td></tr>\n"; 
    for($i=0; $i<$num_rows; $i++){ 
     $anumber = mysql_result($result,$i,"game_account_number"); 
     $aowner = mysql_result($result,$i,"game_account_owner"); 
     $aname = mysql_result($result,$i,"game_account_name"); 
     $abalance = mysql_result($result,$i,"game_account_balance"); 
     setlocale(LC_MONETARY, 'en_US'); 
     $abalance2 = money_format('%(#10n', $abalance); 

     echo "<tr><td>$anumber</td><td>$aname</td><td>$abalance2</td></tr>\n"; 
    } 
     echo "<tr><td></td><td></td><td>$player_balance</td></tr>\n"; 
    echo "</table><br>\n"; 
} 
displayMyAccounts(); 

上面的代碼是每個玩家的「帳戶頁面」上顯示的代碼。我想讓他們的賬戶總數出現在最後一行。感謝您的幫助,我會在此期間繼續搜索並嘗試。

這裏是基於上述的輸出:

Account Number Account Name Balance 
    1000083690 Maverick $ 50,000.00 
    1000083696 WellsFargo $ 50,000.00 
    1000083697 Wachovia $ 50,000.00 
+0

將是有益的,如果你表現出從MySQL的輸出...你真正取回從你的MySQL查詢的信息嗎? – sdolgy

+0

它看起來像我只是需要在遍歷查詢結果的循環內添加$ abalance到$ player_balance。 – Rafe

回答

0

請勿使用mysql_result()。它很慢,效率低下,以及你正在做的是更好地與mysql_fetch_assoc()完成:

$player_balance = 0; 
// Also, ditch the for loop. This is the typical convention for retrieving results. 
while ($row = mysql_fetch_assoc($result)) { 

    $abalance1 = money_format('%(#10n', $row['game_account_balance']); 
    echo "<tr><td>{$row['game_account_number']}</td><td>{$row['game_account_name']}</td><td>$abalance1</td></tr>\n"; 

    // Now add to the balance 
    $player_balance = $player_balance + $row['game_account_balance']; 
} 
// And output your balance 
$abalance_sum = money_format('%(#10n', $player_balance); 
echo "<tr><td></td><td></td><td>$abalance_sum</td></tr>\n"; 
+0

我改變了代碼,它輸出的「0」 – Kenny

+0

@ Kenny我在上面做了幾處修改。這可能是因爲money_format輸出一個字符串。我在執行循環內部和外部的'money_format()'之前改變了它的內容。 –

+0

試圖找出發生了什麼......我交換了代碼,現在頁面沒有出現......去嘗試一些事情,並可能根據您建議的更改重新發布代碼。 – Kenny

-1

資源錯誤意味着 你沒有表或許可,或正在嘗試訪問的列不存在的

+0

對不起...... IT說資源ID 18.我擁有所有權限並存在表格。將更新我的文章。 – Kenny

+1

不需要SH –

+0

帽子是什麼? –