使用复选框php保存首选项

时间:2014-07-20 15:08:12

标签: php mysql

我试图让用户通过一组复选框保存他们收到的电子邮件的首选项。代码如下:

<label class="checkbox" for="account_updated">
                            <input type="checkbox" name="Alerts[]" value="account_updated"  id="account_updated" data-toggle="checkbox">
                            Account Updated
                        </label>

                        <label class="checkbox" for="account_deauthed">
                            <input type="checkbox" value="account_deauthed" name="Alerts[]" id="account_deauthed" data-toggle="checkbox">
                            Account De-authorized
                        </label>

                        <label class="checkbox" for="charge_succeeded">
                            <input type="checkbox" value="charge_succeeded" name="Alerts[]" id="charge_succeeded" data-toggle="checkbox">
                            Charge Succeeded
                        </label>

使用PHP看起来像:

    if(!empty($_POST['Alerts'])) {
                foreach($_POST['Alerts'] as $index) {
                    $index = implode(',', $_POST['Alerts']);
                }
            }

我的数据库结构如下:

设置表包含:

*setting_id * setting_name     *
*   1       * account.updated  *
*   2       * account.deauthed *
*   *       *                  *

然后是users_to_settings表,其中包含:

*user_id * setting_id * setting_value *
* 1      * 0          * 1             *

这根本不起作用,我不确定我的最佳方向是什么。我该如何存储这些偏好?

谢谢!

1 个答案:

答案 0 :(得分:0)

调整users_to_settings的表,使其具有一个新的字段ID作为主键

CREATE TABLE IF NOT EXISTS `users_to_settings` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `user_id` int(11) NOT NULL,
  `setting_id` int(11) NOT NULL,
  `setting_value` int(11) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;

尝试

$user_id = $_POST['user_id']; // assuming user_id is a hidden input field with the value
$valuesString = "";

if(!empty($_POST['Alerts'])) {
    foreach($_POST['Alerts'] as $selectedOptionIndex => $selectedOptionValue) {
            $valuesString .= "'" . $selectedOptionValue . "',";
    }
}

if ($valuesString != "") {
    $valuesString = substr($valuesString, 0, strlen($valuesString)-1); // removes the ending ,
    $result = mysql_query("SELECT setting_id FROM settings WHERE setting_name IN (".$valuesString.")");
    while($setting = mysql_fetch_array($result)) {
        mysql_query("INSERT INTO users_to_settings VALUES ('".$user_id."','".$setting['setting_id']."','1')");
    }
}

请注意:

$_POST['Alerts'] 

总是会有提交表单时检查的复选框项目