Dynamically bind params in $bind_param(); Mysqli

后端 未结 2 1646
悲哀的现实
悲哀的现实 2021-01-23 23:42

I have DB class which is dealing all queries will be made to database I have mysqli prepare working fine. bind_param is also working fine but the problem is I want to define va

2条回答
  •  渐次进展
    2021-01-24 00:04

    For types it's easy. Just use s all the way around.

    There is a much more complex problem: in fact, you cannot bind in a loop, so, have to use call_user_func()

    public function query($sql, $params = array())
    {
        if (!$params)
        {
            return $this->_mysqli->query($sql);
        }
        $stmt = $this->_mysqli->prepare($sql);
        $types = str_repeat("s", count($params));
    
        if (strnatcmp(phpversion(),'5.3') >= 0)
        {
            $bind = array();
            foreach($values as $key => $val)
            {
                $bind[$key] = &$params[$key];
            }
        } else {
            $bind = $values;
        }
    
        array_unshift($bind, $types);
        call_user_func_array(array($stmt, 'bind_param'), $bind);
    
        $stmt->execute();
        return $stmt->get_result();
    }
    

    Note that you shouldn't assign a statement to a local variable and there is no use for the error variable as well. Exceptions are better in every way.

    Looking at the code above you should think twice before turning over PDO, which will take only three lines for such a function:

    public function query($sql, $params = array())
    {
        $stmt = $this->_pdo->prepare($sql);
        $stmt->execute($params);
        return $stmt;
    }
    

    If you have no experience with PDO, here is a PDO tutorial I wrote, from which you will learn that it's most simple yet powerful database API, getting you data in dozens different formats, with very little amount of code.

提交回复
热议问题