如何使用PHP post方法将复选框值提交到数据库[重复项]

问题描述 投票:-1回答:1
<div class=" fl-wrap filter-tags">
    <h4>Check</h4>
    <input type="checkbox" value="obj-1" name="obj-1">
    <label for="check-a">Check option 1</label>
    <input type="checkbox" value="obj-2" name="obj-2">
    <label for="check-b">Check option 2</label>
    <input type="checkbox" value="obj-3" name="obj-3">
    <label for="check-c">Check option 3</label>
    <input type="checkbox" value="obj-4" name="obj-4">
    <label for="check-d">Check option 4</label>
    <input type="checkbox" value="obj-5" name="obj-5">
    <label for="check-e">Check option 5</label>
</div>

如果用户检查Check option 5方法需要将其存储到数据库obj-5中。示例用户check obj-1 - obj-3 - obj-5,他们会将所有选中的内容存储到数据库中。PHP代码是这样的:

if($_POST){
    $obj-1 = $_POST['object-1'];
    $obj-2 = $_POST['object-2'];
    $obj-3 = $_POST['object-3'];
    $obj-4 = $_POST['object-4'];
    $obj-5 = $_POST['object-5'];

    $query = $pdo->prepare("INSERT INTO `db`.`tbl` (`post_id`, `obj-1`, `obj-2`, `obj-3`, `obj-4`, `obj-5`,) VALUES (NULL, ?, ?, ?, ?, ?, ?, ?)");

    $query->bindValue(1, $obj-1);
    $query->bindValue(1, $obj-2);
    $query->bindValue(1, $obj-3);
    $query->bindValue(1, $obj-4);
    $query->bindValue(1, $obj-5);
    $query->execute();
    header('Location: view_checked_boxes.php');
}

使用此代码,我收到此错误:

<br />
<b>Notice</b>:  Undefined index: obj-1 in <b>C:\xampp\htdocs\en\acc\checked-box.php</b> on line <b>19</b><br />
<br />
<b>Notice</b>:  Undefined index: obj-2 in <b>C:\xampp\htdocs\en\acc\checked-box.php</b> on line <b>20</b><br />
<br />
<b>Notice</b>:  Undefined index: obj-3 in <b>C:\xampp\htdocs\en\acc\checked-box.php</b> on line <b>21</b><br />
<br />
<b>Notice</b>:  Undefined index: obj-4 in <b>C:\xampp\htdocs\en\acc\checked-box.php</b> on line <b>22</b><br />
<br />
<b>Notice</b>:  Undefined index: obj-5 in <b>C:\xampp\htdocs\en\acc\chekced-box.php</b> on line <b>23</b><br />

哪里出问题了?如果您需要更多信息,请给我帮助。

谢谢。

php pdo
1个回答
0
投票

您不能使用破折号分隔的变量。]​​>

if($_POST){
    $obj1 = $_POST['object-1'];
    $obj2 = $_POST['object-2'];
    $obj3 = $_POST['object-3'];
    $obj4 = $_POST['object-4'];
    $obj5 = $_POST['object-5'];

    $query = $pdo->prepare("INSERT INTO `db`.`tbl` (`post_id`, `obj-1`, `obj-2`, `obj-3`, `obj-4`, `obj-5`,) VALUES (NULL, ?, ?, ?, ?, ?, ?, ?)");

    $query->bindValue(1, $obj1);
    $query->bindValue(1, $obj2);
    $query->bindValue(1, $obj3);
    $query->bindValue(1, $obj4);
    $query->bindValue(1, $obj5);
    $query->execute();
    header('Location: view_checked_boxes.php');
}
© www.soinside.com 2019 - 2024. All rights reserved.