2016-02-12 16 views
1

與stackoverflow開發人員,我贏了我的第一個任務。我正在創建傳入的電子郵件插入到數據庫查詢。當傳入的郵件插入到數據庫時,只有一個電子郵件詳細信息插入到數據庫

這是我的代碼:

#!/usr/bin/php -q 
<?PHP 

/* connect to gmail */ 
$hostname = '{example.org:995/pop3/ssl/novalidate-cert}'; 
$username = 'user'; 
$password = 'pass'; 

/* try to connect */ 
$inbox = imap_open($hostname,$username,$password) or die('Cannot connect to SERVER: ' . imap_last_error()); 


/* grab emails */ 
$emails = imap_search($inbox,'ALL'); 

/* if emails are returned, cycle through each... */ 
if($emails) { 

    /* begin output var */ 
    $output = ''; 

    /* put the newest emails on top */ 
    rsort($emails); 

    /* for every email... */ 
    foreach($emails as $email_number) { 

     /* get information specific to this email */ 
     $overview = imap_fetch_overview($inbox,$email_number,0); 
     $message = imap_fetchbody($inbox,$email_number,2); 

     /* output the email header information */ 
     //$read_status = '<div class="toggler '.($overview[0]->seen ? 'read' : 'unread').'">'; 
     $subject = $overview[0]->subject; 
     $from = $overview[0]->from; 
     $received_date = '<span class="date">on '.$overview[0]->date.'</span>'; 
     //$output.= '</div>'; 

     /* output the email body */ 
     $output= '<div class="body">'.$message.'</div>'; 
    } 

    //echo $output; 
$servername = "localhost"; 
$username = "username "; 
$password = "password "; 
$dbname = "dbname"; 

$conn = mysqli_connect($servername, $username, $password, $dbname) or die("Connection failed: " . mysqli_connect_error()); 

//INSERT INTO DATABASE 

$sql = "INSERT INTO ads(`banner_name`, `hd_image`)VALUES('".$message."', '".$subject."') "; 
$result = mysqli_query($conn, $sql); 
} 

/* close the connection */ 
imap_close($inbox); 

?> 

這是運作良好。我的問題是,當我發送一封新郵件到我的電子郵件地址。查詢將每次執行並插入第一封電子郵件詳細信息。不新發送電子郵件的詳細信請幫我解決這個問題。

另外,如果電子郵件收到附件,我該如何下載?

感謝您的幫助很大

+0

您將從循環中獲得最終的項目(如果有多個電子郵件,您的代碼只會將最後一個插入到數據庫中)。在foreach循環中執行數據庫操作。 – Nikhil

+0

嗨, 我把DB代碼從循環中,但仍然收到我的第一封電子郵件,而不是接收新發送的詳細信息 謝謝! –

+0

*在foreach循環中* –

回答

0

在這裏,你需要使用asort()功能,因爲rsort()將使用順序顛倒,你需要數組的最後一個指標比您將使用asort()用於獲取最新記錄最新指數的最新紀錄。

asort($emails); // it will give you latest email on last index. 
+0

太棒了!感謝你的幫助。 –

+0

@FrankLeen:很高興幫助你現在接受答案,這將有助於他人...... http://stackoverflow.com/questions/35355581/when-incoming-mails-insert-to-database-only-one-email-細節插入到所述數據 – devpro

相關問題