2011-07-13 51 views
1

我試圖在出現提示時通過電子郵件將數據從MySQL數據庫發送給用戶。我似乎無法用正確的值將信息傳遞給電子郵件正文。下面是一個代碼示例:需要幫助發送電子郵件中的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 = '[email protected]' 
$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 

然而對於數組中的許多標題仍然存在。感謝您的幫助。

回答

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 = '[email protected]' 
$subject = "Titles"; 
// removed $body= ... 

if (mail($email, $subject, $body)) { 
echo("<p>successfully sent. "</p>"); 
} else { 
echo("<p>delivery failed...</p>"); 
} 
0

首先要說的是:這段代碼對於SQL注入攻擊已經非常成熟。修理它! http://www.learnphponline.com/security/sql-injection-prevention-mysql-php

$ title變量在while while循環中,它不在範圍外。拉到外面。

http://www.dreamincode.net/forums/topic/102020-variable-scope-within-while-loop/

+0

謝謝您的意見,但我仍然面臨着如何讓數組讀取的問題,正如我所提到的。是否有某種打印和搜索選項來查看數組結果? – Presto

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

}