php - 如何在数据库的不同行中保存多个复选框值
问题描述
我正在处理一个复选框表,提交的数据应该保存在 mysql 数据库中。表中有两列,自动增量 ID 和另一列用于保存复选框的值。
目前,即使我选择多个,它一次只保存一个值,也只会保存最新的一个。这是代码:
report.php
<?php
$active = "report";
require_once 'pages/header.php';
require_once './functions/schema-functions.php';
$course = Schema::getCourse();
$objective = Schema::getObjective();
?>
<form id="addReport" action ='./functions/report-functions.php' method="post">
<table id="table1" class="table">
<?php
echo '<tr><th>Objectives</th>';
for ($i = 0; $i < count($course); $i++) {
echo '<th id = "rotate1">'. $course[$i]->commonName . '</th>';
}
echo '</tr>';
for ($y = 0; $y < count($objective); $y++) {
echo '<tr><th class=row-header>'.$objective[$y]->objective.'</th>';
for ($x = 0; $x < count($course); $x++) {
echo "<td><input name='check[]' type=checkbox value=c".$course[$x]->courseId."-o".$objective[$y]->objectiveId." id=checked></td>";
}
echo '</tr>';
}
?>
</table>
<input type="submit" name= "submit" value= "Submit"/>
报告-functions.php
<?php
require_once 'db-connect.php';
if(isset($_POST['submit'])){
{
$conn = DatabaseConnection::getConnection();
$conn->beginTransaction();
if(isset($_POST['check'])){
foreach($_POST['check'] as $value){
$sql = $conn->prepare("INSERT INTO Report (ColRow) VALUES
('$value')");
}
if ($sql->execute(array( ':checked' => $checked))) {
$conn->commit();
return true;
} else {
$conn->rollback();
return false;
}
}
}
}
?>
我想将多个选中的复选框保存在数据库的不同行中,提交后,我想再次显示表格并选中复选框,用户应该能够进行检查并再次提交数据。
解决方案
为了保存记录,您可以这样尝试:
<?php
if( isset( $_POST['submit'], $_POST['check'] ) ){
try{
require_once 'db-connect.php';
$conn = DatabaseConnection::getConnection();
$sql='insert into `report` ( `colrow` ) values ( :value )';
$stmt = $conn->prepare( $sql );
if( $stmt ){
$conn->beginTransaction();
foreach( $_POST['check'] as $index => $value ) {
$result = $stmt->execute( [ ':value' => $value ] );
if( !$result ) {
throw new Exception( sprintf( 'Failed to execute query %d for %s', $index, $value ) );
}
}
$conn->commit();
exit();
}
}catch( Exception $e ){
$conn->rollback();
exit( $e->getMessage() );
}
}
?>
推荐阅读
- laravel - Laravel:任务有很多子任务,每个子任务可以有很多任务,没有限制
- bash - 使用 shell 脚本在文件中添加行数组
- windows - 在批处理文件中提取第二行输出
- fiware - FIWARE IoT 代理框架:如何在 IoT 代理中定义具有嵌套属性的设备,例如 geo:json?
- amazon-web-services - 不允许使用 post 方法的 Presigned_url
- python - 转置字典列表
- asp.net - 授权和允许匿名 asp.net 核心
- c# - Csharp:根据组合框中的值加载选中的项目列表
- javascript - CKEditor 文件夹系统
- java - 反射错误无法设置字段值