[英]How to get sum of mysql column using PHP as usable variable
我一直在尋找如何完成此任務的一周,但沒有一個教程有效 - 我通常會收到一條消息“資源 id 18”。
我正在創建一個銀行模擬游戲。
最終目標:我希望變量“$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();
上面的代碼是出現在每個玩家的“帳戶頁面”上的。 我希望他們的帳戶總和出現在最后一行。 感謝您的幫助,我將在此期間繼續搜索和嘗試。
這里是基於上述的output:
Account Number Account Name Balance
1000083690 Maverick $ 50,000.00
1000083696 WellsFargo $ 50,000.00
1000083697 Wachovia $ 50,000.00
不要使用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";
資源錯誤意味着您沒有表格或權限,或者您嘗試訪問不存在的列
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.