我正在使用PHP while循环。在我的while循环中,我有一个HTML表单。我正在通过ajax将表单值处理到我的PHP中,然后在我的数据库中更新这些值。问题是每当我提交该表单时它只更新我表中的第一个获取的行。我也通过我的表单将唯一的Id传递给ajax但由于某种原因,只有第一行不断更新。
我的Php代码:
<?php
$data = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach ($data as $row) { ?><form>
<input type="text" name="id" value="<?php echo $row['no'] ?>"><br>
<fieldset>
<div>
<label>XYZ Question</label>
</div>
<div>
<input type="radio" name="optradio" value="NO">NO
<input type="radio" name="optradio" value="YES">YES
</div>
</fieldset>
<fieldset>
<div>
<label>XYZ Question</label>
</div>
<div>
<input type="radio" name="optradio1" value="NO">NO
<input type="radio" name="optradio1" value="YES">YES
</div>
</fieldset>
<fieldset>
<div>
<label>XYZ Question</label>
</div>
<div>
<input type="radio" name="optradio2" value="NO">NO
<input type="radio" name="optradio2" value="YES">YES
</div>
</fieldset>
<button type="submit" value="Submit" class="btn">SUBMIT</button>
</form><?php }
我的Ajax代码:
$(document).ready(function(){
var launchAjax = function () { // event handler for button click
$.post(
"inbetween.php/",
{
id: $("[name=id]").val(),
question: $("[name=optradio]:checked").val(),
question1: $("[name=optradio1]:checked").val(),
question2: $("[name=optradio2]:checked").val(),
}
);
}
$(".btn").click(launchAjax);
});
我的PHP SQL查询
<?php
include 'common.php';
$id = filter_input(INPUT_POST, "id", FILTER_SANITIZE_NUMBER_INT);
$question = filter_input(INPUT_POST, "optradio", FILTER_SANITIZE_STRING);
$question1 = filter_input(INPUT_POST, "optradio1", FILTER_SANITIZE_STRING);
$question2 = filter_input(INPUT_POST, "optradio2", FILTER_SANITIZE_STRING);
function getMark($answer, $mark = 1){
$result = 0;
if($answer == 'YES'){
$result = $mark;
}
return $result;
}
$p = 0;
$p += getMark($question, 1);
$p += getMark($question1, .5);
$p += getMark($question2, 2);
$command1 = "UPDATE rating SET marks = marks + '$c', marks= marks/ totalNumber WHERE no = '$id'";
// prepare and executing
$stmt1 = $dbh->prepare($command1);
$result = $stmt1->execute();
?>
您正在使用PDO,但您的while循环似乎使用mysqli方法,如果您选择多行使用fetchAll
,请更新您的代码:
$data = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach ($data as $row) {
$id = $row['no'];
}
更新:如果你想要多个表单,每行一个,你必须这样做:
<?php
$data = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach ($data as $row) { ?><form>
<input type="text" name="id" value="<?php echo $row['no'] ?>"><br>
<fieldset>
<div>
<label>XYZ Question</label>
</div>
<div>
<input type="radio" name="optradio" value="NO">NO
<input type="radio" name="optradio" value="YES">YES
</div>
</fieldset>
<fieldset>
<div>
<label>XYZ Question</label>
</div>
<div>
<input type="radio" name="optradio1" value="NO">NO
<input type="radio" name="optradio1" value="YES">YES
</div>
</fieldset>
<fieldset>
<div>
<label>XYZ Question</label>
</div>
<div>
<input type="radio" name="optradio2" value="NO">NO
<input type="radio" name="optradio2" value="YES">YES
</div>
</fieldset>
<button type="submit" value="Submit" class="btn">SUBMIT</button>
</form><?php }