所以我正在使用一些从数据库表填充的复选框。看起来像这样。
<form action="" method="post">
<?php
foreach ($chores as $retrieved_search){
?>
<tr>
<td>
<?php echo "<input type='checkbox' id=".$retrieved_search->id." value=".$retrieved_search->image." name='chores[]'>$retrieved_search->name";?>
<?php echo "<input type='text' value='$retrieved_search->name' id='optionName' name='optionName[]' />"?>
</td>
</tr>
<?php
}
?>
</form>
我正在尝试找出一种方法,可以从我当前正在执行的复选框中获取该值,并且工作正常。复选框中的值是图像 URL。
我还需要获取与复选框关联的名称,因此我添加了另一个输入字段,该输入字段填充复选框的名称,然后将其隐藏。
这是我的 php 语句,它从复选框获取 post 值,但我如何才能从同一插入语句的输入字段获取值?
<?php
if(isset($_POST['saveOptions'])) {
global $wpdb;
$table_name = $wpdb->prefix . "chartUsersOptions";
$user_ID = get_current_user_id();
$typeChore = "chore";
$typeBehavior = "behavior";
if(isset($_POST['chores'])){
foreach ($_POST['chores'] as $chores) {
$wpdb->insert( $table_name, array(
'userId' => $user_ID,
'optionImage' => $chores,
'type' => $typeChore,
));
}
}
$msg = "Saved now redirect to 3rd step";
echo $msg;
}
else{
.............
}
?>
编辑:
基于建议,这有效。
<?php
foreach ($chores as $retrieved_search){
echo "<input type='checkbox' value='{$retrieved_search->image}' name='chores[{$retrieved_search->id}]'>{$retrieved_search->name}";
echo "<input type='text' value='{$retrieved_search->name}' name='optionName[{$retrieved_search->id}]'>"
}
?>
还有这个
if(isset($_POST['chores'])){
foreach ($_POST['chores'] as $chores_key => $chores) {
$text_input_value = $_POST['optionName'][$chores_key];
$wpdb->insert( $table_name, array(
'userId' => $user_ID,
'optionImage' => $chores,
'optionName' => $text_input_value,
'type' => $typeChore,
));
}
}
但是 optionName 仍然插入空白。
最佳答案
我不确定确切的问题是什么,但我的猜测是您的复选框与您的输入框不匹配。这是因为未选中的复选框不会发送到服务器,因此您最终可能会得到一个小于输入框数组的复选框数组。
您应该更改您的 html,以便 checkbox-array-key 始终与 input-array-key 匹配,例如:
echo "<input type='checkbox' value='{$retrieved_search->image}' name='chores[{$retrieved_search->id}]'>{$retrieved_search->name}";
echo "<input type='text' value='{$retrieved_search->name}' name='optionName[{$retrieved_search->id}]'>"
另请注意,ID 需要是唯一的,因此我删除了它们,但这可能与您的问题无关。
编辑:要在进行上述更改后获取文本框的值,您可以执行以下操作:
if (isset($_POST['chores'])) {
foreach ($_POST['chores'] as $chores_key => $chores) {
$text_input_value = $_POST['optionName'][$chores_key];
// and the rest of your code
关于php - 每个 php 都有多个 post 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21024222/