将radiobutton的值发送到DB的不同字段

时间:2010-08-27 03:40:39

标签: php database radio-button field form-submit

我有一个由1组单选按钮组成的提交表单。

<div id="defectclass">
        <input id="def1" type="radio" class="defect" name="defect" value="1"/>S
        <input id="def2" type="radio" class="defect" name="defect" value="1" />A
        <input id="def3" type="radio" class="defect" name="defect" value="1" />B
        <input id="def4" type="radio" class="defect" name="defect" value="1" />C
</div>

除此之外,我在DB表中有4个字段,即:

  1. 取值
  2. A
  3. C
  4. 我想提交后:

        - if def1 are checked send value to field "S"
         - if def2 are checked send value to field "A"
         - if def3 are checked send value to field "B"
         - if def4 are checked send value to field "C"
         - if all not checked or null send to all fields value="0"
    

    我怎么做bcoz我从来没有尝试过这个?

3 个答案:

答案 0 :(得分:0)

  1. 你必须只做一个字段。
  2. 如果您需要数字来表示这些字母,请创建数组
  3. 像这样

    $defects_arr = array(0,"S","A","B","C");
    

    此数组可用于许多任务:

    • 用数字表示这些字母
    • 验证用户rinput
    • 动态构建此输入

    因此,在收到您的POST数据后,只需将其与此数组进行比较:

    $defect = '0';
    if(!empty($_POST['defect'])) {
      $key = array_search($_POST['defect'],$defect_arr));
    }
    

    你将在$ key变量中有一个数字。该号码应存储在数据库中。

答案 1 :(得分:-1)

通过查看表定义中 defect 的可能值

defect VARCHAR(1) 更改为 defect VARCHAR(1) DEFAULT "0"

这简化了代码以插入行/更新列

在php脚本中,解析表单后,添加一个switch语句来决定要更新的列。



// I assumed the row already exists

mysql_connect (localhost, $username, $password);
@mysql_select_db ($database) or die("Error");

$defect = mysql_real_escape_string($_POST["defect"]); //parse the defect field
$id = mysql_real_escape_string$_POST["id"]); //primary key of the table
$flag = True;

if(!empty($_POST['defect']))
{

   switch($defect)
   {
       case "S" : $var = "S";
                  break;
       case "A" : $var = "A";
                  break;
       case "B" : $var = "B";
                  break;
       case "C" : $var = "C";
                  break;
       default : $flag = False;
   }

   if($flag)
   {
      $query = "UPDATE TABLE_NAME SET" + $var + " = '1' WHERE Id = '$id'";
      mysql_query($query);
   }

   mysql_close(); 
}


答案 2 :(得分:-1)

<div id="defectclass">
        <input id="def1" type="radio" class="defect" name="defect['s']" value="1"/>S
        <input id="def2" type="radio" class="defect" name="defect['a']" value="1" />A
        <input id="def3" type="radio" class="defect" name="defect['b']" value="1" />B
        <input id="def4" type="radio" class="defect" name="defect['c']" value="1" />C
</div>

这会给你$ _POST ['缺陷'] ['s'],&amp; tc。所以你会知道要采取哪种更新路径。有关此语法的详细信息,请参阅http://php.net/faq.html