php添加基于数组的多个参数

时间:2014-05-09 13:16:42

标签: php arrays

所以目前我得到的代码用于准备有效但效率低的查询,如果查询变大,可能需要扩展。还有更多像这样的代码。这些代码片段的一个例子如下。

//This function is called when preparing statements to prevent sql-injections(1)
//It binds the variables to the prepared statements based on an array.
//$stmt is the prepared statement. $params is an array with the input data.
public function bind($stmt, $params){
    x = count($params);
    $type = $this->getType($params); //simply obtains the types of the params(2)
    if($x == 1){
        $stmt->bind_param($type, $params[0]);
    }elseif($x == 2){
        stmt->bind_param($type, $params[0], $params[1]);
    }elseif($x == 3){
        $stmt->bind_param($type, $params[0], $params[1], $params[2]);
    }else{
        echo "Too much params";      //error if there are more than 3 params.
    }
    return $stmt;
}

来自代码的参考链接以获取额外信息,而不仅仅是因为它只是一个例子。
(1)= How can I prevent SQL injection in PHP?
(2)= http://www.php.net/manual/en/mysqli-stmt.bind-param.php

因此,如果$ params包含超过3个项目,您将看到这将返回错误。所以我一直试图以更有效的方式解决这个问题,因为添加更多的elseif语句效率不高。我用循环尝试了各种各样的东西,但没有好的或有效的结果。这个问题不仅发生在这个bind_param示例中,也发生在其他函数上。

所以我想要一个简单有效的解决方案,根据数组项的数量向函数调用添加一些变量,这些数据项不仅可以应用于此示例。

2 个答案:

答案 0 :(得分:0)

我创建了自己的功能,允许无限制的'值的数量,检查金额是否正确并创建一系列类型。

然而,这个函数有点不同,因为它要求查询字符串和要绑定的对象数组(你需要一个语句)。

function CreateStatement($query, $objects) {
    $questionMarks = substr_count($query, '?');
    if ($questionMarks != count($objects))
        $this->ThrowError('Trying to create statement with invalid data', array(
            'Query' => $query,
            'Objects' => $objects 
        ));


    $statement = $this->prepare($query);

    if (count($objects) != 0) {
        $fields = array();
        $out = array();

        $field_notation = '';
        foreach ($objects as $key => $value) {
            if (is_string($value)) $field_notation .= 's';
            elseif (is_float($value)) $field_notation .= 'd';
            elseif (is_int($value)) $field_notation .= 'i';
            elseif ($value instanceof DateTime) {
                $field_notation .= 's';
                $objects[$key] = $value->format(DateTime::ISO8601);
            }
            else $field_notation .= 'b';
        }

        $fields[] = $field_notation;
        foreach ($objects as &$value) {
            $fields[] = &$value;
        }

        call_user_func_array(array($statement, 'bind_param'), $fields);
    }
    return $statement;
}

答案 1 :(得分:-1)

public function bind($stmt, $params){
  return call_user_func_array(array($stmt, 'bind_param'), $params);
}

http://php.net/call_user_func_array