当提示时,我试图从MySQL数据库向用户发送电子邮件值。我似乎无法将信息传递给具有正确值的电子邮件消息体。下面是一个代码示例:
mysql_connect ("host","name","pass") or die (mysql_error());
mysql_select_db ("db_name");
$sql = mysql_query("select * from table_name where id = '$id'");
//$id is previously defined as the users id
while ($row = mysql_fetch_array($sql)){
$title = $row["title"];
}
$email = 'user@email.com'
$subject = "Titles";
$body = "Title: " . $title;
if (mail($email, $subject, $body)) {
echo("<p>successfully sent. "</p>");
} else {
echo("<p>delivery failed...</p>");
}
我已经尝试在while循环中运行数组以获得要显示的标题值,但我似乎无法再次获得这些值以传递到电子邮件消息。
这是假设每个用户都有多个标题被发送给他们。理想情况下,最终的电子邮件消息应该是这样的:
Title: Title1
Title: Title2
Title: Title3
Title: Title4
Title: Title5
无论数组中有多少个标题,并继续。谢谢你的帮助。
mysql_connect ("host","name","pass") or die (mysql_error());
mysql_select_db ("db_name");
$body = ''; // start with empty string
$sql = mysql_query("select * from table_name where id = '$id'");
//$id is previously defined as the users id
while ($row = mysql_fetch_assoc($sql))
{
$body .= 'Title: ' . $row['title'] . "'n";
}
$email = 'user@email.com'
$subject = "Titles";
// removed $body= ...
if (mail($email, $subject, $body)) {
echo("<p>successfully sent. "</p>");
} else {
echo("<p>delivery failed...</p>");
}
首先:这段代码非常适合sql注入攻击。修复它!http://www.learnphponline.com/security/sql-injection-prevention-mysql-php
$title变量在while循环内,它在作用域外不可用。把它拉到外面。
http://www.dreamincode.net/forums/topic/102020-variable-scope-within-while-loop/你有一个连接问题,
// use this code inside the while
$title .= 'Title: ' . $row["title"] . '<br>'; // notice the dot before the equal
//and this line in replace of $body = "Title: " . $title;
$body = $title;
我建议将标题存储在数组中,像这样:
$title = array();
while ($row = mysql_fetch_array($sql)){
// [] adds a new element at the end of an array
$titles[] = $row["title"];
}
然后,准备正文,试试这样:
$body = 'You've gained these titles: ';
foreach( $titles as $title ) {
// keep all titles in separate lines of the email body
$body .= "'nTitle: " . $title;
}