这是我的PHP代码连接到服务器并将每个select标签的每个选项值插入数据库中的表
<?php
$servername = "localhost";
$username = "projectuser";
$password ="";
$dbname = "surveyproject";
//establish connection
$connection = mysqli_connect($servername , $username , $password ,$dbname);
//check for connection errors
if ($connection->connect_error) {
die("Connection failed: " . $connection->connect_error);
}
echo "connected succesfully";
//inserting answers into db
if (isset($_POST['submit'])) {
# code...
for($i=1; $i<3; $i++){
if(isset($_POST['select'])){
$select = $_POST['select'];
$query = "INSERT INTO surveyanswers (answer) VALUES ('$select')";
mysqli_query($connection,$query);
}
}
echo "<script>alert('succesfully submitted answers , thank you')</script>";
mysqli_close($connection);
}
?>
这是我的带有三个选择标签的html代码,我希望将每个select标签的选项中的值选择更新到数据库中的表中
<select class="form-control" name="select">
<option value="Very Good">Very Good</option>
<option value="Good">Good</option>
<option value="Average">Average</option>
<option value="Poor">Poor</option>
<option value="Very Poor">Very Poor</option>
</select>
<select class="form-control" name="select">
<option value="Very Good">Very Good</option>
<option value="Good">Good</option>
<option value="Average">Average</option>
<option value="Poor">Poor</option>
<option value="Very Poor">Very Poor</option>
</select>
<select class="form-control" name="select">
<option value="Very Good">Very Good</option>
<option value="Good">Good</option>
<option value="Average">Average</option>
<option value="Poor">Poor</option>
<option value="Very Poor">Very Poor</option>
</select>
答案 0 :(得分:1)
制作select
数组。
<select class="form-control" name="select[]">
<option value="Very Good">Very Good</option>
<option value="Good">Good</option>
<option value="Average">Average</option>
<option value="Poor">Poor</option>
<option value="Very Poor">Very Poor</option>
</select>
<select class="form-control" name="select[]">
<option value="Very Good">Very Good</option>
<option value="Good">Good</option>
<option value="Average">Average</option>
<option value="Poor">Poor</option>
<option value="Very Poor">Very Poor</option>
</select>
<select class="form-control" name="select[]">
<option value="Very Good">Very Good</option>
<option value="Good">Good</option>
<option value="Average">Average</option>
<option value="Poor">Poor</option>
<option value="Very Poor">Very Poor</option>
</select>
然后你可以遍历数组。由于只发送了最后一个select
,因为它们都具有相同的名称。
之后,通过使用带参数化查询的预准备语句来修复SQL注入问题。 http://php.net/manual/en/mysqli.quickstart.prepared-statements.php
然后你的PHP可能是:
$query = "INSERT INTO surveyanswers (answer) VALUES (?)";
if ($stmt = mysqli_prepare($connection,$query)) {
foreach($_POST['select'] as $selectvalue){
mysqli_stmt_bind_param($stmt, "s", $selectvalue);
mysqli_stmt_execute($stmt);
}
} else {
printf("Error: %s.\n", mysqli_stmt_error($stmt));
}