我正在尝试为网站设置一个简单的PHP联系表单,我需要一些帮助修改PHP以从选择菜单中列出多个项目,并希望得到帮助。我是一名平面设计师,而不是开发人员,所以很多事情都是我的头脑。这是问题所在:
<label for="Events[]">Which Event(s) Will You Be Attending?</label>
<div class="input-bg">
<select name="Events[]" size="6" multiple="MULTIPLE" class="required" id="Events[]">
<option value="Wednesday">Portfolio Show June 16</option>
<option value="Thursday">Portfolio Show June 17</option>
<option value="Saturday">Graduation Ceremony</option>
<option value="Saturday Eve">Graduation Party</option>
<option value="Not Sure">Not Sure</option>
<option value="Not Coming">Not Coming</option>
</select>
</div>
这是PHP:
<?php
// CHANGE THE VARIABLES BELOW
$EmailFrom = "Justin@justgooddesign.net";
$EmailTo = "Justin@justgooddesign.net";
$Subject = "Graduation RSVP";
$Name = Trim(stripslashes($_POST['Name']));
$Email = Trim(stripslashes($_POST['Email']));
$Guests = Trim(stripslashes($_POST['Guests']));
$Events = Trim(stripslashes($_POST['Events']));
// prepare email body text
$Body = "";
$Body .= "Name: ";
$Body .= $Name;
$Body .= "\n";
$Body .= "Email: ";
$Body .= $Email;
$Body .= "\n";
$Body .= "Guests: ";
$Body .= $Guests;
$Body .= "\n";
$Body .= "Events: ";
$Body .= $Events;
$Body .= "\n";
// send email
$success = mail($EmailTo, $Subject, $Body, "From: <$EmailFrom>");
// redirect to success page
// CHANGE THE URL BELOW TO YOUR "THANK YOU" PAGE
if ($success){
print "<meta http-equiv=\"refresh\" content=\"0;URL=http://justgooddesign.net/graduation\">";
}
else{
print "<meta http-equiv=\"refresh\" content=\"0;URL=http://justgooddesign.net/graduation/error.html\">";
}
?>
真的很感激任何帮助!
答案 0 :(得分:3)
$ _ POST ['Events']将是一个数组。您可以使用implode()
函数将它们以逗号分隔的字符串连接起来:
$Events = Trim(stripslashes(implode(",", $_POST['Events'])));
或者,您可以使用foreach
语句单独迭代它们。
答案 1 :(得分:3)
当表单中元素的名称以括号结尾时,这意味着PHP会将值放入数组中。换句话说,如果此人选择前两个选项,则$_POST['Events']
的值将与array('Wednesday', 'Thursday')
相同。如果您只想要一个包含所有选项的字符串(例如“星期四星期四”),您可以使用implode()。如果要检查是否存在特定项目,可以使用in_array()。例如:
if (in_array('Wednesday', $_POST['Events']))
{
echo 'You selected Wednesday!';
}
作为旁注,我建议重新考虑允许多项选择的选择控件。许多人不习惯这种行为,并且不会意识到他们可以选择多个。复选框更清晰。
答案 2 :(得分:1)
如果您不想以逗号加入活动但希望以其他方式使用它们,则可以loop through the events进行foreach
循环。而不是
$Body .= $Events;
您可以使用:
foreach($Events as $event) {
$Body .= '- $event\n';
}
那个例子只会在每个事件的前面加上一个' - ',使它看起来像子弹列表。