如何使用自定义函数在php中验证post数据

如何使用自定义函数在php中验证post数据,php,Php,我想使用函数验证我的表单帖子,然后将其插入数据库。 我已经能够做到这一点,而无需将其放入函数,但当我将其放入函数时,它将插入而无需验证输入字段。 谢谢;) 这是我的密码: <?php function validate_post(){ global $link; if (isset($_POST['submit'])) { $error = array();

我想使用函数验证我的表单帖子,然后将其插入数据库。 我已经能够做到这一点,而无需将其放入函数,但当我将其放入函数时,它将插入而无需验证输入字段。 谢谢;) 这是我的密码:

  <?php
      function validate_post(){
          global $link;

          if (isset($_POST['submit'])) {           
              $error = array();

              if (!isset($_POST['cat_title']) || empty($_POST['cat_title'])) {
                  $error[] = "field cannot be empty";
              } else {
                  //check if a name only contains letters and whitespace
                  if (!preg_match("/^[a-zA-Z]*$/", $_POST['cat_title'])) {
                      $cat_err = "Only letters and whitespace allowed";
                  }
              }
              //if no errors found
              if (empty($error) && empty($cat_err)) {
                  $cat_title = htmlentities($_POST['cat_title']);
                  $sql = "INSERT INTO categories(cat_title)VALUES('$cat_title')";
                  $insert = mysqli_query($link, $sql);
                  confirm_query($insert);
                  if (mysqli_affected_rows($link) == 1) {
                      $post_info = "Category has been added";
                      redirect("categories.php");
                  } else {
                      $post_info = "Adding category failed";
                  }
              } else {
                  $post_info = "Field cannot be empty";
              }
          }    
      }
  ?>

<?php validate_post(); ?><!-- call validate_post function-->
<!-- ADD CATEGORY FORM -->
<form action="" method="post">
<?php  
    if(isset($post_info))echo $post_info."<br>";
    if(isset($cat_err))echo $cat_err."\n" ?>
    <div class="form-group">
        <label for="cat_tile">Categories</label>
        <input type="text" class="form-control" name="cat_title" id="cat_tile"/>
    </div>
    <div class="form-group">
        <input type="submit" class="btn btn-primary" value="+ Add Category" name="submit" >
     </div>
 </form>

尝试传入$\u POST数组:

if (isset($_POST['submit'])){
    validate_post($_POST)
}

function validate_post($post_array) {
  // your code here
}

Matt首先提出了这个建议,但下面是您将如何做到这一点。

使用您的代码,这是您需要为函数执行的操作的详细说明

<?php
function validate_post($link, $data=[]) {        
    $error = array();

    if (!isset($data['cat_title']) || empty($data['cat_title'])) {
        $error[] = "field cannot be empty";
    } else {
        //check if a name only contains letters and whitespace
        if (!preg_match("/^[a-zA-Z]*$/", $data['cat_title'])) {
            $cat_err = "Only letters and whitespace allowed";
        }
    }
    //if no errors found
    if (empty($error) && empty($cat_err)) {
        $cat_title = htmlentities($data['cat_title']);
        $sql = "INSERT INTO categories(cat_title)VALUES('$cat_title')";
        $insert = mysqli_query($link, $sql);
        confirm_query($insert); //This is another function you created???
        if (mysqli_affected_rows($link) == 1) {
            $post_info = "Category has been added";
            redirect("categories.php");
        } else {
            $post_info = "Adding category failed";
        }
    } else {
        $post_info = "Field cannot be empty";
    }   
}

if (isset($_POST['submit'])) {
    include 'dbfile.php'; // Containing your db link variable if that is how you've done it
    validate_post($link, $_POST); // Usually you need to pass your database link by reference also rather than by global.
}

?>

--html section--

函数不会返回任何信息。您需要告诉它返回错误,然后处理它们。您需要重新构造功能中消息的组织方式,但要点如下:

添加
返回$error到验证函数的末尾

<?php
function validate_post($link, $data=[]) {        
    $error = array();

    if (!isset($data['cat_title']) || empty($data['cat_title'])) {
        $error[] = "field cannot be empty";
    } else {
        //check if a name only contains letters and whitespace
        if (!preg_match("/^[a-zA-Z]*$/", $data['cat_title'])) {
            $cat_err = "Only letters and whitespace allowed";
        }
    }
    //if no errors found
    if (empty($error) && empty($cat_err)) {
        $cat_title = htmlentities($data['cat_title']);
        $sql = "INSERT INTO categories(cat_title)VALUES('$cat_title')";
        $insert = mysqli_query($link, $sql);
        confirm_query($insert); //This is another function you created???
        if (mysqli_affected_rows($link) == 1) {
            $post_info = "Category has been added";
            redirect("categories.php");
        } else {
            $post_info = "Adding category failed";
        }
    } else {
        $post_info = "Field cannot be empty";
    }   
}

if (isset($_POST['submit'])) {
    include 'dbfile.php'; // Containing your db link variable if that is how you've done it
    validate_post($link, $_POST); // Usually you need to pass your database link by reference also rather than by global.
}

?>

--html section--
然后在页面正文中:

<?php $errors = validate_post(); ?><!-- call validate_post function-->
<!-- ADD CATEGORY FORM -->
<form action="" method="post">
   <?php  
   foreach($errors as $error)
   {
     echo $error;
   }
   ?>
    <div class="form-group">

因此,更改validate函数以将所有消息保存到单个数组中,返回该数组,然后处理这些项


函数中声明的变量仅在该函数的范围内“存在”<代码>$post\u info
在函数内部与函数外部没有关系。

下面的代码将帮助您

<?php
function validate_post($link, $data=[]) {        
    $error = array();

    if (!isset($data['cat_title']) || empty($data['cat_title'])) {
        $error[] = "field cannot be empty";
    } else {
        //check if a name only contains letters and whitespace
        if (!preg_match("/^[a-zA-Z]*$/", $data['cat_title'])) {
            $cat_err = "Only letters and whitespace allowed";
        }
    }
    //if no errors found
    if (empty($error) && empty($cat_err)) {
        $cat_title = htmlentities($data['cat_title']);
        $sql = "INSERT INTO categories(cat_title)VALUES('$cat_title')";
        $insert = mysqli_query($link, $sql);
        confirm_query($insert); //This is another function you created???
        if (mysqli_affected_rows($link) == 1) {
            $post_info = "Category has been added";
            redirect("categories.php");
        } else {
            $post_info = "Adding category failed";
        }
    } else {
        $post_info = "Field cannot be empty";
    }   
}

if (isset($_POST['submit'])) {
    include 'dbfile.php'; // Containing your db link variable if that is how you've done it
    validate_post($link, $_POST); // Usually you need to pass your database link by reference also rather than by global.
}

?>

--html section--
<?php
    function validate_post(){
        global $link;

        if (isset($_POST['submit'])) {
            $cat_err = "";
            if (!isset($_POST['cat_title']) || empty($_POST['cat_title']) || $_POST['cat_title']=="") {
                $cat_err = "field cannot be empty";
            } else {
                //check if a name only contains letters and whitespace
                if (!preg_match("/^[a-zA-Z]*$/", $_POST['cat_title'])) {

                    $cat_err = "Only letters and whitespace allowed";
                }

            }

            //if no errors found
            if ($cat_err=="") {
                $cat_title = htmlentities($_POST['cat_title']);
                  $sql = "INSERT INTO categories(cat_title)VALUES('$cat_title')";
                  $insert = mysqli_query($link, $sql);
                  confirm_query($insert);
                  if (mysqli_affected_rows($link) == 1) {
                      $cat_err = "Category has been added";
                      redirect("categories.php");
                  } else {
                      $cat_err = "Adding category failed";
                  }

            } else {
                $cat_err = "Field cannot be empty";
            }
            return $cat_err;
        }
    }
    ?>
    <?php $data=validate_post();echo $data;?><!-- call validate_post function-->
    <!-- ADD CATEGORY FORM -->
    <form action="" method="post">

        <div class="form-group">
            <label for="cat_tile">Categories</label>
            <input type="text" class="form-control" name="cat_title" id="cat_tile"/>
        </div>
        <div class="form-group">
            <input type="submit" class="btn btn-primary" value="+ Add Category" name="submit" >
        </div>

    </form>

数据不会发布到函数,您需要通过引用将数据从
$\u POST
传递到函数,例如
函数foo($bar){if(isset($bar)){}
将post数据传递给函数,正如matt所说,
$\u post
是一个全局变量,您无需将其传递到函数中即可在函数中使用。@matt您的意思是函数validate\u post($cat\u title){if(isset($cat\u title)){}validate\u post(((“cat\u title”)我试着为这个问题写一个合适的答案,但它不能以写的方式完成。我的答案应该是对原始的完全重写。编辑-它神秘地回答的注释被删除了…*他在他的函数中将
$error
声明为数组。我定义
$errors=validate_post()的方式;
不正确。它可以命名为任何名称…函数范围外的变量与函数范围内的变量没有关系。