我有一个PHP脚本,它从MySQL数据库导入数据,并在while循环的帮助下向所述人发送电子邮件。一切正常,只是我不能在电子邮件正文中使用变量值(而是打印出变量的名称)。例如,如果我写“。$ first_name”。如果这是数据库中条目的名称,我希望电子邮件的正文说“Johan”。
if (isset($_POST['submit'])){
// About database
$user = "user";
$password = "password";
$host = "host";
$dbase = "dbase";
$table = "table";
// Connection to database
$dbc= mysqli_connect($host,$user,$password, $dbase)
or die("Unable to select database");
// Retrieve emails from database
$country = $_POST['country'];
$query= "SELECT email, firstname FROM $table WHERE country = '$country'";
$result= mysqli_query ($dbc, $query)
or die ('Error querying database.');
// Send the email
while ($row = mysqli_fetch_array($result)) {
// Write $first_name for recipients name
$first_name = $row['firstname'];
$last_name = $row['lastname'];
$email = $row['email'];
// About the email
$from = 'info@email.com';
$subject = $_POST['heading'];
$body = $_POST['message'];
$speed = $_POST['speed'];
mail($email, $subject, $body, 'From:' . $from);
echo 'Email sent to: ' . $email. '<br>';
// Delay for speed regulation
sleep(3600/$speed);
}
}
mysqli_close($dbc);
我想问题必须在这里:
$query= "SELECT email, firstname FROM $table WHERE country = '$country'";
$result= mysqli_query ($dbc, $query)
or die ('Error querying database.');
或者在这里:
$first_name = $row['firstname'];
$last_name = $row['lastname'];
$email = $row['email'];
答案 0 :(得分:2)
假设$ _POST [&#39; message&#39;]的内容看起来像......
Dear $first_name,
Greetings, I am a prince from...
PHP不会替换变量。这只是它在内联字符串中的作用(当使用双引号时)。
print("Test... $first_name");
有十几种不同的方法可以解决这个问题......例如你可以:
$body = str_replace('$first_name', $first_name, $body);
请注意使用SINGLE引号。这是为了防止PHP使用$ first_name的值,而是使用文字字符串&#39; $ first_name&#39;。
答案 1 :(得分:0)
在你的行$query= "SELECT email, firstname FROM $table WHERE country = '$country'"
;你也要添加姓氏。