如何使用字符串函数来清理数组变量

时间:2016-08-20 14:39:30

标签: php html string mysqli

我有这个用于html form

的PHP代码
if(isset($_POST['job_title'])){
  foreach($_POST['job_title'] as $selected) {
     $job_title[] = $selected ;
  }
  $job_title = json_encode($job_title);
  $job_title = clean_string($job_title);
}

这就是清除SQL输入的clean_string函数代码

function clean_string($string){
   global $connection;
   $string = trim($string);
   $string = stripslashes($string);
   $string = htmlspecialchars($string);
   $string = htmlentities($string);
   $string = mysqli_real_escape_string($connection,$string);
   return $string;
}

所以当这段代码执行时会导致类似的错误( 期望参数1为字符串,给定数组

如何解决这个问题? 提前致谢

2 个答案:

答案 0 :(得分:0)

山姆大叔可能会争辩说这是你最有可能做的事情:

<?php

    if(isset($_POST['job_title'])){
        foreach($_POST['job_title'] as $selected) {
            $job_title[] = clean_string($selected);
        }
        $job_title  = json_encode($job_title);
    }


    function clean_string($string){
        global $connection;
        $string = trim($string);
        $string = stripslashes($string);
        $string = htmlspecialchars($string);
        $string = htmlentities($string);
        $string = mysqli_real_escape_string($connection,$string);
        return $string;
    }
  

备选方案II:使用array_map()

<?php
    if(isset($_POST['job_title'])){
        foreach($_POST['job_title'] as $selected) {
            $job_title[] = $selected;
        }
        $job_title  = json_encode(array_map("clean_string", $job_title) );
    }


    function clean_string($string){
        global $connection;
        $string = trim($string);
        $string = stripslashes($string);
        $string = htmlspecialchars($string);
        $string = htmlentities($string);
        $string = mysqli_real_escape_string($connection,$string);
        return $string;
    }

答案 1 :(得分:0)

根据您发布的内容,自定义函数 clean_string($ string)看起来接受字符串参数并返回字符串。

你有数组 $ job_title 需要消毒。

您遇到的问题是您在此行中将JSON传递给clean_string($ string):

  $job_title = json_encode($job_title);
  $job_title = clean_string($job_title);  // JSON object is passed.
  

因此,您只需遍历数组$ job_title遍历每个元素,并继续将每个值传递给clean_string()。这可以使用array_map()来实现。

if (isset($_POST['job_title'])) {
    foreach ($_POST['job_title'] as $selected) {
        $job_title[] = $selected ;
    }
    $job_title = array_map("clean_string", $job_title);  // Modify this line
    $job_title = json_encode($job_title);  // Add it here if you need to json encode the sanitized input
}