1

我有 DB 类,它处理所有查询都将对数据库进行我有 mysqli 准备工作正常。bind_param 也可以正常工作,但问题是我想动态定义变量类型。这是我的代码

public function query($sql, $params = array()){
        $this->_error = false;
        if($this->_query = $this->_mysqli->prepare($sql)){
            $x = 1;
            if(count($params)){
                foreach($params as $param){
                    $this->_query->bind_param($x, $param);
                    $x++;
                }
            }

在 PDO 拳头参数定义位置我猜所以这个函数通过设置 X = 1 和 x++ 每次都运行良好,但在bind_param第一个参数定义类型我猜想 php.net 手册说所以如果用户推送我设置的整数值有什么办法 x = i for string x = s 依此类推,适用于所有 4 种类型...

喜欢

if((int)$param->){
    x = i;
}

有什么想法吗?

提前致谢

4

2 回答 2

2

对于类型,这很容易。一直使用就s行了。

还有一个更复杂的问题:事实上,你不能在循环中绑定,所以,必须使用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();
}

请注意,您不应将语句分配给局部变量,并且错误变量也没有用处。例外在各方面都更好。

看上面的代码你应该在翻 PDO 之前三思而后行,这样一个函数只需要三行:

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

如果您没有使用 PDO 的经验,请参阅我编写的PDO 教程,从中您将了解到它是最简单但功能最强大的数据库 API,只需很少的代码即可获得数十种不同格式的数据。

于 2015-09-14T11:01:33.837 回答
0

这是一个可以提供帮助的示例(prepare()函数是类方法)。

function prepare( $query, $bind = array() )
{   
    if ( !$stmt = $this->mysqli->prepare( $query ) ) 
        throw new Exception( 'Query failed: ' . $query . PHP_EOL . $this->mysqli->error );  

    // if $bind is not an empty array shift the type element off the beginning and call stmt->bind_param() with variables to bind passed as reference
    if ( $type = array_shift( $bind ) )
        call_user_func_array( 
            array( $stmt, 'bind_param' ), 
            array_merge( array( $type ), array_map( function( &$item ) { return $item; }, $bind ) ) 
        );

    if ( !$stmt->execute() ) 
        throw new Exception( 'Execute failed: ' . PHP_EOL . $stmt->error );

    // choose what to return here ( 'affected_rows', 'insert_id', 'mysqli_result', 'stmt', 'array' ) 

}

使用示例:

$db->prepare( "SELECT * FROM user WHERE user_name = ? OR user_email = ?", [ 'ss', $user_name, $user_name ] );
于 2015-09-14T16:12:34.773 回答