You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PHP邮件正文中使用foreach循环及$endrank++生效问题咨询

Hey there, let's sort out your email body issue for the step league results! The main problems right now are that you're not actually looping through your $leaguedata array to build the results, and the $endrank++ is just being printed as a string instead of incrementing properly. Here's how to fix it:

Fixing Email Body Loop & Rank Increment

First, let's rewrite the email generation part of your code to properly iterate through the league data and calculate ranks correctly:

<?php 
// If admin and league end date has passed, mark league as inactive
if ($info['role'] == "ADMIN") { 
    if ($info['end_date'] < date("Y-m-d")) { 
        // Use prepared statement to avoid SQL injection (critical fix!)
        $endleague = $link->prepare("UPDATE leagues SET active = 0 WHERE joincode=?");
        $endleague->bind_param("s", $joincode);
        $endleague->execute();
        $endleague->close();

        echo "<h3><br/>This league has now ended, results will be sent to everyone via email!</h3>"; 

        // Prepare email content
        $endrank = 1; 
        $subject = "$league_name has ended!"; 
        // Start with a clear header and formatted columns for readability
        $body = "Results are in and these were the final scores:\n\n";
        $body .= "Rank | Username | Most Steps | Average Steps | Total Steps\n";
        $body .= "-----|----------|------------|---------------|-------------\n";

        // Loop through each user in the league data to build the results
        foreach ($leaguedata as $user) {
            // Use sprintf to align columns neatly in plain text
            $body .= sprintf("%4d | %-8s | %10d | %13d | %11d\n", 
                $endrank, 
                $user['nickname'], 
                $user['maxsteps'], 
                $user['average'], 
                $user['total']
            );
            $endrank++; // Increment rank after adding the user's line
        }

        // Set email headers (you might want to use a real sender email instead of localhost)
        $headers = "From: no-reply@yourdomain.com\r\n";
        $headers .= "Content-Type: text/plain; charset=UTF-8\r\n";

        // Send email to each user in the league
        foreach ($leaguedata as $user){ 
            mail($user['email'], $subject, $body, $headers); 
        } 
    } 
} 
?>

Key Fixes & Explanations

  1. Proper Rank Increment: Instead of dumping "$endrank++" as a static string, we initialize $endrank = 1 before the loop, then increment it after adding each user's data. This ensures every user gets a sequential, correct rank.
  2. Loop Through $leaguedata: We added a foreach loop over your pre-built $leaguedata array to iterate through every user's result and append their details to the email body.
  3. Readable Format: The header line and separator make the plain-text email easy to scan. sprintf helps align columns so the results don't look messy.
  4. Security Fix: I replaced your raw SQL UPDATE query with a prepared statement to eliminate SQL injection risks—this is a critical best practice!
  5. Better Email Headers: I updated the headers to use a proper sender address and explicitly set the content type for better compatibility.

Bonus: HTML Email Option (If You Want Prettier Results)

If you'd prefer an HTML email with a table (matching your frontend display), modify the body and headers like this:

// Build HTML table body
$body = "<html><body>
<h2>Results are in for $league_name!</h2>
<table border='1' cellpadding='8'>
<tr>
<th>Rank</th>
<th>Username</th>
<th>Most Steps</th>
<th>Average Steps</th>
<th>Total Steps</th>
</tr>";

foreach ($leaguedata as $user) {
    $body .= "<tr>
    <td>$endrank</td>
    <td>{$user['nickname']}</td>
    <td>{$user['maxsteps']}</td>
    <td>{$user['average']}</td>
    <td>{$user['total']}</td>
    </tr>";
    $endrank++;
}

$body .= "</table></body></html>";

// Update headers for HTML
$headers = "From: no-reply@yourdomain.com\r\n";
$headers .= "Content-Type: text/html; charset=UTF-8\r\n";

内容的提问来源于stack exchange,提问作者user8182265

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 08:03:34