PHP邮件仅显示MySQL数据最后一行的问题求助
Got it, let's figure out why only the last line of your invoice email is showing up. Here are the key issues and fixes to get your full invoice content sending correctly:
Main Problems & Fixes
Uninitialized message variable
You’re using.=to append content to$email_message, but if the variable wasn’t set to an empty string first, PHP can behave unpredictably (even if it doesn’t throw an error, it’s not reliable). Always start with$email_message = '';before appending.Incorrect line breaks
Emails require\r\n(CRLF) for line breaks, not just\n. Some mail clients or servers won’t render\nproperly, which can cause lines to disappear or merge together.Missing Content-Type header
Without specifying that your email is plain text, some clients might misinterpret the content. Adding aContent-Typeheader ensures the email is rendered as intended.Unwanted HTML tags
Your code includes escaped HTML tags like<strong>and<hr>, but your expected output is plain text. These will show as literal text unless you’re sending an HTML email—so I replaced them with plain text alternatives to match your desired result.
Corrected Code
<?php // Assume $row is populated from your MySQL query $email_from = 'info@email.com'; $email_to = $row['email']; $email_subject = "The " . $row['event'] . " Registration"; // Initialize message variable to empty string $email_message = ''; $email_message .= "Dear " . $row['lname'] . " " . $row['fname'] . "\r\n"; $email_message .= "This is a notice that an invoice for your order has been generated on " . $row['reg_date'] . "\r\n"; $email_message .= "Your payment method is: " . $row['payment'] . "\r\n"; $email_message .= "Invoice: " . $row['id'] . "\r\n"; $email_message .= "Status: Unpaid\r\n"; $email_message .= "Invoice Items\r\n"; $email_message .= "Event: " . $row['event'] . "\r\n"; $email_message .= "------------------------\r\n"; // Plain text separator instead of <hr> $email_message .= "Here is your Invoice id: " . $row['ref'] . "\r\n"; // Updated headers with Content-Type for plain text $headers = 'From: ' . $email_from . "\r\n" . 'Reply-To: ' . $email_from . "\r\n" . 'Content-Type: text/plain; charset=UTF-8' . "\r\n" . 'X-Mailer: PHP/' . phpversion(); // Remove @ during testing to see any errors if (mail($email_to, $email_subject, $email_message, $headers)) { echo "Email sent successfully!"; } else { echo "Failed to send email."; } ?>
Bonus: If You Want HTML Email
If you’d prefer to send a formatted HTML email instead of plain text, adjust the code like this:
- Change the
Content-Typeheader totext/html; charset=UTF-8 - Use actual HTML tags (not escaped ones) like
<strong>,<hr>, and<br>for line breaks - Wrap the message in basic HTML structure (e.g.,
<html><body>...</body></html>)
内容的提问来源于stack exchange,提问作者Arnab Dasgupta ADG

