通过选中的单选按钮更新

时间:2012-02-21 09:39:53

标签: php radio-button

大家好,抱歉我的英文,

我尝试通过选定的单选按钮进行简单的更新,但它无法正常工作。我有一个3< input type ='radio'> while循环中的按钮和每个按钮应该执行我想要过滤的其他内容。

$result=mysql_query("SELECT id FROM table WHERE state=0");
    while ($record=mysql_fetch_array($result)):
        <form  method='post' action=''>
         <input type='radio' name='state' value='1' /> 1
         <input type='radio' name='state' value='2' /> 2
         <input type='radio' name='state' value='3' /> 3

         <input type='submit' value='Send' /> 
        </form>
    endwhile;

如果我选择三个按钮之一并单击“发送”,那么一行(基于ID)应该是更新MySQL数据库:

mysql_query ("UPDATE table SET state=(selected radio button number 1-3) WHERE id=$record[id]");

但是,脚本必须在while循环之外,如果我这样做,它就不起作用,因为脚本无法识别选择了哪个ID。

如果我这样做:

$result=mysql_query("SELECT id FROM table WHERE state=0");
    while ($record=mysql_fetch_array($result)):
        <form  method='post' action=''>
         <input type='radio' name='state' value='$record[id]' /> 1
         <input type='radio' name='state' value='$record[id]' /> 2
         <input type='radio' name='state' value='$record[id]' /> 3

         <input type='submit' value='Send' /> 
        </form>
    endwhile;

然后ID被脚本识别,但我不知道,我怎样才能过滤哪个号码(1,2或3)正在发送到“状态”列的UPDATE查询。对我来说这是一个很大的困境,我无法弄明白。我需要识别ID并过滤所选的数字(1-3)。你能救我一下吗?

1 个答案:

答案 0 :(得分:1)

有两种选择。

<强>首先

$result=mysql_query("SELECT id FROM table WHERE state=0");
while ($record=mysql_fetch_array($result)):
    <form  method='post' action=''>
     <input type='hidden' name='recordId' value='$record[id]' />
     <input type='radio' name='state' value='1' />
     <input type='radio' name='state' value='2' />
     <input type='radio' name='state' value='3' />
     <input type='submit' value='Send' /> 
    </form>
endwhile;

$recordId = (int)$_POST['recordId'];
$state = (int)$_POST['state'];
mysql_query ("UPDATE table SET state=$state WHERE id=$recordId");

<强>第二

$result=mysql_query("SELECT id FROM table WHERE state=0");
<form method='post' action=''>
    while ($record=mysql_fetch_array($result)):
        <input type='radio' name='state[$record[id]]' value='1' />
        <input type='radio' name='state[$record[id]]' value='2' />
        <input type='radio' name='state[$record[id]]' value='3' />
    endwhile;
    <input type='submit' value='Send' /> 
</form>

foreach($_POST['state'] as $key => $val) {
    $recordId = (int)$key;
    $state = (int)$val;
    mysql_query ("UPDATE table SET state=$state WHERE id=$recordId");
}

(请注意,上面的代码可能在语法上不正确,并作为该想法的说明)

此外,混合代码和数据是一种不好的做法;请考虑使用prepared statements

相关问题