使用表单

1.1使用一个简单的输入表单

表单页

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>无标题文档</title>
</head>

<body>
<form method="post" action="send.php">
    <input type="text" name="user" />
    <textarea name="message">
        
    </textarea>
    <button type="submit">发送消息</button>
</form>
</body>
</html>

send.php

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>无标题文档</title>
</head>

<body>
<?php
    echo $_POST['user'].":".$_POST['message'];
?>
</body>
</html>

使用超全局变量$_POST访问表单输入的数据

1.2使用数组访问表单

表单页面

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>无标题文档</title>
</head>

<body>
<form method="post" action="send.php">
    1.
    <input type="checkbox" name="products[]" value="yellow"/>
    <br />2.
    <input type="checkbox" name="products[]" value="red"/>
    <br />3.
    <input type="checkbox" name="products[]" value="blue"/>
    <br />
    <button type="submit">提交</button>
</form>
</body>
</html>

send.php

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>无标题文档</title>
</head>

<body>
<?php
    //empty判断是否为空
    if (!empty($_POST['products'])){
        echo "<ul>";
        //foreach遍历数组
        foreach($_POST['products'] as $value) {
            echo "<li>".$value."</li>";
        }
        echo "</ul>";
    }else {
        echo "没有选择";
    }
?>
</body>
</html>

将同类的输入存放到数组中,只需要在变量名后面加个[]就可以。如上述实例中每个input的name属性都是products[];

1.3在单个页面提交表单

猜数字程序

<?php
    $comfirm_num = 42;
    //isset检测变量是否设置
    if(!isset($_POST['guess'])){
        $message = "猜数字游戏";
    } else if (!is_numeric($_POST['guess'])){
        $message = "请输入数字";
    } else if ($_POST['guess'] == $comfirm_num ){
        $message = "正确";
    } else if ($_POST['guess'] > $comfirm_num ){
        $message = "大了";
    } else if ($_POST['guess'] < $comfirm_num ){
        $message = "小了";
    } else {
        $message = "你好强大!";
    }
?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>无标题文档</title>
</head>

<body>
<!--$_SERVER['PHP_SELF'];重载当前页面-->
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
    <input type="text" name="guess"/>
    <button type="submit">提交</button>
</form>
<?php echo $message ?>
</body>
</html>
原文地址:https://www.cnblogs.com/winderby/p/4287786.html