【发布时间】:2022-01-14 07:32:50
【问题描述】:
我有一个包含 4 个复选框的表单,我希望能够将单击的复选框保存在数据库中,但按顺序,它们会被单击。因此,例如,如果我按 1、3、4、2 的顺序单击复选框,它应该按该顺序保存在数据库中。目前,尽管我以不同的顺序进行了选择,但它只是以默认顺序保存了它。有没有办法做到这一点?
我的表格:
<?php
// Initialize the session
session_start();
// Store the submitted data sent
// via POST method, stored
// Temporarily in $_POST structure.
$_SESSION['system_battery_runout']
= $_POST['system_battery_runout'];
?>
<!DOCTYPE html>
<html lang="en">
<head>
<title>Rank form</title>
</head>
<body>
<div class="div2">
<h1>Which Appliances Do You Use The Most?</h1>
<form action="insert.php" method="post">
<br />
<input type="checkbox" style="height:20px; width:20px;" name="rank_appliances[]" value="Fridge" /><label style="font-size: 20px;"> Fridge</label><br />
<input type="checkbox" style="height:20px; width:20px;" name="rank_appliances[]" value="Stove" /><label style="font-size: 20px;"> Stove</label><br />
<input type="checkbox" style="height:20px; width:20px;" name="rank_appliances[]" value="TV" /><label style="font-size: 20px;"> TV</label><br />
<input type="checkbox" style="height:20px; width:20px;" name="rank_appliances[]" value="Water Tank" /><label style="font-size: 20px;"> Water Tank</label><br />
<br/>
<input type="submit" value="Submit" style="float: right;" >
</form>
</div>
</body>
</html>
插入.php:
<?php
session_start();
?>
<!DOCTYPE html>
<html>
<head>
<title>Insert Page</title>
</head>
</center>
<body>
<div class="div2">
<?php
// serverfullname => localhost
// userfullname => root
// password => empty
// database fullname => staff
$conn = mysqli_connect("localhost", "root", "", "survey");
// Check connection
if ($conn === false) {
die("ERROR: Could not connect. "
. mysqli_connect_error());
}
$system_battery_runout = $_SESSION['system_battery_runout'];
$rank_appliances = $_POST['rank_appliances'];
$checkboxvalue = implode(",", $rank_appliances);
$sql = $conn->prepare("INSERT INTO cus_survey( system_battery_runout,rank_appliances) VALUES (?, ?)");
$sql->bind_param('ss', $system_battery_runout, $checkboxvalue);
if (mysqli_stmt_execute($sql)) {
echo "<h3>Your survey was captured successfully. Thank You!";
} else {
echo "<h3>Sorry, something went wrong</h3> ";
}
// Close connection
mysqli_close($conn);
?>
</div>
</body>
</html>
【问题讨论】:
-
表单元素
system_battery_runout在哪里?数据库架构在哪里?如果您使用 ajax,您可以在单击每个请求时发送单独的请求,或者您希望以传统方式提交一次表单?无论哪种方式,您都需要 javascript -
@ProfessorAbronsius 这只是一种形式,
system_battery_runout只是取自以前的形式。这个表单调用了一个insert.php,它只是将会话数据存储在db中 -
@ProfessorAbronsius 我希望先提交表格然后保存记录
-
创建隐藏输入并在单击/选中复选框时使用 javascript 填充
-
您需要 javascript 来处理操作。这是我找到的解决方案stackoverflow.com/a/60884815/14032355
标签: javascript php html mysql