Передача данных sql в письмо phpmailer
В php и js я совсем новичок и не могу понять как мне передать данные из базы данных в письмо, отправленное через phpmailer. Данные из базы я беру, отсортировывая через get запрос конкретной страницы.
script.js:
document.addEventListener('DOMContentLoaded', function(){
const form = document.getElementById('form');
form.addEventListener('submit', formSend);
async function formSend(e) {
e.preventDefault();
let error = formValidate(form);
let formData = new FormData(form);
if (error === 0) {
form.classList.add('_sending');
let response = await fetch('sendmail.php', {
method: 'POST',
body: formData
});
if (response.ok) {
let result = await response.json();
alert(result.message);
form.reset();
form.classList.remove('_sending');
}
else {
alert("Ошибка2");
form.classList.remove('_sending');
}
}
else {
alert ("ошибка1");
}
}
function formValidate(form) {
let error = 0;
let formReq = document.querySelectorAll('._req');
for (let index = 0; index < formReq.length; index++) {
const input = formReq[index];
formRemoveError(input);
if(input.classList.contains('_email')){
if(emailTest(input)){
formAddError(input);
error++;
}
}
else if(input.getAttribute("type") === "checkbox" && input.checked == false) {
formAddError(input);
error++;
}
else {
if (input.value === '') {
formAddError(input);
error++;
}
}
}
return error;
}
function formAddError(input) {
input.parentElement.classList.add('_error');
input.classList.add('_error');
}
function formRemoveError(input) {
input.parentElement.classList.remove('_error');
input.classList.remove('_error');
}
function emailTest(input) {
return !/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,8})+$/.test(input.value);
}
});
sendmail.php:
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
require 'phpmailer/src/Exception.php';
require 'phpmailer/src/PHPMailer.php';
$mail = new PHPMailer(true);
$mail->CharSet = 'UTF-8';
$mail->IsHTML(true);
$mail->setFrom('@gmail.com');
$mail->addAddress($_POST['email']);
$id = $_GET["id"];
$category = $_GET["category"];
$singles = get_singles_by_category_and_id($id, $category);
foreach ($singles as $single) {
$mail->Subject = 'Title ' $single["title"];
}
$mail->Body = '<h1>Title</h1>';
if(trim(!empty($_POST['surname']))) {
$mail->Body.='<p><strong>Surname:</strong> '.$_POST['surname'].'</p>';
}
if(trim(!empty($_POST['name']))) {
$mail->Body.='<p><strong>Name:</strong> '.$_POST['name'].'</p>';
}
if (!$mail->send()) {
$message = 'Ошибка';
}
else {
$message = 'Данные отправлены!';
}
$response = ['message' => $message];
header('Content-type: application/json');
echo json_encode($response);