【问题标题】:Separating array values into multiple arguments将数组值分成多个参数
【发布时间】:2014-05-29 05:29:34
【问题描述】:

我有一个在自定义数据库类中创建的函数。该函数旨在采用参数化 SQL,清理输入并执行它。

我遇到的唯一问题是最后一个未注释的行。我有一个数组类型的变量,但我需要将数组中的每个值作为单独的参数传递。我该怎么做呢?

function do_query($sql, $values){
    if(!isset($this->connect_error)){
        if(tg_debug == true){
            print "Query Executing! <br />";
        }
        $num_vals = count($values);
        $i = 0;
        $type = "";
        while($i < $num_vals){
            if(is_int($values[$i]) == true)
                $type .= "i";
            elseif(is_string($values[$i]) == true)
                $type .= "s";
            $i++;
        }
        $i = 0;
        while($i < $num_vals){
            // security stuff goes here...
            $values[$i] = $this->escape_string($values[$i]);
            $i++;
        }

        $expr = $this->prepare($sql);
        print_r($values);
        // $values is still an array, extract values and convert to a seperate argument
        $expr->bind_param($type, $value);
        //$expr->execute();

    }
}

查询示例:$class-&gt;do_query("INSERT INTOtable(id, value) VALUES (?, ?)", array(3, "This is a test"));

【问题讨论】:

  • 用foreach循环遍历第二个参数,然后在循环中使用bind_param,然后在endforeach之后执行
  • 如果您的意思是:$expr-&gt;bind_param($type); foreach($values as $val){ $expr-&gt;bind_param($val); } 这不起作用。我收到错误参数计数警告。
  • 查看 php.net 上的discussion 了解如何使用 ReflectionClass 来实现这一点。

标签: php arrays function arguments sanitization


【解决方案1】:

使用ReflectionMethod class

...
$bindParamReflection = new \ReflectionMethod($expr, 'bind_param');
$args = $values;
array_unshift($args, $type);
$bindParamReflection->invokeArgs($expr, $args);
...

【讨论】:

    【解决方案2】:

    你可以使用call_user_func_array():

    $args = $values;
    array_unshift($args, $type);
    call_user_func_array(array($expr, 'bind_param'), $args);
    

    splat operator 添加到语言中时,这将大大简化,这应该在 5.6 中发生:

    $exp->bind_param($type, ...$values);
    

    【讨论】:

      猜你喜欢
      • 2016-02-20
      • 2021-11-04
      • 2023-02-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多