我有一个HTML表单,其中包含许多复选框。当用户单击提交按钮时,将发布已检查的数组,并根据该结果运行查询。 我有一个按钮,允许用户在将保存的结果插入另一个表时保存结果。 但这意味着我需要再次发布表单结果,但它不允许我这样做。我该如何解决这个问题?
答案 0 :(得分:1)
PHP代码
<?php
if (isset($_POST['submit']) && isset($_POST['sport'])) {
$class = $_POST["sport"];
foreach ($class As $key => $value) {
$query = "SELECT *
FROM sport b
join sport a
on a.Tag = b.Name
where a.SportID<> b.SportID and a.Tag = '$value'";
$result = mysqli_query($con, $query) or die("Invalid Query");
while ($row = mysqli_fetch_assoc($result)) {
echo "* $row[Name]\n";
}
}
} else if (isset($_POST['saved'])) {
$arr_class = $_POST["sport"];
foreach ($arr_class As $key => $newvalue) {
$query2 = "INSERT INTO save (Username, Name)
SELECT '$username', b.Name
FROM sport b
JOIN sport a
on a.Tag = b.Name
where a.SportID <> b.SportID
and a.Name = '$newvalue'";
$result2 = mysqli_query($con, $query2) or die('Result could not be saved!');
}
echo 'Result saved!';
}
JS代码
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('.submit-button').click(function (ev) {
var $item = $(this);
var formData = $('form').serialize();
$.ajax({
data: formData+'&submit=submit',
url:'test1.php',
type: "POST",
dataType: "html",
success:function (data) {
console.log(data);
if(confirm('You want to save \n'+data+ ' as your sport')){
$.ajax({
data: formData+'&saved=saved',
url:'test1.php',
type: "POST",
dataType: "html",
success:function (data) {
console.log(data);
}
});
}
}
});
});
});
</script>
HTML代码
<form id="form" action="" method="post">
<input type="checkbox" name="sport[]" value="Football">Football<br>
<input type="checkbox" name="sport[]" value="Rugby">Rugby<br>
<input type="checkbox" name="sport[]" value="Golf">Golf<br>
<input type="checkbox" name="sport[]" value="Basketball">Basketball<br>
<br> <input type="button" class="submit-button btn btn-info" name="submit" value="submit">
<input type="submit" style="display:none;">
</form>