我有多个复选框,用户应该检查他观看的系列。在我的数据库中,我想在他检查的每个系列中更新“watch”列,其值为“yes”(我已经创建了一个包含所有系列的列)。
HTML代码:
<p>Please check the series you watch:</p>
<form action="2.php" method="post">
Game Of Thrones <input type="checkbox" value="Game Of Thrones" name="series"/><br>
The Big Bang Theory <input type="checkbox" value="The Big Bang Theory" name="series"/><br>
Arrow <input type="checkbox" value="Arrow" name="series"/><br>
<input type="submit" value="Submit">
</form>
send.php:
<?php
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "test";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$series = $_POST['series'];
$sql = "UPDATE data SET watch='yes' WHERE series='$series'";
if ($conn->query($sql) === TRUE) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . $conn->error;
}
$conn->close();
?>
只要用户只检查一个系列就可以工作,但是当他检查两个或更多系列时,它只更新他检查的系列中的一个。
帮助?
答案 0 :(得分:1)
您必须将其作为数组发布,简单示例:
$_POST['fields']
在POST之后,您有一个数组foreach($_POST['fields'] as $field)
$db->query("UPDATE table SET value = 1 WHERE id = '" . $db->real_escape_string($field) . "'");
,其中包含所有选中的复选框值。像这样处理:
{{1}}
答案 1 :(得分:0)
更改您的HTML代码,如:
<p>Please check the series you watch:</p>
<form action="2.php" method="post">
<!-- make the name as an array -->
Game Of Thrones <input type="checkbox" value="Game Of Thrones" name="series[]"/><br>
The Big Bang Theory <input type="checkbox" value="The Big Bang Theory" name="series[]"/><br>
Arrow <input type="checkbox" value="Arrow" name="series[]"/><br>
<input type="submit" value="Submit">
</form>
你的 send.php :
<?php
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "test";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$series = $_POST['series'];
for( $i = 0; $i < count($series); $i ++) {
$sql = "UPDATE data SET watch='yes' WHERE series='$series[$i]'";
if ($conn->query($sql) === TRUE) {
echo "Record updated successfully";
}
else {
echo "Error updating record: " . $conn->error;
}
}
$conn->close();
?>
答案 2 :(得分:0)
将输入名称设置为:
<input type="checkbox" value="Game Of Thrones" name="series[]"/>
那样$_POST['series']
将是一个数组。
如果要更新数据库中的多行,请构建查询字符串,如下所示:
$series = array_map( function( $item ) use ( $conn ) {
return $conn->real_escape_string( $item );
}, $_POST['series'] );
$query = "UPDATE data SET watch='yes' WHERE series IN ( '" . implode( "', '", $series ) . "' )";
答案 3 :(得分:0)
您必须在表单中将复选框定义为数组:
<input type="checkbox" value="Game Of Thrones" name="series[]"/>
<input type="checkbox" value="The Big Bang Theory" name="series[]"/>
<input type="checkbox" value="Arrow" name="series[]"/>
var_dump($_POST['series']);
请参阅PHP reference on this topic。
请注意,您的代码包含 SQL注入漏洞! See how to protect your code properly。最好是使用PHP PDO (PHP Data Objects) extension。