【问题标题】:equaling a loop to a variable before sending it via phpmailer在通过 phpmailer 发送变量之前等于一个变量的循环
【发布时间】:2019-07-07 10:18:39
【问题描述】:

我有一个复选框表单,它被发送到 mail.php 以进行邮寄。所选项目应通过邮件发送。我有一个查询来输出选定的项目。在邮件正文中;要回显从数据库中提取的所有选定项目,我需要将 while 循环等同于一个变量。但我无法做到平等。

<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

require 'PHPMailer/src/Exception.php';
require 'PHPMailer/src/PHPMailer.php';
require 'PHPMailer/src/SMTP.php';

include 'nedmin/netting/database.php';

if (isset($_POST['sendmail'])) {

$city=array_keys($_POST['cities']);

$cities=implode(",",$city);


$query = $db->prepare("SELECT * FROM semt WHERE semt_id IN('".$cities."')");

$query->execute();

while ($statement = $query->fetch(PDO::FETCH_ASSOC)) {

?>
   <td><?php echo $statement["city_name"]?></td>

<?php }


$mail = new PHPMailer;

try {
   /* SMTP parameters. */
   $mail->isSMTP();
   $mail->SMTPKeepAlive = TRUE;   
   $mail->SMTPAuth = TRUE;
   $mail->SMTPSecure = 'tls';

   ...
   ...
   ...
   $mail->isHTML(TRUE);
   $mail->Subject = "Subject";
   $mail->Body = "Selected cities: $......";

   $mail->send();
}
catch (Exception $e)
{
   echo $e->errorMessage();
}
catch (\Exception $e)
{
   echo $e->getMessage();
}
}
?>

【问题讨论】:

  • 不要用答案中的代码替换您的原始代码。读者需要看看答案是什么。
  • WHERE semt_id IN('".$cities."') 不会按预期工作。见:can-i-bind-an-array-to-an-in-condition

标签: php mysql loops phpmailer


【解决方案1】:
$citiesName = [];

while ($statement = $query->fetch(PDO::FETCH_ASSOC)) { ?>
    <td><?php echo $statement["city_name"]?></td>
    <?php $citiesName[] = $statement["city_name"]?>
<?php }

//code ...
$mail->Body = "Selected cities: " . implode(',', $citiesName);

【讨论】:

  • 有效,但仅从数据库中提取第一项。我该怎么办
  • 在这个 显示多个?
  • 然后有什么问题呢? - 我不明白
  • 我需要它通过从数据库中获取来回显表单中的所有选定项目。但它只获取第一个选择,而不是所有选择。
  • 这一切都取决于表单的内容。可以通过条件 - 应该只返回一个结果
【解决方案2】:

连接到一个字符串而不是打印输出。

$city_names = "";
while ($statement = $query->fetch(PDO::FETCH_ASSOC) {
    $city_names .= "<td>{$statement["city_name"]}</td>\n";
}

然后你可以在邮件中使用$city_names

【讨论】:

  • 获取 HTTP 500
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-05-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多