开发者

Errors when Binding Params (PHP)

开发者 https://www.devze.com 2023-02-13 12:21 出处:网络
I have been trying to get this to work for most of the day to no avail. Basically, I\'m trying to bind_param()\'s inside a foreach() loop, but, when I do, I get the following errors:

I have been trying to get this to work for most of the day to no avail.

Basically, I'm trying to bind_param()'s inside a foreach() loop, but, when I do, I get the following errors:

Warning: mysqli_stmt::bind_param() [mysqli-stmt.bind-param]: Number of variables doesn't match number of parameters in prepared statement in /nfs/domains/domain.com/html/v2/includes/classes/class.Database.php on line 72

Warning: mysqli_stmt::bind_param() [mysqli-stmt.bind-param]: Number of variables doesn't match number of parameters in prepared statement in /nfs/domains/domain.com/html/v2/includes/classes/class.Database.php on line 72

I'm assuming this is due to PHP thinking that there is only one parameter being binded due to the single bind_param() statement inside the loop, thus it doesn't match the number of parameters specified in the prepare statement.

If this is right, how do I correct this?

Code extract (line 19):

public function query($sql, $params) {

    if(!$sobj = $this->conn->prepare($sql)) {

        die('Query Prepare Error (' . $this->conn->mysqli_errno . ') '
            . $this->conn->mysqli_error);

    } else {

        if(!is_array($params)) {

            $params = array_slice(func_get_args(), 1);

        }

        foreach($params as $value) {

            $type = strtolower(gettype($value)开发者_如何学运维);
            $sobj->bind_param($type[0], $value);

        }                      

        $sobj->execute();
        $sobj->bind_result($result);
        $sobj->fetch();

        $sobj->close();

        return $result;

    }

}

Thanks.


mysqli_stmt::bind_param expects you to bind all necessary parameters in one call, not in many successive calls. It would need to be more like this:

$types = '';
foreach($params as $value) {
    $types.= substr(strtolower(gettype($value)), 0, 1);
}
call_user_func_array(array($sobj, 'bind_param'), array_merge(array($types), $params)));

Do look at the warnings regarding call_user_func_array here though.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号