我的网站上有一张表格。问题存储在数据库中,一些变量确定您看到的问题。因此,问题的数量是未知的。问题的代码是这样的:
HTML
<ol class="questions">
<?php
$number = 1;
while($row = mysql_fetch_assoc($result)) {
echo '<li>';
echo '<span><label for="q'.$number.'">'.$row['question'].'</label></span>';
echo '<input id="q'.$number.'" name="q'.$number.'" type="text" value="'.$row['description'].'" onclick="this.value="";this.onclick="test";this.style.color="#000000"; setAttribute("type", "text");" onfocus="if (this.value == "'.$row['description'].'") {this.value = ""; setAttribute("type", "text");}" onblur="if (this.value == "") {this.value = "'.$row['description'].'";setAttribute("type", "text");}"/>';
echo '</li>';
$number++;
};?>
现在,在一些帮助下,我创建了关注AJAX帖子。
$.ajax({
url: "mailer.php",
method: "post",
data: $("#theForm").serialize()
});
如何使用未知数量的问题在PHP中处理此问题?
答案 0 :(得分:0)
最简单的选项:在表单中使用PHP的“数组”语法,而不是将数字硬编码到字段名称中:
<input name="q[1]" value="foo" ...
<input name="q[2]" value="bar" ...
etc..
然后
$_POST['q'][1] -> foo
$_POST['q'][2] -> bar
如果您无法重写表单,那么:
$field_names = preg_grep('/^q\d+$/', array_keys($_POST));
foreach($field_names as $field) {
$val = $_POST[$field];
... do whatever you have to
}
答案 1 :(得分:0)
mailer.php
$to = 'nobody@example.com';
$subject = 'the subject';
$message = 'hello';
$headers = 'From: webmaster@example.com' . "\r\n" .
'Reply-To: webmaster@example.com' . "\r\n" .
'X-Mailer: PHP/' . phpversion();
if(!empty($_POST)){
foreach($_POST as $key => $val){
$message .= "\n".$key.":".$val;
}
}
mail($to, $subject, $message, $headers);
请参阅php mail():http://php.net/manual/en/function.mail.php