douyimiao1993 2016-07-07 17:24
浏览 8
已采纳

PHP检查$ _POST是否等于特定值[关闭]

I am trying to get PHP $_POST to show if its equaled or not from a form selection. I have searched/tried different things but can seem to make it work.

Form:

<html>
<body>
<form action="sig_action.php" method="post">
    Phone Lines:<br />
    <select name="phone_op_1">
        <option value="T ">T: Office Phone</option>
        <option value="F ">F: Office Fax</option>
        <option value="TF ">TF: Toll Free Office Phone</option>
        <option value="C ">C: Cell Phone</option>
        <option value="none">none</option>
    </select><br />
    <input type="submit" value="Submit">
</form>
</body>
</html>

Form Handler:

<html>
    <?php
        if ($_POST['phone_op_1'] == 'none') {
        echo 'found none';
        } else {
        echo 'not found none';
        }
    ?>
</html>
  • 写回答

3条回答 默认 最新

  • duanjin9035 2016-07-07 17:32
    关注

    You code should be:

    <html>
        <?php
            if ($_POST['phone_op_1'] == 'none' || empty($_POST['phone_op_1'])) {
            echo 'found none';
            } else {
            echo 'not found none';
            }
        ?>
    </html>
    

    and:

    <html>
    <body>
    <form action="sig_action.php" method="post">
        Phone Lines:<br />
        <select name="phone_op_1">
            <option value="none" selected>none</option>
            <option value="T ">T: Office Phone</option>
            <option value="F ">F: Office Fax</option>
            <option value="TF ">TF: Toll Free Office Phone</option>
            <option value="C ">C: Cell Phone</option>
        </select><br />
        <input type="submit" value="Submit">
    </form>
    </body>
    </html>
    

    If nothing is selected, then the value will not be set. Additionally, if you don't want them to be able to reselect the "none" option, then also add the disabled attribute.


    Side Note:

    While there is technically nothing wrong with checking the value like this in PHP, it can be considered bad practice. A good practice would be to have an array of all the possible values for this option and then check if $_POST['phone_op_1'] existed in that array with in_array(). Then, if it does not exist in that array, assume the value is "none"

    Example:
    $my_array = array(
        'T ',
        'F ',
        'TF ',
        'C '
    );
    
    $result = 'none';
    if (in_array(strtoupper($_POST['phone_op_1']), $my_array)) {
        $output = strtoupper($_POST['phone_op_1']);
    }
    echo $output;
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 企业资源规划ERP沙盘模拟
  • ¥15 前端echarts坐标轴问题
  • ¥15 CMFCPropertyPage
  • ¥15 ad5933的I2C
  • ¥15 请问RTX4060的笔记本电脑可以训练yolov5模型吗?
  • ¥15 数学建模求思路及代码
  • ¥50 silvaco GaN HEMT有栅极场板的击穿电压仿真问题
  • ¥15 谁会P4语言啊,我想请教一下
  • ¥15 这个怎么改成直流激励源给加热电阻提供5a电流呀
  • ¥50 求解vmware的网络模式问题 别拿AI回答