gpt4 book ai didi

php - 如何在页面提交和重新加载后保留复选框的选中状态?

转载 作者:行者123 更新时间:2023-11-29 06:49:36 25 4
gpt4 key购买 nike

我有一个名为 property_amenities 的表,其中包含列; amenity_idamenity_name 其值作为复选框填充在表单上。提交表单后,选中的值将以数组形式插入到 property_listings 表的 property_amenities 列中。

    <?php
$db_host="localhost";
$db_name="cl43-realv3";
$db_user="root";
$db_pass="";

try
{
$DB_con = new PDO("mysql:host={$db_host};dbname={$db_name}",$db_user,$db_pass);
$DB_con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e)
{
$e->getMessage();
}

if (isset($_POST['list_property'])) {
if (isset($_POST['property_amenities'])) {
$property_amenities = implode(",",$_POST['property_amenities']);
}else{ $property_amenities = "";}
}
?>
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="post">
<div class="row clearfix">
<div class="col-lg-12 col-md-6 col-sm-12">
<?php
$stm = $DB_con->prepare("SELECT * FROM property_amenities");
$stm->execute(array(
));

while ($row = $stm->fetch()){
$amenity_id = $row['amenity_id'];
$amenity_name = $row['amenity_name'];
$List[] ="<label class=checkbox> <input type=checkbox name='property_amenities[]' value='$amenity_name'> $amenity_name</label>";
}
$allamenities = $stm->rowCount();

$how_many_chunks = $allamenities/3;

$roster_chunks = array_chunk($List, round($how_many_chunks), true);
?>

<label>Property Amenities</label></small>

<?php
foreach ($roster_chunks as $roster_chunk_key => $roster_chunk_value) {
echo "<div class='col-lg-3 col-md-6 col-sm-12'>";
echo join($roster_chunk_value);
echo '</div>';
}
?>

</div>
</div><!-- end row -->
<button type="submit" class="btn btn-primary" name="list_property" >SUBMIT PROPERTY</button>
</form>
</body>
</html>

上面的代码工作正常。唯一的问题是,当我提交表单并且页面重新加载时,property_amenities 的所有复选框均未选中,我想要的是在页面提交之前选中的复选框被选中。

我怎样才能实现这个目标?

这是 property_amenities 表

--
-- Table structure for table `property_amenities`
--

CREATE TABLE `property_amenities` (
`amenity_id` int(11) NOT NULL,
`amenity_name` varchar(60) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- Dumping data for table `property_amenities`
--

INSERT INTO `property_amenities` (`amenity_id`, `amenity_name`) VALUES
(1, 'Outdoor Balcony'),
(2, 'Outdoor Yard Access'),
(3, 'Large Windows/Natural Light'),
(4, 'Closet Space'),
(5, 'Storage Space'),
(6, 'Laundry in Unit'),
(7, 'Parking Garage'),
(8, 'Ample Parking'),
(9, 'Stainless Steel Appliances'),
(10, 'Open Floor Plan'),
(11, 'Newly Renovated'),
(12, 'Close to Social Amenities'),
(13, 'Swimming Pool'),
(14, 'Courtyard'),
(15, 'Electric Fence'),
(16, 'Intercom'),
(17, 'Patio'),
(18, 'Internet'),
(19, 'Guest Quarters'),
(20, 'Gym / Workout Room'),
(21, 'Kitchenette'),
(22, 'Day And Night Guards'),
(23, 'Borehole'),
(24, 'Street Lights'),
(25, '3 Phase Power'),
(26, 'Dhobi Area'),
(27, 'Wheelchair Access '),
(28, 'Generator');

最佳答案

只需在数据库中检查哪些复选框已被选中,并在回显复选框时将 checked 属性包含在其中:

$checked = (condition) ? "checked" : "";

$List[] = "<label class=checkbox>
<input type=checkbox name='...' value='$amenity_name' $checked/>
$amenity_name
</label>";
<小时/>

编辑:

(响应 comment )

由于每个复选框是设施的名称,因此您可以使用$_POST['property_amenities']轻松找到复选框 提交表单时获得的数组:

  1. 首先,为已检查的设施创建一个空数组 ($amenities_checked)。
  2. 然后,使用 isset($_POST["property_amenities"]) 检查是否有已检查的便利设施。如果是,则更新上面创建的数组的值。
  3. while 循环内,检查设施的名称是否在该数组中。

步骤 1 和 2 的代码:

# Initialise an array to store the amenities checked.
$amenities_checked = [];

# Check whether the form has been submitted.
if (isset($_POST["list_property"])) {
# Initialise the amenities string.
$property_amenities = "";

# Check whether any checkbox has been checked.
if (isset($_POST["property_amenities"])) {
# Update the checked amenities array.
$amenities_checked = $_POST["property_amenities"];

# Implode the array into a comma-separated string.
$property_amenities = implode(",", $amenities_checked);
}
}

第 3 步的代码:

# Iterate over every amenity.
while ($row = $stm -> fetch()) {
# Cache the id and name of the amenity.
list($amenity_id, $amenity_name) = [$row["amenity_id"], $row["amenity_name"]];

# Check whether the name of the amenity is in the array of the checked ones.
$checked = in_array($amenity_name, $amenities_checked) ? "checked" : "";

# Insert the HTML code in the list array.
$List[] = "<label class = checkbox>
<input type = checkbox name = 'property_amenities[]'
value = '$amenity_name' $checked/>
$amenity_name
</label>";
}

完整代码:

(该片段用于折叠代码)

<?php
$db_host = "localhost";
$db_name = "cl43-realv3";
$db_user = "root";
$db_pass = "";

# Create a PDO database connection.
try {
$DB_con = new PDO("mysql:host={$db_host};dbname={$db_name}",$db_user,$db_pass);
$DB_con -> setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch (PDOException $e) {
$e -> getMessage();
}

# Initialise an array to store the amenities checked.
$amenities_checked = [];

# Check whether the form has been submitted.
if (isset($_POST["list_property"])) {
# Initialise the amenities string.
$property_amenities = "";

# Check whether any checkbox has been checked.
if (isset($_POST["property_amenities"])) {
# Update the checked amenities array.
$amenities_checked = $_POST["property_amenities"];

# Implode the array into a comma-separated string.
$property_amenities = implode(",", $amenities_checked);
}
}
?>
<!DOCTYPE html>
<html>
<body>
<form action = "<?= htmlspecialchars($_SERVER["PHP_SELF"]);?>" method = "post">
<div class = "row clearfix">
<div class="col-lg-12 col-md-6 col-sm-12">
<?php
# Fetch the amenities.
$stm = $DB_con->prepare("SELECT * FROM property_amenities");
$stm -> execute([]);

# Iterate over every amenity.
while ($row = $stm -> fetch()) {
# Cache the id and name of the amenity.
list($amenity_id, $amenity_name) = [$row["amenity_id"], $row["amenity_name"]];

# Check whether the name of the amenity is in the array of the checked ones.
$checked = in_array($amenity_name, $amenities_checked) ? "checked" : "";

# Insert the HTML code in the list array.
$List[] = "<label class = checkbox>
<input type = checkbox name = 'property_amenities[]' value = '$amenity_name' $checked/>
$amenity_name
</label>";
}

# Save the number of amenities.
$allamenities = $stm -> rowCount();

# Determine the number of chunks.
$how_many_chunks = $allamenities / 3;
$roster_chunks = array_chunk($List, round($how_many_chunks), true);
?>

<label>Property Amenities</label>

<?php
# Iterate over every chunk.
foreach ($roster_chunks as $roster_chunk_key => $roster_chunk_value) {
echo "<div class='col-lg-3 col-md-6 col-sm-12'>" . join($roster_chunk_value) . "</div>";
}
?>
</div>
</div>
<button type = "submit" class = "btn btn-primary" name = "list_property">SUBMIT PROPERTY</button>
</form>
</body>
</html>

关于php - 如何在页面提交和重新加载后保留复选框的选中状态?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48035552/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com