如何在变量中保存foreach循环值并将其打印到循环外?

时间:2017-03-13 10:15:54

标签: php loops foreach concatenation

我正在尝试通过电子邮件发送学生列表。 学生列表数据已保存在数据库中。

所以我根据merchTxnRef

创建了一个检索数据的查询

然后从表/记录中检索该行并将其分配给变量..

然后将变量连接到邮件正文并尝试发送它们。

但我的<tr></tr>在邮件中是空的。我知道这是因为我将foreach循环变量错误地保存到此变量$studentList

如何将foreach循环值保存在变量中并将其打印到循环外

以下是我正在尝试的代码。

$sqlListst = "SELECT * FROM tck_paymentStudents WHERE merchTxnRef LIKE $merchTxnRef'";

$resultListst = $wpdb->get_results($sql) or die(mysql_error());

foreach( $resultListst as $resultsListst ) {

        $merchTxnRef = $resultsListst->merchTxnRef;
        $sudentname = $resultsListst->sudentname;
        $admissionnmbr = $resultsListst->admissionnmbr;
        $purpose = $resultsListst->purpose;
        $amount = $resultsListst->amount;
        $grade = $resultsListst->grade;

        $studentList = '<tr><td>'.$merchTxnRef.'</td><td>'.$sudentname.'</td><td>'.$admissionnmbr.'</td><td>'.$purpose.'</td><td>'.$amount.'</td><td>'.$grade.'</td></tr>';
}
    $mail_body_guest_full  = '<table>';
    $mail_body_guest_full .=  $studentList;
    $mail_body_guest_full .= '</table>';

    $email = 'myemail@examplsite.com';
    $subject = 'Student List';
    $from_guest = 'guestemail@gmail.com';
    $headers_guest = array('From: My Site <'.$from_guest.'>');

    $mail_sent_guest = wp_mail( $email, $subject, $mail_body_guest_full, $headers_guest );

1 个答案:

答案 0 :(得分:1)

1)$studentList.=附近缺少连接点

2)LIKE '".$merchTxnRef."'";附近的查询中缺少单引号

3)根据您的评论$wpdb->get_results($sqlListst)

      $sqlListst = "SELECT * FROM tck_paymentStudents WHERE merchTxnRef LIKE '".$merchTxnRef."'";
      $resultListst = $wpdb->get_results($sqlListst) or die(mysql_error());
       foreach( $resultListst as $resultsListst ) 
       {
        $merchTxnRef = $resultsListst->merchTxnRef;
        $sudentname = $resultsListst->sudentname;
        $admissionnmbr = $resultsListst->admissionnmbr;
        $purpose = $resultsListst->purpose;
        $amount = $resultsListst->amount;
        $grade = $resultsListst->grade;

        $studentList.= '<tr><td>'.$merchTxnRef.'</td><td>'.$sudentname.'</td><td>'.$admissionnmbr.'</td><td>'.$purpose.'</td><td>'.$amount.'</td><td>'.$grade.'</td></tr>';
       }
        $mail_body_guest_full  = '<table><tbody>';
        $mail_body_guest_full .=  $studentList;
        $mail_body_guest_full .= '</tbody></table>';

        $email = 'myemail@examplsite.com';
        $subject = 'Student List';
        $from_guest = 'guestemail@gmail.com';
        $headers_guest = array('From: My Site <'.$from_guest.'>');

        $mail_sent_guest = wp_mail( $email, $subject, $mail_body_guest_full, $headers_guest );