首页 > 解决方案 > 表单提交后 $_POST 没有得到值

问题描述

我在同一页面中发布了一些变量,但 $_POST 得到一个空值。
对于 HTML

<form action="" method="POST">
<table><tr>
    <td>Product Name :</td>
    <td><input type="text" class="searchname" name="productName" value=""/></td>
    <td class="pc">Brand Name :</td>
    <td><input type="text" class="searchname" name="brandName" value="" /></td>
<tr>
    <td>Category Name :</td>
    <td><input type="text" class="searchname"  name="category" value="" /></td>
</tr></table>

<input type="submit" class="fdasearch" value="Search" />
    </form>


对于 PHP

if(empty($_POST['productName']) && empty($_POST['brandName']) && empty($_POST['category'])){
    $query = "SELECT * FROM tbl_product";
    $getAllProduct = $db->select($query);
}elseif(isset($_POST) || !empty($_POST)){
    Setting variables from $_POST and make a search
}

我在 productName 中输入“鞋子”,然后我使用了 var_dump(file_get_contents('php://input')),我得到了

字符串(72)“产品名称=鞋子&品牌名称=&类别=&产品名称=&品牌名称=&类别=


当我使用 var_dump($_POST) 时,我得到

数组(3) { ["productName"]=> string(0) "" ["brandName"]=> string(0) "" ["category"]=> string(0) "" }

我不知道 file_get_contents 是如何工作的,但似乎有一个值,但它没有填充 $_POST 变量。我希望 $_POST 有一个值以便进行搜索。

标签: phphttp-post

解决方案


您应该在表单中设置操作,如下所示:

<form action="yourphpfile.php" method="POST">

当我设置动作时,它工作正常。

如果您在同一个文件中,则此代码可以完美运行:

<?php

    if(empty($_POST['productName']) && empty($_POST['brandName']) && empty($_POST['category'])){
        echo "we haven't post request";
    }elseif(isset($_POST) || !empty($_POST)){
        echo "we have post request";
        var_dump($_POST); exit;
    }

?>

<html>
    <body>
        <form action="" method="POST">
            <table><tr>
                <td>Product Name :</td>
                <td><input type="text" class="searchname" name="productName" value=""/></td>
                <td class="pc">Brand Name :</td>
                <td><input type="text" class="searchname" name="brandName" value="" /></td>
            <tr>
                <td>Category Name :</td>
                <td><input type="text" class="searchname"  name="category" value="" /></td>
            </tr></table>

            <input type="submit" class="fdasearch" value="Search" />
        </form>
    </body>
</html>

回报是:

we have post request

    array(3) {
     ["productName"]=> string(4) "dsad" 
     ["brandName"]=> string(4) "dasd" 
     ["category"]=> string(5) "dsada" 
    }

推荐阅读