将动态命名的无线电输入的值提交到数据库

时间:2016-05-25 23:06:02

标签: php database wordpress dynamic input

我充其量只是PHP的业余爱好者,但我可以以缓慢的速度瞎扯。 在下面的代码中,我试图获取一些动态生成的单选按钮的值,然后将详细信息提交到数据库。

我正在更新数据库时取得了部分成功,但这只是最后一次。例如以下代码生成2016-03-01,2016-03-02,2016-03-03和2016-03-04的单选按钮。如果我在所有单选按钮上选择“关闭”并仅提交数据库中最后一个日期的更改。

这可能是一种更简单的方法。但是从谷歌搜索到这是我设法与我有限的知识凑合的代码。

感谢您提供任何帮助。

<form action="" id="open_closed" method="post">
<?php
global $wpdb;
$startdate       = '2016-03-01';
$nextdate        = '2016-03-04';
$get_month_dates = $wpdb->get_results("SELECT * FROM wp_vgs_attendance WHERE date >= '$startdate' AND date <= '$nextdate' ");
foreach ($get_month_dates as $month_dates) {
$individual_date = $month_dates->date;
echo '<input type="radio" name="' . $individual_date . '" id="' . $individual_date . '" value="0">Open</input>';
echo '<input type="radio" name="' . $individual_date . '" id="' . $individual_date . '" value="1">Closed</input>';
echo '<input type="hidden" name="date-' . $individual_date . '" id="date-' . $individual_date . '" value="' . $individual_date . '"></input> - ' . $individual_date . '<br><br>';
}

?>
<input name="open_closed" type="submit" class="button button-primary button-large" value="Submit">
</form>
<?php

if (isset($_POST['open_closed'])) {
global $wpdb;
foreach ($get_month_dates as $month_dates) {
    $individual_date = $month_dates->date;
    $name            = $individual_date;
    $open            = $_POST[$name];
    $date            = $_POST['date-' . $individual_date . ''];
}

$wpdb->query("UPDATE wp_vgs_attendance SET closed = '$open' WHERE date = '$date'");

}

1 个答案:

答案 0 :(得分:0)

<form action="" id="open_closed" method="post">
<?php
global $wpdb;
$startdate       = '2016-03-01';
$nextdate        = '2016-03-04';
$get_month_dates = $wpdb->get_results("SELECT * FROM wp_vgs_attendance WHERE date >= '$startdate' AND date <= '$nextdate' ");
foreach ($get_month_dates as $month_dates) {
$individual_date = $month_dates->date;
echo '<input type="radio" name="' . $individual_date . '" id="' . $individual_date . '" value="0">Open</input>';
echo '<input type="radio" name="' . $individual_date . '" id="' . $individual_date . '" value="1">Closed</input>';
echo '<input type="hidden" name="date-' . $individual_date . '" id="date-' . $individual_date . '" value="' . $individual_date . '"></input> - ' . $individual_date . '<br><br>';
}

?>
<input name="open_closed" type="submit" class="button button-primary button-large" value="Submit">
</form>
<?php

if (isset($_POST['open_closed'])) {
global $wpdb;
foreach ($get_month_dates as $month_dates) {
    $individual_date = $month_dates->date;
    $name            = $individual_date;
    $open            = $_POST[$name];
    $date            = $_POST['date-' . $individual_date . ''];

    $wpdb->query("UPDATE wp_vgs_attendance SET closed = '$open' WHERE date = '$date'");
}

}

只需在foreach循环中放置UPDATE查询。