如何在PHP MySQL中存储多个选中的单选值以及复选框


How to store multiple selected values of radio as well as checkboxes in PHP MySQL

我想使用PHP将单选按钮和复选框的多个选定值存储到MySQL数据库中。请让我知道输入按钮的名称和值,以及如何在Mysql查询中传递它?

示例1(单选按钮):

答案1答案2答案2其他原因请注明

例2(复选框)

答案1

答案2

答案3

答案4,请指定

回答5

回答6没有

单选组只能选中一个项目。复选框,可以存储多个选项的值。

我所提供的只是一个例子,而不是一个工作代码。你需要根据你的要求参考和做必要的事情。

首先用下面的示例代码填充输入字段

广播组

<input type="radio" name="radio_group" value="answerswer1">
<input type="radio" name="radio_group" value="answerswer2">
<input type="radio" name="radio_group" value="answerswer3">

复选框组

<input type="checkbox" name="checkbox_group[]" value="answerswer1">
<input type="checkbox" name="checkbox_group[]" value="answerswer2">
<input type="checkbox" name="checkbox_group[]" value="answerswer3">

现在在数据库中创建一个表,如下所示

数据库表

CREATE TABLE IF NOT EXISTS `your_table_name` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `radio_group` enum('answer1','answer2','answer3') NOT NULL DEFAULT 'answer2',  // for radio button
  `checkbox_group` longtext CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL,  // for checkbox serialized data
  PRIMARY KEY (`id`),
) ENGINE=InnoDB  DEFAULT CHARSET=latin1;

在表中插入数据的方法有很多种。在下面的示例

中找到几个选项示例1

$my_radio_value = $_POST['radio_group'];
$my_checkbox_values = $_POST['checkbox_group'];
$checkbox_result = serialize($my_checkbox_values);
// now store $my_radio_value and $checkbox_result in table by running query
INSERT INTO `your_table_name` (radio_group, checkbox_group) VALUES ($my_radio_value, $checkbox_result);
示例2

也可以用json代替serialize

$my_radio_value = $_POST['radio_group'];
$my_checkbox_values = $_POST['checkbox_group'];
$checkbox_result = json_encode($my_checkbox_values);
// now store $my_radio_value and $checkbox_result in table by running query
INSERT INTO `your_table_name` (radio_group, checkbox_group) VALUES ($my_radio_value, $checkbox_result);

示例3

但是直接使用$_POST不是一个好主意。您可以使用mysql_real_escape_string()filter_input()。我个人更喜欢用filter_input()

// using mysql_real_escape_string()
$my_radio_value = mysql_real_escape_string($_POST['radio_group']);
$my_checkbox_values = mysql_real_escape_string($_POST['checkbox_group']);
// using filter_input()
$my_radio_value = filter_input(INPUT_POST, 'radio_group');
$my_checkbox_values = filter_input(INPUT_POST, 'checkbox_group');

// serialize output for checkbox
$checkbox_result = serialize($my_checkbox_values);
// json output for checkbox
$checkbox_result = json_encode($my_checkbox_values);
// now store $my_radio_value and $checkbox_result in table by running query
INSERT INTO `your_table_name` (radio_group, checkbox_group) VALUES ($my_radio_value, $checkbox_result);

我希望这对你有帮助:)