下面是我正在使用的代码,当我提交调查,到达和模式工作而不是事务/复选框时,数据在表(调查)数据库(wdtlabwork)中重新显示为“ on”,该字段也是,与其他两个模式n到达数据库相同,所有字段均为VARCHAR类型。不好意思,如果格式不好我是新来的。注意:我希望数据以汽车,火车或公共汽车的形式返回,但是因为如果用户选中了火车和汽车,它的复选框我希望数据库显示火车和汽车。
HTML
<section id="content">
<form action="connect.php" method="post">
<div class="col-6 col-s-9">
<h3>Available Transportation?</h3>
<input id="trans1" type="checkbox" name="trans[]"><label for ="trans1">Car</label>
<input id="trans2" type="checkbox" name="trans[]"><label for ="trans2">Train</label>
<input id="trans3" type="checkbox" name="trans[]"><label for ="trans3">Bus</label>
<h4>How do you intend to arrive at the Hostel?</h4>
<input id="arrive1" type="radio" value="car" name="arrive"><label for="arrive1">Car</label>
<input id="arrive2" type="radio" value="train" name="arrive"><label for="arrive2">Train</label>
<input id="arrive3" type="radio" value="bus" name="arrive"><label for="arrive3">Bus</label>
<h5>Preferred mode of transport?</h5>
<select name="mode">
<option selected hidden value="">Select Option</option>
<option value="car">Car</option>
<option value="train">Train</option>
<option value="bus">Bus</option>
</select><input type="submit" class="btn btn=primary"></div></section>
PHP
<?php
$arrive = $_POST['arrive'];
$trans = $_POST['trans'];
$mode = $_POST['mode'];
$conn = new mysqli('localhost', 'root','','wdtlabwork');
if ($conn->connect_error){
die('Connection Failed : '.$conn-> connect_error);
}else{
$stmt = $conn->prepare("insert into survey(trans, arrive, mode)
values(?, ?, ?)");
$stmt->bind_param("sss",$trans, $arrive, $mode);
$stmt->execute();
echo "registration successfully...";
$stmt->close();
$conn->close();
}
?>
答案 0 :(得分:1)
您的输入字段没有value=
属性,因此它们默认为on
,如下所述:https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/checkbox#Value
要在POST中获取值,您需要指定值,例如:
<input id="trans1" type="checkbox" name="trans[]" value ="car"><label for ="trans1">Car</label>
<input id="trans2" type="checkbox" name="trans[]" value ="train"><label for ="trans2">Train</label>
<input id="trans3" type="checkbox" name="trans[]" value ="bus"><label for ="trans3">Bus</label>
然后在您的PHP中,您将在$_POST['trans']
中收到一组选定元素。如果您希望将它们(not recommended)加入到数据库中的单个字段中,则可以使用implode(',', $_POST['trans'])
,例如:
$trans = implode(',', $_POST['trans']);
$arrive = $_POST['arrive'];
$mode = $_POST['mode'];