需要帮助在电子邮件中发送MySQL表信息

时间:2011-07-13 19:37:29

标签: php mysql database html-email

我正在尝试在提示时将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

并继续,因为阵列中有很多标题。感谢您的帮助。

4 个答案:

答案 0 :(得分:0)

第一件事:这段代码对于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/

答案 1 :(得分:0)

你有连接问题,

// 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;  

答案 2 :(得分:0)

我建议将文件存储在数组中,如下所示:

$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;

}

答案 3 :(得分:0)

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>");
}