PHP切换案例HTML多选

时间:2017-10-04 18:24:50

标签: javascript php jquery html

我有HTML多选框:

<option value="1">First selection item</option>
<option value="2">Another selection item</option>
<option value="3">Third selection item</option>

通过jQuery我发送POST请求到PHP,然后我检查..:

switch( $value ) :
    case 1:
        $firstItem = 1;
        break;
    case 2:
        $anotherItem = 1;
        break;
    case 3:
        $thirdItem = 1;
        break;
    default:
        $firstItem = $anotherItem = $thirdItem = 0;
endswitch;

则...

$stmt = $this->db->prepare( "UPDATE myTable SET firstItem = ?, anotherItem = ?, thirdItem = ? WHERE Nickname = ?" );
$stmt->execute( array( $firstItem, $anotherItem, $thirdItem, $nickname ) );

我不知道为什么代码不起作用。例如,如果我只选择option with value = 2然后选择$firstItem = NULL$thirdItem = NULL。我认为,如果能够做出很多选择,那将是很愚蠢的。我需要这样做:

  选择

选项1 --- $ firstItem = 1,$ anotherItem = $ thirdItem = 0;

     选择

选项1,2 - $ firstItem = $ anotherItem = 1,$ thirdItem = 0;

是的..如果有任何选择($value = 0),那么$firstItem = $anotherItem = $thirdItem = 0

有什么建议吗?提前致谢。

2 个答案:

答案 0 :(得分:1)

您没有显示$value的位置,但您需要select,并且需要name定义为数组[]才能获得多个PHP端数组中的值。然后,将这些数组值设置为1会更容易。

<select name="something[]" multiple>
    <option value="1">First selection item</option>
    <option value="1">Another selection item</option>
    <option value="1">Third selection item</option>
</select>

现在您可以创建一个0$nickname的默认数组,替换为select中的数组,然后在execute中使用:

$params = array_replace(array(0,0,0,$nickname), $_POST['something']);
$stmt->execute( $params );

答案 1 :(得分:1)

仅切换1个案例,您希望始终将它们设置为0。

这应该这样做:

$firstItem = ($value == 1) ? 1 : 0;
$anotherItem = ($value == 2) ? 1 : 0;
$thirdItem = ($value == 3) ? 1 : 0;

默认情况仅在$value不是1,2或3时运行,这就是您获得空值的原因。此外,交换机只跟随一个分支(或者一个分支和所有后续分支,如果没有中断),所以你应该使用if语句或上面的三级语句。如果您可以将true / false作为变量值(而不是1/0),那么您可以$firstitem = ($value == 1);