send radiobutton's value to different fields at DB
i have a submit form that consist of 1 group radio button.
<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>
beside that i have 4 fields at DB table, that is :
- S
- A
- B
- C
i want after submit:
- 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"
how do i do that bcoz i've never try this?
- You have to make just 1 field.
- If you need numbers to represent these letters make an array.
like this
$defects_arr = array(0,"S","A","B","C");
this array can be used in many tasks:
- to represent these letters with numbers
- to validate user rinput
- to build this input dynamically
So, upon receiving your POST data just compare it against this array:
$defect = '0';
if(!empty($_POST['defect'])) {
$key = array_search($_POST['defect'],$defect_arr));
}
and you will have a number in the $key variable. This number should be stored in the database.
<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>
This will give you $_POST['defect']['s'], &tc. so you'll know which update path to take. See http://php.net/faq.html for more about this syntax.
By looking at the possible values of defect
, in your table definition,
change defect VARCHAR(1)
to defect VARCHAR(1) DEFAULT "0"
This simplifies your code to insert row/update columns
in your php script, after parsing the form, add a switch statement to decide which column to update.
// 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();
}
精彩评论